text:
To use the JS client, it should be made a dependency of the bower project.
Use `bower install elasticsearch` ( `bower install 'git://github.com/elastic/elasticsearch-js.git#10.0.1'` )

Three separate 'build' (js-files that can be included in the index.html)
exist, next to the native version, there exist special builds for angular and
jQuery.
https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/browser-builds.html

## Example for Elasticsearch in Angular

https://github.com/spalger/elasticsearch-angular-example

## Using the JS client

https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/quick-start.html

Query client using promises instead of callbacks.

    client.search({
      q: 'pants'
    }).then(function (body) {
      var hits = body.hits.hits;
    }, function (error) {
      console.trace(error.message);
    });

# Elasticsearch Server

## Import documents (Simple Way)

Elasticsearch terminology : there is an index (we use 'opendata') and inside
that, there are documents/items (we use 'statement')

To import a file `data/export-minimal.json` into 'opendata', and into an
index/collection 'statement':

    curl -XPOST localhost:9200/opendata/statement/_bulk?pretty --data-binary @data/export-minimal.json

To delete an index again (e.g. to start fresh import)

    curl -XDELETE 'http://localhost:9200/opendata/'

## Configuring Analyzers

Problem : default is to tokenize all input fields.
For some fields it is required to not use the default analyzer, which will
split contents into tokens!

First, to inspect the current mappings of an index (this was also used to
create the basis for the currently in-use mapping file `mapping.json` :

    GET /opendat/_mapping/statement

To *not* use a tokenizer, configure the fields like this :

    "occupation": {
                  "type": "string",
                  "index": "not_analyzed"
               },

We use this for occupation and name of speaker.

## Import documents (Complete Steps)

So, to properly import:

0) delete any old index (if you want to reload)

    curl -XDELETE 'localhost:9200/opendata?pretty'

1) create the index

    curl -XPUT 'localhost:9200/opendata?pretty'

2) create and load the mapping file

    curl -XPUT localhost:9200/opendata/statement/_mapping?pretty -d @data/mapping.json

3) load the json dataset

    curl -XPOST localhost:9200/opendata/statement/_bulk?pretty --data-binary @data/export-minimal.json

## Useful es configuring

CORS-Headers need to be configured so that the js application may issue requests
to the elasticsearch backend (which is running on different port).
For CORS, see https://www.elastic.co/guide/en/elasticsearch/reference/1.4/modules-http.html
Part of the settings below should be default.

Done in `config/elasticsearch.yml`

    # Set my own datadir (completely  optional)
    path.data: /var/elasticsearch

    # Enable cors to be able to talk directly to elasticsearch from our frontend
    http.cors.enabled: true
    http.cors.allow-origin : "*"
    http.cors.allow-methods : OPTIONS, HEAD, GET, POST, PUT, DELETE
    http.cors.allow-headers : X-Requested-With,X-Auth-Token,Content-Type, Content-Length

# JS Implementation

## Elastic search client

https://www.elastic.co/guide/en/elasticsearch/reference/1.4/_executing_searches.html

A more complex query

    "query": {
        "bool": {
            "must": [
                {"term": {"current_party":"grüne"}},
                {"term": {"text":"umweltschutz"}}
            ]
        }

Example of query with aggregations (=facets)

    {"body":{
        "aggregations":
            {"duration":{"histogram":{"field":"duration","interval":180}},
            "party":{"terms":{"field":"current_party"}}},
        "query":{
            "bool":{
                "must":[
                    {"term":{"current_party":"spö"}}
                ]}}}}


text:
setMaskCpf($("#cpf"));

setMaskCelular($("#telefone_responsavel"));

setMaskCelular($("#telefone_responsavel_2"));

setMaskData($("#date_paciente"));

setMaskCep($("#cep_paciente"));

redpajama_set_name: RedPajamaGithub


text:
import logging
import requests
from speculator.utils import date

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def json_to_url(json, symbol):
    """ Converts a JSON to a URL by the Poloniex API

    Args:
        json: JSON data as a list of dict dates, where the keys are
            the raw market statistics.
        symbol: String of currency pair, like a ticker symbol.

    Returns:
        String URL to Poloniex API representing the given JSON.
    """
    start = json[0]['date']
    end = json[-1]['date']
    diff = end - start

    # Get period by a ratio from calculated period to valid periods
    # Ratio closest to 1 is the period
    # Valid values: 300, 900, 1800, 7200, 14400, 86400
    periods = [300, 900, 1800, 7200, 14400, 86400]

    diffs = {}
    for p in periods:
        diffs[p] = abs(1 - (p / (diff / len(json)))) # Get ratio

    period = min(diffs, key=diffs.get) # Find closest period

    url = ('https://poloniex.com/public?command'
           '=returnChartData&currencyPair={0}&start={1}'
           '&end={2}&period={3}').format(symbol, start, end, period)
    return url

def chart_json(start, end, period, symbol):
    """ Requests chart data from Poloniex API

    Args:
        start: Int epoch date to START getting market stats from.
            Note that this epoch is FURTHER from the current date.
        end: Int epoch date to STOP getting market stats from.
            Note that this epoch is CLOSER to the current date.
        period: Int defining width of each chart candlestick in seconds.
            Valid values: 300, 900, 1800, 7200, 14400, 86400
        symbol: String of currency pair, like a ticker symbol.

    Returns:
        Tuple of (JSON data, URL to JSON).
        JSON data as a list of dict dates, where the keys are
        the raw market statistics.
        String URL to Poloniex API representing the given JSON.
    """
    url = ('https://poloniex.com/public?command'
           '=returnChartData&currencyPair={0}&start={1}'
           '&end={2}&period={3}').format(symbol, start, end, period)
    logger.debug(' HTTP Request URL:\n{0}'.format(url))
    json = requests.get(url).json()
    logger.debug(' JSON:\n{0}'.format(json))

    if 'error' in json:
        logger.error(' Invalid parameters in URL for HTTP response')
        raise SystemExit
    elif all(val == 0 for val in json[0]):
        logger.error(' Bad HTTP response.  Time unit too short?')
        raise SystemExit
    elif len(json) < 1: # time to short
        logger.error(' Not enough dates to calculate changes')
        raise SystemExit

    return json, url

def parse_changes(json):
    """ Gets price changes from JSON

    Args:
        json: JSON data as a list of dict dates, where the keys are
            the raw market statistics.

    Returns:
        List of floats of price changes between entries in JSON.
    """
    changes = []
    dates = len(json)
    for date in range(1, dates):
        last_close = json[date - 1]['close']
        now_close = json[date]['close']
        changes.append(now_close - last_close)
    logger.debug('Market Changes (from JSON):\n{0}'.format(changes))
    return changes

def get_gains_losses(changes):
    """ Categorizes changes into gains and losses

    Args:
        changes: List of floats of price changes between entries in JSON.

    Returns:
        Dict of changes with keys 'gains' and 'losses'.
        All values are positive.
    """
    res = {'gains': [], 'losses': []}
    for change in changes:
        if change > 0:
            res['gains'].append(change)
        else:
            res['losses'].append(change * -1)
    logger.debug('Gains: {0}'.format(res['gains']))
    logger.debug('Losses: {0}'.format(res['losses']))
    return res

def get_attribute(json, attr):
    """ Gets the values of an attribute from JSON

    Args:
        json: JSON data as a list of dict dates, where the keys are
            the raw market statistics.
        attr: String of attribute in JSON file to collect.

    Returns:
        List of values of specified attribute from JSON
    """
    res = [json[entry][attr] for entry, _ in enumerate(json)]
    logger.debug('{0}s (from JSON):\n{1}'.format(attr, res))
    return res

def get_json_shift(year, month, day, unit, count, period, symbol):
    """ Gets JSON from shifted date by the Poloniex API

    Args:
        year: Int between 1 and 9999.
        month: Int between 1 and 12.
        day: Int between 1 and 31.
        unit: String of time period unit for count argument.
            How far back to check historical market data.
            Valid values: 'hour', 'day', 'week', 'month', 'year'
        count: Int of units.
            How far back to check historical market data.
        period: Int defining width of each chart candlestick in seconds.
        symbol: String of currency pair, like a ticker symbol.

    Returns: JSON, list of dates where each entry is a dict of raw market data.
    """
    epochs = date.get_end_start_epochs(year, month, day, 'last', unit, count)
    return chart_json(epochs['shifted'], epochs['initial'],
                      period, symbol)[0]


text:
<?php

namespace Oqq\Minc\Serializer\Encoder\Decode;

use Oqq\Minc\Serializer\Exception\DecodingException;
use Oqq\Minc\Serializer\Exception\UnexpectedDecodingFormatException;

/**
 * @author Eric Braun <eb@oqq.be>
 */
interface DecodeInterface
{
    /**
     * @param string $format
     *
     * @return bool
     */
    public function canDecode($format);

    /**
     * @param mixed $data
     * @param string $format
     * @param array $context
     *
     * @return string
     * @throws DecodingException
     * @throws UnexpectedDecodingFormatException
     */
    public function decode($data, $format, array $context = []);
}


text:
package net.izenith.Events;

import org.bukkit.Material;
import org.bukkit.block.BlockState;
import org.bukkit.block.Skull;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;

import net.izenith.Main.Vars;
import net.md_5.bungee.api.ChatColor;

public class InteractListener implements Listener {

	@EventHandler
	public void onClick(final PlayerInteractEvent e) {
		Action a = e.getAction();
		if (a.equals(Action.RIGHT_CLICK_BLOCK)) {
			Player p = e.getPlayer();
			BlockState b = e.getClickedBlock().getState(); //b is the block
			if (b instanceof Skull) { //this test if b is a skull
				if (!(p.isSneaking()) || (p.getItemInHand().getType() == Material.AIR)){
					Skull s = (Skull) b;
					String owner = s.getOwner();
					if (owner == null) {
					} else {
						p.sendMessage(ChatColor.YELLOW + "That is the head of " + ChatColor.GOLD + owner + ChatColor.YELLOW + ".");
						e.setCancelled(true);
					}
				}
			}
		}

		ItemStack item = e.getItem();
		if (e.getPlayer().getLocation().getWorld().getName().equals("spawn") && item != null && e.getItem().getType().equals(Material.NETHER_STAR)) {
			Vars.tpGUI.open(e.getPlayer());
		}

		if(e.getPlayer().getWorld().getName().equals("spawn") && e.getClickedBlock().getType().equals(Material.STONE_BUTTON)){
			e.setCancelled(false);
		}
	}
}


text:
package com.squareup.picasso;

import android.graphics.Bitmap;
import android.net.Uri;
import java.io.IOException;
import java.io.InputStream;

/** A mechanism to load images from external resources such as a disk cache and/or the internet. */
public interface Downloader {
  /**
   * Download the specified image {@code url} from the internet.
   *
   * @param uri Remote image URL.
   * @param localCacheOnly If {@code true} the URL should only be loaded if available in a local
   * disk cache.
   * @return {@link Response} containing either a {@link Bitmap} representation of the request or an
   * {@link InputStream} for the image data. {@code null} can be returned to indicate a problem
   * loading the bitmap.
   * @throws IOException if the requested URL cannot successfully be loaded.
   */
  Response load(Uri uri, boolean localCacheOnly) throws IOException;

  /**
   * Allows to perform a clean up for this {@link Downloader} including closing the disk cache and
   * other resources.
   */
  void shutdown();

  /** Thrown for non-2XX responses. */
  class ResponseException extends IOException {
    public ResponseException(String message) {
      super(message);
    }
  }

  /** Response stream or bitmap and info. */
  class Response {
    final InputStream stream;
    final Bitmap bitmap;
    final boolean cached;
    final long contentLength;

    /**
     * Response image and info.
     *
     * @param bitmap Image.
     * @param loadedFromCache {@code true} if the source of the image is from a local disk cache.
     */
    public Response(Bitmap bitmap, boolean loadedFromCache) {
      if (bitmap == null) {
        throw new IllegalArgumentException("Bitmap may not be null.");
      }
      this.stream = null;
      this.bitmap = bitmap;
      this.cached = loadedFromCache;
      this.contentLength = -1;
    }

    /**
     * Response stream and info.
     *
     * @param stream Image data stream.
     * @param loadedFromCache {@code true} if the source of the stream is from a local disk cache.
     * @deprecated Use {@link Response#Response(java.io.InputStream, boolean, long)} instead.
     */
    @Deprecated @SuppressWarnings("UnusedDeclaration")
    public Response(InputStream stream, boolean loadedFromCache) {
      this(stream, loadedFromCache, -1);
    }

    /**
     * Response image and info.
     *
     * @param bitmap Image.
     * @param loadedFromCache {@code true} if the source of the image is from a local disk cache.
     * @param contentLength The content length of the response, typically derived by the
     * {@code Content-Length} HTTP header.
     * @deprecated The {@code contentLength} argument value is ignored. Use {@link #Response(Bitmap,
     * boolean)}.
     */
    @Deprecated @SuppressWarnings("UnusedDeclaration")
    public Response(Bitmap bitmap, boolean loadedFromCache, long contentLength) {
      this(bitmap, loadedFromCache);
    }

    /**
     * Response stream and info.
     *
     * @param stream Image data stream.
     * @param loadedFromCache {@code true} if the source of the stream is from a local disk cache.
     * @param contentLength The content length of the response, typically derived by the
     * {@code Content-Length} HTTP header.
     */
    public Response(InputStream stream, boolean loadedFromCache, long contentLength) {
      if (stream == null) {
        throw new IllegalArgumentException("Stream may not be null.");
      }
      this.stream = stream;
      this.bitmap = null;
      this.cached = loadedFromCache;
      this.contentLength = contentLength;
    }

    /**
     * Input stream containing image data.
     *

     * If this returns {@code null}, image data will be available via {@link #getBitmap()}.
     */
    public InputStream getInputStream() {
      return stream;
    }

    /**
     * Bitmap representing the image.
     *

     * If this returns {@code null}, image data will be available via {@link #getInputStream()}.
     */
    public Bitmap getBitmap() {
      return bitmap;
    }

    /** Content length of the response. Only valid when used with {@link #getInputStream()}. */
    public long getContentLength() {
      return contentLength;
    }
  }
}


text:
package org.copperengine.core.test.tranzient.simple;

import org.copperengine.core.Interrupt;

public class IssueClassCastExceptionWorkflow extends AbstractIssueClassCastExceptionWorkflow {

    private static final long serialVersionUID = 1L;

    @Override
    protected void callAbstractExceptionSimulation0(String partnerLink) {
        throw new RuntimeException("Simulate exception.");
    }

    @Override
    protected void callAbstractExceptionSimulation1() throws Interrupt {
        throw new RuntimeException("Simulate exception.");
    }

    @Override
    protected void callAbstractExceptionSimulation2(String partnerLink) {
        throw new RuntimeException("Simulate exception.");
    }

    @Override
    public void main() throws Interrupt {
        this.callPartner(100);
        getData().error = false;
        getData().done = true;
    }
}


text:
// <copyright file="CubicBezier2D.cs" company="Shkyrockett" >
//     Copyright © 2005 - 2020 Shkyrockett. All rights reserved.
// </copyright>
// <author id="shkyrockett">Shkyrockett</author>
// <license>
//     Licensed under the MIT License. See LICENSE file in the project root for full license information.
// </license>
// <summary></summary>
// <remarks></remarks>

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using static Engine.Operations;
using static Engine.Polynomials;
using static System.Math;

namespace Engine
{
    /// <summary>
    /// Cubic or 3rd degree Bézier curve.
    /// </summary>
    /// <structure>Engine.Geometry.CubicBezier2D</structure>
    /// <remarks>
    /// <para>http://paulbourke.net/geometry/bezier/index.html
    /// http://pomax.github.io/bezierinfo/</para>
    /// </remarks>
    [DataContract, Serializable]
    [GraphicsObject]
    [DisplayName(nameof(CubicBezier2D))]
    [XmlType(TypeName = "Bezier-Cubic")]
    [DebuggerDisplay("{ToString()}")]
    public class CubicBezier2D
        : Shape2D, IEquatable<CubicBezier2D>
    {
        #region Fields
        /// <summary>
        /// Position 1 x-coordinate.
        /// </summary>
        private double ax;

        /// <summary>
        /// Position 1 y-coordinate.
        /// </summary>
        private double ay;

        /// <summary>
        /// Tangent 1 x-coordinate.
        /// </summary>
        private double bx;

        /// <summary>
        /// Tangent 1 y-coordinate.
        /// </summary>
        private double by;

        /// <summary>
        /// Tangent 2 x-coordinate.
        /// </summary>
        private double cx;

        /// <summary>
        /// Tangent 2 y-coordinate.
        /// </summary>
        private double cy;

        /// <summary>
        /// Position 2 x-coordinate.
        /// </summary>
        private double dx;

        /// <summary>
        /// Position 2 y-coordinate.
        /// </summary>
        private double dy;
        #endregion Fields

        #region Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="CubicBezier2D"/> class.
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public CubicBezier2D()
            : this(0, 0, 0, 0, 0, 0, 0, 0)
        { }

        /// <summary>
        /// Initializes a new instance of the <see cref="CubicBezier2D"/> class from a <see cref="QuadraticBezier2D"/>.
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <param name="c"></param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public CubicBezier2D(Point2D a, Point2D b, Point2D c)
        {
            (ax, ay, bx, by, cx, cy, dx, dy) = Conversions.QuadraticBezierToCubicBezierTuple(a.X, a.Y, b.X, b.Y, c.X, c.Y);
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="CubicBezier2D"/> class from a <see cref="QuadraticBezier2D"/>.
        /// </summary>
        /// <param name="tuple"></param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public CubicBezier2D((double aX, double aY, double bX, double bY, double cX, double cY) tuple)
            : this(tuple.aX, tuple.aY, tuple.bX, tuple.bY, tuple.cX, tuple.cY)
        { }

        /// <summary>
        /// Initializes a new instance of the <see cref="CubicBezier2D"/> class from a <see cref="QuadraticBezier2D"/>.
        /// </summary>
        /// <param name="ax"></param>
        /// <param name="ay"></param>
        /// <param name="bx"></param>
        /// <param name="by"></param>
        /// <param name="cx"></param>
        /// <param name="cy"></param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public CubicBezier2D(double ax, double ay, double bx, double by, double cx, double cy)
        {
            (this.ax, this.ay, this.bx, this.by, this.cx, this.cy, dx, dy) = Conversions.QuadraticBezierToCubicBezierTuple(ax, ay, bx, by, cx, cy);
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="CubicBezier2D"/> class.
        /// </summary>
        /// <param name="a">Position1</param>
        /// <param name="b">Tangent1</param>
        /// <param name="c">Position2</param>
        /// <param name="d">Tangent2</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public CubicBezier2D(Point2D a, Point2D b, Point2D c, Point2D d)
            : this(a.X, a.Y, b.X, b.Y, c.X, c.Y, d.X, d.Y)
        { }

        /// <summary>
        /// Initializes a new instance of the <see cref="CubicBezier2D"/> class.
        /// </summary>
        /// <param name="ax">Position1</param>
        /// <param name="ay">Position1</param>
        /// <param name="bx">Tangent1</param>
        /// <param name="by">Tangent1</param>
        /// <param name="cx">Position2</param>
        /// <param name="cy">Position2</param>
        /// <param name="dx">Tangent2</param>
        /// <param name="dy">Tangent2</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public CubicBezier2D(double ax, double ay, double bx, double by, double cx, double cy, double dx, double dy)
        {
            this.ax = ax;
            this.ay = ay;
            this.bx = bx;
            this.by = by;
            this.cx = cx;
            this.cy = cy;
            this.dx = dx;
            this.dy = dy;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="CubicBezier2D"/> class.
        /// </summary>
        /// <param name="tuple"></param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public CubicBezier2D((double aX, double aY, double bX, double bY, double cX, double cY, double dX, double dY) tuple)
            : this(tuple.aX, tuple.aY, tuple.bX, tuple.bY, tuple.cX, tuple.cY, tuple.dX, tuple.dY)
        { }
        #endregion Constructors

        #region Deconstructors
        /// <summary>
        /// Deconstruct this <see cref="CubicBezier2D"/> to a Tuple.
        /// </summary>
        /// <param name="ax"></param>
        /// <param name="ay"></param>
        /// <param name="bx"></param>
        /// <param name="by"></param>
        /// <param name="cx"></param>
        /// <param name="cy"></param>
        /// <param name="dx"></param>
        /// <param name="dy"></param>
        public void Deconstruct(out double ax, out double ay, out double bx, out double by, out double cx, out double cy, out double dx, out double dy)
        {
            ax = this.ax;
            ay = this.ay;
            bx = this.bx;
            by = this.by;
            cx = this.cx;
            cy = this.cy;
            dx = this.dx;
            dy = this.dy;
        }
        #endregion Deconstructors

        #region Properties
        /// <summary>
        /// Gets or sets a list of points representing the handles of the <see cref="CubicBezier2D"/> curve.
        /// </summary>
        [IgnoreDataMember, XmlIgnore, SoapIgnore]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        [TypeConverter(typeof(ExpandableCollectionConverter))]
        public List<Point2D> Points
        {
            get { return new List<Point2D> { A, B, C, D }; }
            set
            {
                if (value is not null)
                {
                    A = value[0];
                    B = value[1];
                    C = value[2];
                    D = value[3];
                }
            }
        }

        /// <summary>
        /// Gets or sets the starting node for the <see cref="CubicBezier2D"/> curve.
        /// </summary>
        [IgnoreDataMember, XmlIgnore, SoapIgnore]
        [Category("Elements")]
        [Description("The first Point of a Cubic Bézier.")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        [TypeConverter(typeof(Point2DConverter))]
        public Point2D A
        {
            get { return new Point2D(ax, ay); }
            set
            {
                ax = value.X;
                ay = value.Y;
                ClearCache();
                OnPropertyChanged(nameof(A));
                update?.Invoke();
            }
        }

        /// <summary>
        /// Gets or sets the X coordinate of the first Point of a Cubic Bézier.
        /// </summary>
        [XmlAttribute(nameof(ax))]
        [Browsable(false)]
        [Category("Elements")]
        [Description("The X coordinate of the first Point of a Cubic Bézier.")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        [RefreshProperties(RefreshProperties.All)]
        public double AX
        {
            get { return ax; }
            set
            {
                ax = value;
                ClearCache();
                OnPropertyChanged(nameof(AX));
                update?.Invoke();
            }
        }

        /// <summary>
        /// Gets or sets the Y coordinate of the first Point of a Cubic Bézier.
        /// </summary>
        [XmlAttribute(nameof(ay))]
        [Browsable(false)]
        [Category("Elements")]
        [Description("The y coordinate of the first Point of a Cubic Bézier.")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        [RefreshProperties(RefreshProperties.All)]
        public double AY
        {
            get { return ay; }
            set
            {
                ay = value;
                ClearCache();
                OnPropertyChanged(nameof(AY));
                update?.Invoke();
            }
        }

        /// <summary>
        /// Gets or sets the first middle tangent control node for the <see cref="CubicBezier2D"/> curve.
        /// </summary>
        [IgnoreDataMember, XmlIgnore, SoapIgnore]
        [Category("Elements")]
        [Description("The second Point of a Cubic Bézier.")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        [TypeConverter(typeof(Point2DConverter))]
        public Point2D B
        {
            get { return new Point2D(bx, by); }
            set
            {
                bx = value.X;
                by = value.Y;
                ClearCache();
                OnPropertyChanged(nameof(B));
                update?.Invoke();
            }
        }

        /// <summary>
        /// Gets or sets the X coordinate of the second Point of a Cubic Bézier.
        /// </summary>
        [XmlAttribute(nameof(bx))]
        [Browsable(false)]
        [Category("Elements")]
        [Description("The X coordinate of the second Point of a Cubic Bézier.")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        [RefreshProperties(RefreshProperties.All)]
        public double BX
        {
            get { return bx; }
            set
            {
                bx = value;
                ClearCache();
                OnPropertyChanged(nameof(BX));
                update?.Invoke();
            }
        }

        /// <summary>
        /// Gets or sets the Y coordinate of the second Point of a Cubic Bézier.
        /// </summary>
        [XmlAttribute(nameof(by))]
        [Browsable(false)]
        [Category("Elements")]
        [Description("The y coordinate of the second Point of a Cubic Bézier.")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        [RefreshProperties(RefreshProperties.All)]
        public double BY
        {
            get { return by; }
            set
            {
                by = value;
                ClearCache();
                OnPropertyChanged(nameof(BY));
                update?.Invoke();
            }
        }

        /// <summary>
        /// Gets or sets the second middle tangent control node for the <see cref="CubicBezier2D"/> curve.
        /// </summary>
        [IgnoreDataMember, XmlIgnore, SoapIgnore]
        [Category("Elements")]
        [Description("The third Point of a Cubic Bézier.")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        [TypeConverter(typeof(Point2DConverter))]
        public Point2D C
        {
            get { return new Point2D(cx, cy); }
            set
            {
                cx = value.X;
                cy = value.Y;
                ClearCache();
                OnPropertyChanged(nameof(C));
                update?.Invoke();
            }
        }

        /// <summary>
        /// Gets or sets the X coordinate of the third Point of a Cubic Bézier.
        /// </summary>
        [XmlAttribute(nameof(cx))]
        [Browsable(false)]
        [Category("Elements")]
        [Description("The X coordinate of the third Point of a Cubic Bézier.")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        [RefreshProperties(RefreshProperties.All)]
        public double CX
        {
            get { return cx; }
            set
            {
                bx = value;
                ClearCache();
                OnPropertyChanged(nameof(CX));
                update?.Invoke();
            }
        }

        /// <summary>
        /// Gets or sets the Y coordinate of the third Point of a Cubic Bézier.
        /// </summary>
        [XmlAttribute(nameof(cy))]
        [Browsable(false)]
        [Category("Elements")]
        [Description("The y coordinate of the third Point of a Cubic Bézier.")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        [RefreshProperties(RefreshProperties.All)]
        public double CY
        {
            get { return cy; }
            set
            {
                by = value;
                ClearCache();
                OnPropertyChanged(nameof(CY));
                update?.Invoke();
            }
        }

        /// <summary>
        /// Gets or sets the closing node for the <see cref="CubicBezier2D"/> curve.
        /// </summary>
        [IgnoreDataMember, XmlIgnore, SoapIgnore]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        [TypeConverter(typeof(Point2DConverter))]
        public Point2D D
        {
            get { return new Point2D(dx, dy); }
            set
            {
                dx = value.X;
                dy = value.Y;
                ClearCache();
                OnPropertyChanged(nameof(D));
                update?.Invoke();
            }
        }

        /// <summary>
        /// Gets or sets the X coordinate of the fourth Point of a Cubic Bézier.
        /// </summary>
        [XmlAttribute(nameof(dx))]
        [Browsable(false)]
        [Category("Elements")]
        [Description("The X coordinate of the fourth Point of a Cubic Bézier.")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        [RefreshProperties(RefreshProperties.All)]
        public double DX
        {
            get { return dx; }
            set
            {
                bx = value;
                ClearCache();
                OnPropertyChanged(nameof(DX));
                update?.Invoke();
            }
        }

        /// <summary>
        /// Gets or sets the Y coordinate of the fourth Point of a Cubic Bézier.
        /// </summary>
        [XmlAttribute(nameof(dy))]
        [Browsable(false)]
        [Category("Elements")]
        [Description("The y coordinate of the fourth Point of a Cubic Bézier.")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        [RefreshProperties(RefreshProperties.All)]
        public double DY
        {
            get { return dy; }
            set
            {
                by = value;
                ClearCache();
                OnPropertyChanged(nameof(DY));
                update?.Invoke();
            }
        }

        /// <summary>
        /// Gets the axial aligned bounding box of the <see cref="CubicBezier2D"/> curve.
        /// </summary>
        [IgnoreDataMember, XmlIgnore, SoapIgnore]
        [ReadOnly(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        [TypeConverter(typeof(Rectangle2DConverter))]
        public override Rectangle2D Bounds
            => (Rectangle2D)CachingProperty(() => Measurements.BezierBounds(CurveX, CurveY));

        /// <summary>
        /// An approximation of the length of a <see cref="CubicBezier2D"/> curve.
        /// </summary>
        /// <returns></returns>
        [IgnoreDataMember, XmlIgnore, SoapIgnore]
        public double Length
            => (double)CachingProperty(() => Measurements.CubicBezierArcLength(ax, ay, bx, by, cx, cy, dx, dy));

        /// <summary>
        /// Gets the perimeter length of the <see cref="CubicBezier2D"/> curve.
        /// </summary>
        [IgnoreDataMember, XmlIgnore, SoapIgnore]
        public override double Perimeter
            => Length;

        /// <summary>
        /// Gets the Polynomial degree of the <see cref="CubicBezier2D"/> curve.
        /// </summary>
        [IgnoreDataMember, XmlIgnore, SoapIgnore]
        public static PolynomialDegree Degree
            => PolynomialDegree.Cubic;

        /// <summary>
        /// Gets the <see cref="CubicBezier2D"/> curve's polynomial representation along the x-axis.
        /// </summary>
        [IgnoreDataMember, XmlIgnore, SoapIgnore]
        public Polynomial CurveX
        {
            get
            {
                var curveX = (Polynomial)CachingProperty(() => (Polynomial)CubicBezierBernsteinBasis(dx, cx, bx, ax));
                curveX.IsReadonly = true;
                return curveX;
            }
        }

        /// <summary>
        /// Gets the <see cref="CubicBezier2D"/> curve's polynomial representation along the y-axis.
        /// </summary>
        [IgnoreDataMember, XmlIgnore, SoapIgnore]
        public Polynomial CurveY
        {
            get
            {
                var curveY = (Polynomial)CachingProperty(() => (Polynomial)CubicBezierBernsteinBasis(dy, cy, by, ay));
                curveY.IsReadonly = true;
                return curveY;
            }
        }

        /// <summary>
        /// Gets a value indicating whether the curve is simple.
        /// </summary>
        /// <acknowledgment>
        /// http://pomax.github.io/bezierinfo/
        /// </acknowledgment>
        [IgnoreDataMember, XmlIgnore, SoapIgnore]
        public bool IsSimple
        {
            get
            {
                return (bool)CachingProperty(() => isSimple());

                bool isSimple()
                {
                    if (Degree == PolynomialDegree.Cubic)
                    {
                        var a1 = AngleVector(Points[0].X, Points[0].Y, Points[3].X, Points[3].Y, Points[1].X, Points[1].Y);
                        var a2 = AngleVector(Points[0].X, Points[0].Y, Points[3].X, Points[3].Y, Points[2].X, Points[2].Y);
                        if (a1 > 0 && a2 < 0 || a1 < 0 && a2 > 0)
                        {
                            return false;
                        }
                    }
                    var n1 = Normal(0);
                    var n2 = Normal(1);
                    var s = (n1.I * n2.I) + (n1.J * n2.J);
                    var angle = Abs(Acos(s));
                    return angle < PI / 3d;
                }
            }
        }

        /// <summary>
        /// Gets the derivative coordinates.
        /// </summary>
        /// <acknowledgment>
        /// http://pomax.github.io/bezierinfo/
        /// </acknowledgment>
        [IgnoreDataMember, XmlIgnore, SoapIgnore]
        public IList<IList<Point2D>> DerivativeCoordinates
        {
            get
            {
                return (IList<IList<Point2D>>)CachingProperty(() => DerivativeCoordinates());

                IList<IList<Point2D>> DerivativeCoordinates()
                {
                    // One-time compute of derivative coordinates
                    var derivitivePoints = new List<IList<Point2D>>();
                    var p = Points;
                    for (int d = p.Count, c = d - 1; d > 1; d--, c--)
                    {
                        var list = new List<Point2D>();
                        for (var j = 0; j < c; j++)
                        {
                            var dpt = new Point2D(
                            x: c * (p[j + 1].X - p[j].X),
                            y: c * (p[j + 1].Y - p[j].Y)
                            //,z: c * (p[j + 1].Z - p[j].Z)
                            );

                            list.Add(dpt);
                        }

                        derivitivePoints.Add(list);
                        p = list;
                    }

                    return derivitivePoints;
                }
            }
        }

        /// <summary>
        /// Gets the extrema.
        /// </summary>
        /// <acknowledgment>
        /// http://pomax.github.io/bezierinfo/
        /// </acknowledgment>
        [IgnoreDataMember, XmlIgnore, SoapIgnore]
        public IList<double> Extrema
        {
            get
            {
                return (IList<double>)CachingProperty(() => Extrema(DerivativeCoordinates));

                // ToDo: What are DRoots?
                static List<double> Extrema(IList<IList<Point2D>> derivativeCoordinates)
                {
                    var p = (from a in derivativeCoordinates[0] select a.X).ToList();
                    var result = new List<double>(DRoots(p));
                    p = (from a in derivativeCoordinates[0] select a.Y).ToList();
                    result.AddRange(DRoots(p));
                    p = (from a in derivativeCoordinates[1] select a.X).ToList();
                    result.AddRange(DRoots(p));
                    p = (from a in derivativeCoordinates[1] select a.Y).ToList();
                    result.AddRange(DRoots(p));

                    result = result.Where((t) => { return t >= 0 && t <= 1; }).ToList();
                    result.Sort();
                    return result;
                }
            }
        }

        /// <summary>
        /// Gets the inflections.
        /// </summary>
        /// <acknowledgment>
        /// https://pomax.github.io/bezierinfo/#inflections
        /// </acknowledgment>
        [IgnoreDataMember, XmlIgnore, SoapIgnore]
        public IList<double> Inflections
        {
            get
            {
                return (IList<double>)CachingProperty(() => Inflections(Points));
                static IList<double> Inflections(IList<Point2D> points)
                {
                    var p = Conversions.AlignPoints(points.ToArray(), points[0].X, points[0].Y, points[3].X, points[3].Y);
                    var a = p[2].X * p[1].Y;
                    var b = p[3].X * p[1].Y;
                    var c = p[1].X * p[2].Y;
                    var d = p[3].X * p[2].Y;
                    var v1 = 18 * ((-3 * a) + (2 * b) + (3 * c) - d);
                    var v2 = 18 * ((3 * a) - b - (3 * c));
                    var v3 = 18 * (c - a);

                    if (Approximately(v1, 0))
                    {
                        return Array.Empty<double>();
                    }

                    var descriminant = (v2 * v2) - (4 * v1 * v3);
                    var sq = Sqrt(descriminant);
                    d = 2 * v1;

                    return Approximately(d, 0)
                        ? new List<double>()
                        : new List<double>(
                        from r in new double[] { (sq - v2) / d, -(v2 + sq) / d }
                        where 0 <= r && r <= 1
                        select r
                        );
                }
            }
        }

        /// <summary>
        /// The reduce.
        /// </summary>
        /// <returns>The <see cref="List{T}"/>.</returns>
        /// <acknowledgment>
        /// http://pomax.github.io/bezierinfo/
        /// </acknowledgment>
        [IgnoreDataMember, XmlIgnore, SoapIgnore]
        public IList<CubicBezier2D> Reduction
        {
            get
            {
                return (IList<CubicBezier2D>)CachingProperty(() => Reduce());

                IList<CubicBezier2D> Reduce()
                {
                    int i;
                    double t1 = 0, t2 = 0;
                    const double step = 0.01;
                    CubicBezier2D segment;
                    var pass1 = new List<CubicBezier2D>();
                    var pass2 = new List<CubicBezier2D>();

                    // first pass: split on extrema
                    var extrema = Extrema.ToList();
                    if (extrema.IndexOf(0) == -1)
                    {
                        extrema.Insert(0, 0);
                    }

                    if (extrema.IndexOf(1) == -1)
                    {
                        extrema.Add(1);
                    }

                    t1 = extrema[0];
                    for (i = 1; i < extrema.Count; i++)
                    {
                        t2 = extrema[i];

                        // For some reason my splitting method produces the same starting values, but all other nodes are different, and the middle ones are in different orders.
                        var s = this.Split(t1, t2)[1];

                        segment = new CubicBezier2D(
                            s.Points[0],
                            s.Points[1],
                            s.Points[2],
                            s.Points[3]);
                        // segment,T1 and segment.T2 appear to be for debugging purposes.
                        //segment.T1 = t1;
                        //segment.T2 = t2;
                        pass1.Add(segment);
                        t1 = t2;
                    }

                    // Second pass: further reduce these segments to simple segments
                    foreach (var p1 in pass1)
                    {
                        t1 = 0;
                        t2 = 0;
                        while (t2 <= 1)
                        {
                            for (t2 = t1 + step; t2 <= 1 + step; t2 += step)
                            {
                                {
                                    var a = p1.Split(t2, t1);
                                    var s = a[1];
                                    segment = new CubicBezier2D(
                                        s.Points[0],
                                        s.Points[1],
                                        s.Points[2],
                                        s.Points[3]);
                                }

                                if (!segment.IsSimple)
                                {
                                    t2 -= step;
                                    if (Abs(t1 - t2) < step)
                                    {
                                        // we can never form a reduction
                                        return new List<CubicBezier2D>();
                                    }
                                    var a = p1.Split(t2, t1);
                                    var s = a[1];
                                    segment = new CubicBezier2D(
                                        s.Points[0],
                                        s.Points[1],
                                        s.Points[2],
                                        s.Points[3]);
                                    // segment,T1 and segment.T2 appear to be for debugging purposes.
                                    //segment.T1 = BezierUtil.Map(t1, 0, 1, p1.T1, p1.T2);
                                    //segment.T2 = BezierUtil.Map(t2, 0, 1, p1.T1, p1.T2);
                                    pass2.Add(segment);
                                    t1 = t2;
                                    break;
                                }
                            }
                        }
                        if (t1 < 1)
                        {
                            var a = p1.Split(1, t1);
                            var s = a[1];
                            segment = new CubicBezier2D(
                                s.Points[0],
                                s.Points[1],
                                s.Points[2],
                                s.Points[3]);
                            //segment.T1 = BezierUtil.Map(t1, 0, 1, p1.T1, p1.T2);
                            //segment.T2 = p1.T2;
                            pass2.Add(segment);
                        }
                    }

                    return pass2;
                }
            }
        }
        #endregion Properties

        #region Operators
        /// <summary>
        /// The operator ==.
        /// </summary>
        /// <param name="left">The left.</param>
        /// <param name="right">The right.</param>
        /// <returns>The <see cref="bool"/>.</returns>
        //[DebuggerStepThrough]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool operator ==(CubicBezier2D left, CubicBezier2D right) => (left?.Equals(right)).Value;

        /// <summary>
        /// The operator !=.
        /// </summary>
        /// <param name="left">The left.</param>
        /// <param name="right">The right.</param>
        /// <returns>The <see cref="bool"/>.</returns>
        //[DebuggerStepThrough]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool operator !=(CubicBezier2D left, CubicBezier2D right) => !(left?.Equals(right)).Value;

        /// <summary>
        /// Implicit conversion from tuple.
        /// </summary>
        /// <returns></returns>
        /// <param name="tuple"></param>
        //[DebuggerStepThrough]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static implicit operator CubicBezier2D((double aX, double aY, double bX, double bY, double cX, double cY) tuple) => new CubicBezier2D(tuple);

        /// <summary>
        /// Implicit conversion from tuple.
        /// </summary>
        /// <returns></returns>
        /// <param name="tuple"></param>
        //[DebuggerStepThrough]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static implicit operator CubicBezier2D((double aX, double aY, double bX, double bY, double cX, double cY, double dX, double dY) tuple) => new CubicBezier2D(tuple);
        #endregion Operators

        /// <summary>
        /// The hull.
        /// </summary>
        /// <param name="t">The t.</param>
        /// <returns>The <see cref="List{T}"/>.</returns>
        /// <acknowledgment>
        /// http://pomax.github.io/bezierinfo/
        /// </acknowledgment>
        //[DebuggerStepThrough]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public List<Point2D> Hull(double t)
        {
            var points = Points;
            var results = new List<Point2D>(Points);

            // We lerp between all points at each iteration, until we have 1 point left.
            while (points.Count > 1)
            {
                var remaining = new List<Point2D>();

                for (var i = 0; i < points.Count - 1; i++)
                {
                    var pt = Interpolators.Linear(t, points[i], points[i + 1]);
                    results.Add(pt);
                    remaining.Add(pt);
                }

                points = remaining;
            }

            return results;
        }

        /// <summary>
        /// The interpolate.
        /// </summary>
        /// <param name="t">The t.</param>
        /// <returns>The <see cref="Point2D"/>.</returns>
        //[DebuggerStepThrough]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override Point2D Interpolate(double t)
            => new Point2D(Interpolators.CubicBezier(t, A.X, A.Y, B.X, B.Y, C.X, C.Y, D.X, D.Y));

        /// <summary>
        /// The interpolate.
        /// </summary>
        /// <param name="ts">The ts.</param>
        /// <returns>The <see cref="List{T}"/>.</returns>
        //[DebuggerStepThrough]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public IList<Point2D> Interpolate(IList<double> ts)
        {
            if (ts is null)
            {
                throw new ArgumentNullException(nameof(ts));
            }

            var list = new List<Point2D>();

            foreach (var t in ts)
            {
                list.Add(Interpolate(t));
            }

            return list;
        }

        /// <summary>
        /// Gets the first derivative of the curve at the given t value.
        /// </summary>
        /// <param name="t">Time value at which to sample (should be between 0 and 1, though it won't fail if outside that range).</param>
        /// <returns>First derivative of curve at sampled point.</returns>
        /// <acknowledgment>
        /// https://github.com/burningmime/curves
        /// </acknowledgment>
        //[DebuggerStepThrough]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public Vector2D Derivate(double t)
        {
            // The inverse of t.
            var ti = 1d - t;

            // The derivative of the de Casteljau method applied to a cubic Bezier curve.
            return (3d * ti * ti * (B - A)) + (6d * t * ti * (C - B)) + (3d * t * t * (D - C));
        }

        /// <summary>
        /// Gets the normal vector of the curve at the given t value.
        /// </summary>
        /// <param name="t">The t.</param>
        /// <returns>The <see cref="Point2D"/>.</returns>
        /// <acknowledgment>
        /// https://pomax.github.io/bezierinfo/#pointvectors
        /// </acknowledgment>
        //[DebuggerStepThrough]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public Vector2D Normal(double t)
        {
            var d = Derivate(t);
            var q = 1d / Sqrt((d.I * d.I) + (d.J * d.J));
            return new Vector2D(-d.J * q, d.I * q);
        }

        /// <summary>
        /// Gets the tangent (normalized derivative) of the curve at a given t value.
        /// </summary>
        /// <param name="t">Time value at which to sample (should be between 0 and 1, though it won't fail if outside that range).</param>
        /// <returns>Direction the curve is going at that point.</returns>
        /// <acknowledgment>
        /// https://github.com/burningmime/curves
        /// </acknowledgment>
        //[DebuggerStepThrough]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public Vector2D Tangent(double t)
            => Derivate(t).Normalize();

        #region Methods
        /// <summary>
        /// Get the enumerator.
        /// </summary>
        /// <returns>The <see cref="IEnumerator{T}"/>.</returns>
        //[DebuggerStepThrough]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public IEnumerator<Point2D> GetEnumerator()
        {
            yield return new Point2D(Interpolators.CubicBezier(Length, A.X, A.Y, B.X, B.Y, C.X, C.Y, D.X, D.Y));
        }

        /// <summary>
        /// The equals.
        /// </summary>
        /// <param name="other">The other.</param>
        /// <returns>The <see cref="bool"/>.</returns>
        //[DebuggerStepThrough]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool Equals(CubicBezier2D other) => A.Equals(other?.A) && B.Equals(other?.B) && C.Equals(other?.C) && D.Equals(other?.D);

        /// <summary>
        /// The equals.
        /// </summary>
        /// <param name="obj">The obj.</param>
        /// <returns>The <see cref="bool"/>.</returns>
        //[DebuggerStepThrough]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override bool Equals(object obj) => obj is CubicBezier2D d && Equals(d);

        /// <summary>
        /// Get the hash code.
        /// </summary>
        /// <returns>The <see cref="int"/>.</returns>
        /// <remarks><para>https://github.com/burningmime/curves</para></remarks>
        //[DebuggerStepThrough]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override int GetHashCode() => HashCode.Combine(ax, ay, bx, by, cx, cy, dx, dy);

        /// <summary>
        /// Creates a string representation of this <see cref="CubicBezier2D"/> struct based on the format string
        /// and IFormatProvider passed in.
        /// If the provider is null, the CurrentCulture is used.
        /// See the documentation for IFormattable for more information.
        /// </summary>
        /// <param name="format"></param>
        /// <param name="provider"></param>
        /// <returns>
        /// A string representation of this object.
        /// </returns>
        //[DebuggerStepThrough]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override string ConvertToString(string format, IFormatProvider provider)
        {
            if (this is null)
            {
                return nameof(CubicBezier2D);
            }

            var sep = Tokenizer.GetNumericListSeparator(provider);
            IFormattable formatable = $"{nameof(CubicBezier2D)}={{{nameof(A)}={A}{sep}{nameof(B)}={B}{sep}{nameof(C)}={C}{sep}{nameof(D)}={D}}}";
            return formatable.ToString(format, provider);
        }
        #endregion Methods
    }
}


text:
package com.amazonaws.services.mediaconvert.model;

import javax.annotation.Generated;

/**
 * Specify font outline color. Leave Outline color (OutlineColor) blank and set Style passthrough (StylePassthrough) to
 * enabled to use the font outline color data from your input captions, if present.
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum BurninSubtitleOutlineColor {

    BLACK("BLACK"),
    WHITE("WHITE"),
    YELLOW("YELLOW"),
    RED("RED"),
    GREEN("GREEN"),
    BLUE("BLUE"),
    AUTO("AUTO");

    private String value;

    private BurninSubtitleOutlineColor(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return BurninSubtitleOutlineColor corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static BurninSubtitleOutlineColor fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (BurninSubtitleOutlineColor enumEntry : BurninSubtitleOutlineColor.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { HomeComponent } from './home';
import { TablesComponent } from './tables/tables.component';
import { PathComponent } from './path/path.component';
import { VariableBindComponent } from './variable-bind/variable-bind.component';
import { TodoComponent } from './todo/todo.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'home', component: HomeComponent },
  { path: 'tables', component: TablesComponent },
  { path: 'path', component: PathComponent },
  { path: 'live', component: VariableBindComponent },
  { path: 'todo', component: TodoComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { relativeLinkResolution: 'legacy' })],
  exports: [RouterModule],
})
export class AppRoutingModule {}


text:
from __future__ import division, print_function

import warnings
import numpy as np

from scipy.special import gammainccinv
from scipy.ndimage.filters import convolve

def _inv_nchi_cdf(N, K, alpha):
    """Inverse CDF for the noncentral chi distribution
    See [1]_ p.3 section 2.3"""
    return gammainccinv(N * K, 1 - alpha) / K

def piesno(data, N, alpha=0.01, l=100, itermax=100, eps=1e-5, return_mask=False):
    """
    Probabilistic Identification and Estimation of Noise (PIESNO).

    Parameters
    -----------
    data : ndarray
        The magnitude signals to analyse. The last dimension must contain the
        same realisation of the volume, such as dMRI or fMRI data.

    N : int
        The number of phase array coils of the MRI scanner.
        If your scanner does a SENSE reconstruction, ALWAYS use N=1, as the noise
        profile is always Rician.
        If your scanner does a GRAPPA reconstruction, set N as the number
        of phase array coils.

    alpha : float
        Probabilistic estimation threshold for the gamma function.

    l : int
        number of initial estimates for sigma to try.

    itermax : int
        Maximum number of iterations to execute if convergence
        is not reached.

    eps : float
        Tolerance for the convergence criterion. Convergence is
        reached if two subsequent estimates are smaller than eps.

    return_mask : bool
        If True, return a mask identyfing all the pure noise voxel
        that were found.

    Returns
    --------
    sigma : float
        The estimated standard deviation of the gaussian noise.

    mask : ndarray (optional)
        A boolean mask indicating the voxels identified as pure noise.

    Note
    ------
    This function assumes two things : 1. The data has a noisy, non-masked
    background and 2. The data is a repetition of the same measurements
    along the last axis, i.e. dMRI or fMRI data, not structural data like T1/T2.

    This function processes the data slice by slice, as originally designed in
    the paper. Use it to get a slice by slice estimation of the noise, as in
    spinal cord imaging for example.

    References
    ------------

    .. [1] Koay CG, Ozarslan E and Pierpaoli C.
    "Probabilistic Identification and Estimation of Noise (PIESNO):
    A self-consistent approach and its applications in MRI."
    Journal of Magnetic Resonance 2009; 199: 94-103.

    .. [2] Koay CG, Ozarslan E and Basser PJ.
    "A signal transformational framework for breaking the noise floor
    and its applications in MRI."
    Journal of Magnetic Resonance 2009; 197: 108-119.
    """

    # This method works on a 2D array with repetitions as the third dimension,
    # so process the dataset slice by slice.
    if data.ndim < 3:
        e_s = "This function only works on datasets of at least 3 dimensions."
        raise ValueError(e_s)

    if data.ndim == 4:

        sigma = np.zeros(data.shape[-2], dtype=np.float32)
        mask_noise = np.zeros(data.shape[:-1], dtype=np.bool)

        for idx in range(data.shape[-2]):
            sigma[idx], mask_noise[..., idx] = _piesno_3D(data[..., idx, :],
                                                          N, alpha=alpha,
                                                          l=l, itermax=itermax,
                                                          eps=eps, return_mask=True)

    else:
        sigma, mask_noise = _piesno_3D(data, N,
                                       alpha=alpha,
                                       l=l,
                                       itermax=itermax,
                                       eps=eps,
                                       return_mask=True)

    if return_mask:
        return sigma, mask_noise

    return sigma

def _piesno_3D(data, N, alpha=0.01, l=100, itermax=100, eps=1e-5,
               return_mask=False):
    """
    Probabilistic Identification and Estimation of Noise (PIESNO).
    This is the slice by slice version for working on a 4D array.

    Parameters
    -----------
    data : ndarray
        The magnitude signals to analyse. The last dimension must contain the
        same realisation of the volume, such as dMRI or fMRI data.

    N : int
        The number of phase array coils of the MRI scanner.

    alpha : float (optional)
        Probabilistic estimation threshold for the gamma function.
        Default: 0.01.

    l : int (optional)
        number of initial estimates for sigma to try. Default: 100.

    itermax : int (optional)
        Maximum number of iterations to execute if convergence
        is not reached. Default: 100.

    eps : float (optional)
        Tolerance for the convergence criterion. Convergence is
        reached if two subsequent estimates are smaller than eps.
        Default: 1e-5.

    return_mask : bool (optional)
        If True, return a mask identyfing all the pure noise voxel
        that were found. Default: False.

    Returns
    --------
    sigma : float
        The estimated standard deviation of the gaussian noise.

    mask : ndarray
        A boolean mask indicating the voxels identified as pure noise.

    Notes
    ------
    This function assumes two things : 1. The data has a noisy, non-masked
    background and 2. The data is a repetition of the same measurements
    along the last axis, i.e. dMRI or fMRI data, not structural data like T1/T2.

    References
    ------------

    .. [1] Koay CG, Ozarslan E and Pierpaoli C.
    "Probabilistic Identification and Estimation of Noise (PIESNO):
    A self-consistent approach and its applications in MRI."
    Journal of Magnetic Resonance 2009; 199: 94-103.

    .. [2] Koay CG, Ozarslan E and Basser PJ.
    "A signal transformational framework for breaking the noise floor
    and its applications in MRI."
    Journal of Magnetic Resonance 2009; 197: 108-119.
    """
    # Get optimal quantile for N if available, else use the median.
    opt_quantile = {1: 0.79681213002002,
                    2: 0.7306303027491917,
                    4: 0.6721952960782169,
                    8: 0.6254030432343569,
                   16: 0.5900487123737876,
                   32: 0.5641772300866416,
                   64: 0.5455611840489607,
                  128: 0.5322811923303339}

    if N in opt_quantile:
        q = opt_quantile[N]

    else:
        q = 0.5

    # Initial estimation of sigma
    denom = np.sqrt(2 * _inv_nchi_cdf(N, 1, q))
    m = np.percentile(data, q * 100) / denom

    phi = np.arange(1, l + 1) * m / l
    K = data.shape[-1]
    sum_m2 = np.sum(data**2, axis=-1, dtype=np.float32)

    sigma = np.zeros(phi.shape, dtype=phi.dtype)
    mask = np.zeros(phi.shape + data.shape[:-1])

    lambda_minus = _inv_nchi_cdf(N, K, alpha/2)
    lambda_plus = _inv_nchi_cdf(N, K, 1 - alpha/2)

    pos = 0
    max_length_omega = 0

    for num, sig in enumerate(phi):

        sig_prev = 0
        omega_size = 1
        idx = np.zeros(sum_m2.shape, dtype=np.bool)

        for n in range(itermax):

            if np.abs(sig - sig_prev) < eps:
                break

            s = sum_m2 / (2 * K * sig**2)
            idx = np.logical_and(lambda_minus <= s, s <= lambda_plus)
            omega = data[idx, :]

            # If no point meets the criterion, exit
            if omega.size == 0:
                omega_size = 0
                break

            sig_prev = sig

            # Numpy percentile must range in 0 to 100, hence q*100
            sig = np.percentile(omega, q * 100) / denom
            omega_size = omega.size / K

        # Remember the biggest omega array as giving the optimal
        # sigma amongst all initial estimates from phi
        if omega_size > max_length_omega:
            pos, max_length_omega = num, omega_size

        sigma[num] = sig
        mask[num] = idx

    if return_mask:
        return sigma[pos], mask[pos]

    return sigma[pos]

def estimate_sigma(arr, disable_background_masking=False, N=1):
    """Standard deviation estimation from local patches

    Parameters
    ----------
    arr : 3D or 4D ndarray
        The array to be estimated

    disable_background_masking : bool, default False
        If True, uses all voxels for the estimation, otherwise, only non-zeros
        voxels are used. Useful if the background is masked by the scanner.

    N : int, default 1
        Number of coils of the receiver array. Use N = 1 in case of a SENSE
        reconstruction (Philips scanners) or the number of coils for a GRAPPA
        reconstruction (Siemens and GE). See [1] for more information.

    Returns
    -------
    sigma : ndarray
        standard deviation of the noise, one estimation per volume.

    Note
    -------
    This function is the same as manually taking the standard deviation of the
    background and gives one value for the whole 3D array.
    It also includes the coil-dependent correction factor of Koay 2006
    (see [1]_, equation 18) with theta = 0.
    Since this function was introduced in [2]_ for T1 imaging,
    it is expected to perform ok on diffusion MRI data, but might oversmooth
    some regions and leave others un-denoised for spatially varying noise profiles.
    Consider using :func:`piesno` to estimate sigma instead if visual inacuracies
    are apparent in the denoised result.

    Reference
    -------
    .. [1] Koay, C. G., & Basser, P. J. (2006). Analytically exact correction
    scheme for signal extraction from noisy magnitude MR signals.
    Journal of Magnetic Resonance), 179(2), 317-22.

    .. [2] Coupe, P., Yger, P., Prima, S., Hellier, P., Kervrann, C., Barillot, C., 2008.
    An optimized blockwise nonlocal means denoising filter for 3-D magnetic
    resonance images, IEEE Trans. Med. Imaging 27, 425-41.
    """
    k = np.zeros((3, 3, 3), dtype=np.int8)

    k[0, 1, 1] = 1
    k[2, 1, 1] = 1
    k[1, 0, 1] = 1
    k[1, 2, 1] = 1
    k[1, 1, 0] = 1
    k[1, 1, 2] = 1

    # Precomputed factor from Koay 2006, this corrects the bias of magnitude image
    correction_factor = {1: 0.42920367320510366,
                         4: 0.4834941393603609,
                         6: 0.4891759468548269,
                         8: 0.49195420135894175,
                        12: 0.4946862482541263,
                        16: 0.4960339908122364,
                        20: 0.4968365823718557,
                        24: 0.49736907650825657,
                        32: 0.49803177052530145,
                        64: 0.49901964176235936}

    if N in correction_factor:
        factor = correction_factor[N]
    else:
        raise ValueError("N = {0} is not supported! Please choose amongst \
{1}".format(N, sorted(list(correction_factor.keys()))))

    if arr.ndim == 3:
        sigma = np.zeros(1, dtype=np.float32)
        arr = arr[..., None]
    elif arr.ndim == 4:
        sigma = np.zeros(arr.shape[-1], dtype=np.float32)
    else:
        raise ValueError("Array shape is not supported!", arr.shape)

    if disable_background_masking:
        mask = arr[..., 0].astype(np.bool)
    else:
        mask = np.ones_like(arr[..., 0], dtype=np.bool)

    conv_out = np.zeros(arr[..., 0].shape, dtype=np.float64)

    for i in range(sigma.size):
        convolve(arr[..., i], k, output=conv_out)
        mean_block = np.sqrt(6/7) * (arr[..., i] - 1/6 * conv_out)
        sigma[i] = np.sqrt(np.mean(mean_block[mask]**2) / factor)

    return sigma


text:
var File = java.io.File;
/*
 wph 20140102 - warn if legacy 'mcserver/js-plugins' or
 'mcserver/plugins/scriptcraft' directories are present
 */
module.exports = function( jsPluginsRootDir ) {
  var mcServerDir = new File(jsPluginsRootDir.canonicalPath).parentFile;
  if (mcServerDir == null){
    console.warn('Could not find parent directory for ' + jsPluginsRootDir.canonicalPath);
    return;
  }
  var legacyExists = false,
      legacyDirs = [
	new File( mcServerDir, 'js-plugins' ),
	new File( mcServerDir, 'plugins/scriptcraft' )
      ];

  for ( var i = 0; i < legacyDirs.length; i++ ) {
    if ( legacyDirs[i].exists()
         && legacyDirs[i].isDirectory() ) {

      legacyExists = true;

      console.warn('Legacy ScriptCraft directory %s was found. This directory is no longer used.',
	legacyDirs[i].canonicalPath);
      console.warn('Please put plugins in the ' + jsPluginsRootDir.canonicalPath + '/plugins directory');
    }
  }
  if ( legacyExists ) {
    console.info( 'Please note that the working directory for %s is %s',
		  __plugin, jsPluginsRootDir.canonicalPath );
  }
};


text:
ActiveRecord::Schema.define(version: 20150805182908) do

  create_table "books", force: :cascade do |t|
    t.string   "title"
    t.string   "author"
    t.date     "published_on"
    t.text     "description"
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
    t.string   "image_url"
  end

end


text:
#pragma once

// layer includes

#if ENABLED(RDOC_WIN32)
// undefined clashing windows #defines
#undef CreateEvent
#undef CreateSemaphore
#endif

#include "vk_hookset_defs.h"

void InitReplayTables(void *vulkanModule);

struct InstanceDeviceInfo
{
#undef DeclExt
#define DeclExt(name) bool ext_##name = false;

  bool brokenGetDeviceProcAddr = false;

  int vulkanVersion = VK_API_VERSION_1_0;

  DeclExts();
};

void InitInstanceExtensionTables(VkInstance instance, InstanceDeviceInfo *info);
void InitDeviceExtensionTables(VkDevice device, InstanceDeviceInfo *info);

VkLayerDispatchTableExtended *GetDeviceDispatchTable(void *device);
VkLayerInstanceDispatchTableExtended *GetInstanceDispatchTable(void *instance);

class WrappedVulkan;

template <typename parenttype, typename wrappedtype>
void SetDispatchTable(bool writing, parenttype parent, WrappedVulkan *core, wrappedtype *wrapped)
{
  wrapped->core = core;
  if(writing)
  {
    wrapped->table = wrappedtype::UseInstanceDispatchTable
                         ? (uintptr_t)GetInstanceDispatchTable((void *)parent)
                         : (uintptr_t)GetDeviceDispatchTable((void *)parent);
  }
  else
  {
    wrapped->table = wrappedtype::UseInstanceDispatchTable
                         ? (uintptr_t)GetInstanceDispatchTable(NULL)
                         : (uintptr_t)GetDeviceDispatchTable(NULL);
  }
}


text:
<?xml version='1.0' encoding='utf-8'?>
<manifest android:hardwareAccelerated="true" android:versionCode="1" android:versionName="0.0.1" android:windowSoftInputMode="adjustPan" package="com.igz.geoshare" xmlns:android="http://schemas.android.com/apk/res/android">
    <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:debuggable="true" android:hardwareAccelerated="true" android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/app_name" android:name="IGZEnterpriseGeoshare" android:theme="@android:style/Theme.Black.NoTitleBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.plugin.gcm.PushHandlerActivity" />
        <receiver android:name="com.plugin.gcm.CordovaGCMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
                <category android:name="com.igz.geoshare" />
            </intent-filter>
        </receiver>
        <service android:name="com.plugin.gcm.GCMIntentService" />
    </application>
    <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <permission android:name="com.igz.geoshare.permission.C2D_MESSAGE" android:protectionLevel="signature" />
    <uses-permission android:name="com.igz.geoshare.permission.C2D_MESSAGE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
</manifest>


text:
package com.google.api.ads.dfp.jaxws.v201308;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for createBaseRateResponse element declaration.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <element name="createBaseRateResponse">
 *   <complexType>
 *     <complexContent>
 *       <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *         <sequence>
 *           <element name="rval" type="{https://www.google.com/apis/ads/publisher/v201308}BaseRate" minOccurs="0"/>
 *         </sequence>
 *       </restriction>
 *     </complexContent>
 *   </complexType>
 * </element>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "rval"
})
@XmlRootElement(name = "createBaseRateResponse")
public class BaseRateServiceInterfacecreateBaseRateResponse {

    protected BaseRate rval;

    /**
     * Gets the value of the rval property.
     *
     * @return
     *     possible object is
     *     {@link BaseRate }
     *
     */
    public BaseRate getRval() {
        return rval;
    }

    /**
     * Sets the value of the rval property.
     *
     * @param value
     *     allowed object is
     *     {@link BaseRate }
     *
     */
    public void setRval(BaseRate value) {
        this.rval = value;
    }

}


text:
package org.vizzini.example.boardgame.tictactoe;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

import org.junit.Test;
import org.vizzini.core.game.boardgame.AlphaBetaSearch;
import org.vizzini.core.game.boardgame.Search;

/**
 * Provides tests for the AlphaBetaSearch class.
 */
public final class AlphaBetaSearchTest extends MyTestSearch
{
    /**
     * @return a new search.
     */
    private static Search createSearch()
    {
        final TTTActionGenerator actionGenerator = new TTTActionGenerator();
        final TTTEnvironmentEvaluator environmentEvaluator = new TTTEnvironmentEvaluator();

        return new AlphaBetaSearch(actionGenerator, environmentEvaluator);
    }

    /**
     * Construct this object.
     */
    public AlphaBetaSearchTest()
    {
        super(createSearch());
    }

    /**
     * Test the AlphaBetaSearch() method.
     */
    @Test
    public void testConstructorNull()
    {
        // Setup.
        final TTTActionGenerator actionGenerator = new TTTActionGenerator();
        final TTTEnvironmentEvaluator environmentEvaluator = new TTTEnvironmentEvaluator();

        try
        {
            new AlphaBetaSearch(null, environmentEvaluator);
            fail("Should have thrown an exception");
        }
        catch (final IllegalArgumentException e)
        {
            assertThat(e.getMessage(), is("actionGenerator is null"));
        }

        try
        {
            new AlphaBetaSearch(actionGenerator, null);
            fail("Should have thrown an exception");
        }
        catch (final IllegalArgumentException e)
        {
            assertThat(e.getMessage(), is("environmentEvaluator is null"));
        }
    }
}


text:
{% extends "account/base.html" %}

{% load url from future %}
{% load bootstrap %}

{% block body_class %}account settings{% endblock %}

{% block head_title %}Account{% endblock %}

{% block body %}

            <form method="POST" action="{% url "nintendosettings" %}">
                <legend>Nintendo Account Info</legend>
                {% csrf_token %}
                {{ form|bootstrap }}
                <button class="btn btn-primary" type="submit">Update</button>
            </form>

{% endblock %}


text:
<!DOCTYPE html>
<!--
Copyright (c) 2013 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="/tracing/base/task.html">
<link rel="import" href="/tracing/core/test_utils.html">
<link rel="import" href="/tracing/model/event_set.html">
<link rel="import" href="/tracing/ui/find_controller.html">
<link rel="import" href="/tracing/ui/timeline_track_view.html">
<link rel="import" href="/tracing/ui/timeline_view.html">

<script>
'use strict';

tr.b.unittest.testSuite(function() {
  var Task = tr.b.Task;

  /*
   * Just enough of the BrushingStateController to support the tests below.
   */
  function FakeBrushingStateController() {
    this.addAllEventsMatchingFilterToSelectionReturnValue = [];

    this.viewport = undefined;
    this.model = undefined;
    this.selection = new tr.model.EventSet();
    this.findMatches = new tr.model.EventSet();
  }

  FakeBrushingStateController.prototype = {
    addAllEventsMatchingFilterToSelectionAsTask: function(filter, selection) {
      return new Task(function() {
        var n = this.addAllEventsMatchingFilterToSelectionReturnValue.length;
        for (var i = 0; i < n; i++) {
          selection.push(
              this.addAllEventsMatchingFilterToSelectionReturnValue[i]);
        }
      }, this);
    },

    uiStateFromString: function(string) {
      return undefined;
    },

    findTextChangedTo: function(selection) {
      this.findMatches = selection;
      this.selection = new tr.model.EventSet();
    },

    findFocusChangedTo: function(selection) {
      this.selection = selection;
    },

    findTextCleared: function(selection) {
      this.selection = new tr.model.EventSet();
      this.findMatches = new tr.model.EventSet();
    }
  };

  test('findControllerNoModel', function() {
    var brushingStateController = new FakeBrushingStateController();
    var controller = new tr.ui.FindController(brushingStateController);
    controller.findNext();
    controller.findPrevious();
  });

  test('findControllerEmptyHit', function() {
    var brushingStateController = new FakeBrushingStateController();
    var controller = new tr.ui.FindController(brushingStateController);

    brushingStateController.selection = new tr.model.EventSet();
    brushingStateController.findMatches = new tr.model.EventSet();
    controller.findNext();
    assert.lengthOf(brushingStateController.selection, 0);
    assert.lengthOf(brushingStateController.findMatches, 0);
    controller.findPrevious();
    assert.lengthOf(brushingStateController.selection, 0);
    assert.lengthOf(brushingStateController.findMatches, 0);
  });

  test('findControllerOneHit', function() {
    var brushingStateController = new FakeBrushingStateController();
    var controller = new tr.ui.FindController(brushingStateController);

    var s1 = {guid: 1};
    brushingStateController.addAllEventsMatchingFilterToSelectionReturnValue = [
      s1
    ];
    return new Promise(function(resolve, reject) {
      controller.startFiltering('asdf').then(function() {
        try {
          assert.lengthOf(brushingStateController.selection, 0);
          assert.strictEqual(
              tr.b.getOnlyElement(brushingStateController.findMatches), s1);

          controller.findNext();
          assert.strictEqual(
              tr.b.getOnlyElement(brushingStateController.selection), s1);
          assert.strictEqual(
              tr.b.getOnlyElement(brushingStateController.findMatches), s1);

          controller.findNext();
          assert.strictEqual(
              tr.b.getOnlyElement(brushingStateController.selection), s1);
          assert.strictEqual(
              tr.b.getOnlyElement(brushingStateController.findMatches), s1);

          controller.findPrevious();
          assert.strictEqual(
              tr.b.getOnlyElement(brushingStateController.selection), s1);
          assert.strictEqual(
              tr.b.getOnlyElement(brushingStateController.findMatches), s1);
          resolve();
        } catch (err) {
          reject(err);
        }
      });
    });
  });

  test('findControllerMultipleHits', function() {
    var brushingStateController = new FakeBrushingStateController();
    var controller = new tr.ui.FindController(brushingStateController);

    var s1 = {guid: 1};
    var s2 = {guid: 2};
    var s3 = {guid: 3};

    brushingStateController.addAllEventsMatchingFilterToSelectionReturnValue = [
      s1, s2, s3
    ];
    return new Promise(function(resolve, reject) {
      controller.startFiltering('asdf').then(function() {
        try {
          // Loop through hits then when we wrap, try moving backward.
          assert.lengthOf(brushingStateController.selection, 0);
          assert.lengthOf(brushingStateController.findMatches, 3);
          let matches = Array.from(brushingStateController.findMatches);
          assert.strictEqual(matches[0], s1);
          assert.strictEqual(matches[1], s2);
          assert.strictEqual(matches[2], s3);

          controller.findNext();
          assert.strictEqual(
              tr.b.getOnlyElement(brushingStateController.selection), s1);

          controller.findNext();
          assert.strictEqual(
              tr.b.getOnlyElement(brushingStateController.selection), s2);

          controller.findNext();
          assert.strictEqual(
              tr.b.getOnlyElement(brushingStateController.selection), s3);

          controller.findNext();
          assert.strictEqual(
              tr.b.getOnlyElement(brushingStateController.selection), s1);

          controller.findPrevious();
          assert.strictEqual(
              tr.b.getOnlyElement(brushingStateController.selection), s3);

          controller.findPrevious();
          assert.strictEqual(
              tr.b.getOnlyElement(brushingStateController.selection), s2);
          assert.lengthOf(brushingStateController.findMatches, 3);
          matches = Array.from(brushingStateController.findMatches);
          assert.strictEqual(matches[0], s1);
          assert.strictEqual(matches[1], s2);
          assert.strictEqual(matches[2], s3);
          resolve();
        } catch (err) {
          reject(err);
        }
      });
    });
  });

  test('findControllerChangeFilterAfterNext', function() {
    var brushingStateController = new FakeBrushingStateController();
    var controller = new tr.ui.FindController(brushingStateController);

    var s1 = {guid: 1};
    var s2 = {guid: 2};
    var s3 = {guid: 3};
    var s4 = {guid: 4};

    brushingStateController.addAllEventsMatchingFilterToSelectionReturnValue = [
      s1, s2, s3
    ];
    return new Promise(function(resolve, reject) {
      controller.startFiltering('asdf').then(function() {
        // Loop through hits then when we wrap, try moving backward.
        controller.findNext();
        brushingStateController.
            addAllEventsMatchingFilterToSelectionReturnValue = [s4];

        controller.startFiltering('asdfsf').then(function() {
          controller.findNext();
          try {
            assert.strictEqual(
                tr.b.getOnlyElement(brushingStateController.selection), s4);
            resolve();
          } catch (err) {
            reject(err);
          }
        });
      });
    });
  });

  test('findControllerSelectsAllItemsFirst', function() {
    var brushingStateController = new FakeBrushingStateController();
    var controller = new tr.ui.FindController(brushingStateController);

    var s1 = {guid: 1};
    var s2 = {guid: 2};
    var s3 = {guid: 3};
    brushingStateController.addAllEventsMatchingFilterToSelectionReturnValue = [
      s1, s2, s3
    ];
    return new Promise(function(resolve, reject) {
      controller.startFiltering('asdfsf').then(function() {
        try {
          assert.lengthOf(brushingStateController.selection, 0);
          assert.lengthOf(brushingStateController.findMatches, 3);
          let matches = Array.from(brushingStateController.findMatches);
          assert.strictEqual(matches[0], s1);
          assert.strictEqual(matches[1], s2);
          assert.strictEqual(matches[2], s3);

          controller.findNext();
          assert.strictEqual(
              tr.b.getOnlyElement(brushingStateController.selection), s1);

          controller.findNext();
          assert.strictEqual(
              tr.b.getOnlyElement(brushingStateController.selection), s2);
          assert.lengthOf(brushingStateController.findMatches, 3);
          matches = Array.from(brushingStateController.findMatches);
          assert.strictEqual(matches[0], s1);
          assert.strictEqual(matches[1], s2);
          assert.strictEqual(matches[2], s3);
          resolve();
        } catch (err) {
          reject(err);
        }
      });
    });
  });

  test('findControllerWithRealTimeline', function() {
    var model = tr.c.TestUtils.newModel(function(model) {
      var p1 = model.getOrCreateProcess(1);
      var t1 = p1.getOrCreateThread(1);
      t1.sliceGroup.pushSlice(new tr.model.ThreadSlice(
          '', 'a', 0, 1, {}, 3));
      model.t1 = t1;
    });

    var container = document.createElement('track-view-container');
    container.id = 'track_view_container';

    var timeline = document.createElement('tr-ui-timeline-view');
    Polymer.dom(timeline).appendChild(container);

    // This is for testing only, have to make sure things link up right.
    timeline.trackViewContainer_ = container;

    timeline.model = model;

    var brushingStateController = timeline.brushingStateController;
    var controller = timeline.findCtl_.controller;

    // Test find with no filterText.
    controller.findNext();

    // Test find with filter txt.
    return new Promise(function(resolve, reject) {
      controller.startFiltering('a').then(function() {
        try {
          assert.strictEqual(brushingStateController.selection.length, 0);
          assert.deepEqual(tr.b.asArray(brushingStateController.findMatches),
              model.t1.sliceGroup.slices);

          controller.findNext();
          assert.isTrue(brushingStateController.selection.equals(
              new tr.model.EventSet(model.t1.sliceGroup.slices[0])));

          controller.startFiltering('xxx').then(function() {
            try {
              assert.strictEqual(brushingStateController.findMatches.length, 0);
              assert.strictEqual(brushingStateController.selection.length, 1);

              controller.findNext();
              assert.strictEqual(brushingStateController.selection.length, 0);

              controller.findNext();
              assert.strictEqual(brushingStateController.selection.length, 0);
              resolve();
            } catch (err) {
              reject(err);
            }
          });
        } catch (err) {
          reject(err);
        }
      });
    });
  });

  test('findControllerNavigation', function() {
    var brushingStateController = new FakeBrushingStateController();
    var controller = new tr.ui.FindController(brushingStateController);

    var navToPositionCallCount = 0;
    var findTextClearedCallCount = 0;
    var fakeUIState = {};
    brushingStateController.uiStateFromString = function(string) {
      if (string === '') return undefined;

      assert.strictEqual(string, '2000@1.2x7');
      return fakeUIState;
    };
    brushingStateController.navToPosition = function(uiState) {
      assert.strictEqual(uiState, fakeUIState);
      navToPositionCallCount++;
    };
    brushingStateController.findTextCleared = function() {
      findTextClearedCallCount++;
    };

    return new Promise(function(resolve, reject) {
      controller.startFiltering('2000@1.2x7').then(function() {
        assert.strictEqual(navToPositionCallCount, 1);
      }).then(function() {
        controller.startFiltering('').then(function() {
          try {
            assert.strictEqual(findTextClearedCallCount, 1);
            resolve();
          } catch (err) {
            reject(err);
          }
        });
      });
    });
  });

  test('findControllerClearAfterSet', function() {
    var brushingStateController = new FakeBrushingStateController();
    var controller = new tr.ui.FindController(brushingStateController);
    var findTextChangedToCalled = false;
    brushingStateController.findTextChangedTo = function(selection) {
      findTextChangedToCalled = true;
    };
    brushingStateController.findTextCleared = function() {
      assert.strictEqual(findTextChangedToCalled, true);
    };
    controller.startFiltering('1');
    controller.startFiltering('');
  });
});
</script>


text:
import * as THREE from "three";
import { LOADER_OPTIONS, MAP_ID } from "./config";
import { ThreeJSOverlayView, WORLD_SIZE } from "../src";

import { Loader } from "@googlemaps/js-api-loader";

const mapOptions = {
  center: {
    lat: 45,
    lng: 0,
  },
  mapId: MAP_ID,
  zoom: 5,
  heading: -45,
  tilt: 45,
};

new Loader(LOADER_OPTIONS).load().then(() => {
  const map = new google.maps.Map(document.getElementById("map"), mapOptions);
  const scene = new THREE.Scene();

  scene.add(new THREE.AxesHelper(WORLD_SIZE));

  // add ThreeJS Overlay view anchored to center of map
  new ThreeJSOverlayView({
    anchor: { ...mapOptions.center, altitude: 0 },
    scene,
    map,
    THREE,
  });
});


text:
<?php

/**
 * Service definition for SearchConsole (v1).
 *
 *

 * Provides tools for running validation tests against single URLs

 *
 *

 * For more information about this service, see the API
 * Documentation
 *

 *
 * @author Google, Inc.
 */
class Google_Service_SearchConsole extends Google_Service
{

  public $urlTestingTools_mobileFriendlyTest;

  /**
   * Constructs the internal representation of the SearchConsole service.
   *
   * @param Google_Client $client
   */
  public function __construct(Google_Client $client)
  {
    parent::__construct($client);
    $this->rootUrl = 'https://searchconsole.googleapis.com/';
    $this->servicePath = '';
    $this->batchPath = 'batch';
    $this->version = 'v1';
    $this->serviceName = 'searchconsole';

    $this->urlTestingTools_mobileFriendlyTest = new Google_Service_SearchConsole_Resource_UrlTestingToolsMobileFriendlyTest(
        $this,
        $this->serviceName,
        'mobileFriendlyTest',
        array(
          'methods' => array(
            'run' => array(
              'path' => 'v1/urlTestingTools/mobileFriendlyTest:run',
              'httpMethod' => 'POST',
              'parameters' => array(),
            ),
          )
        )
    );
  }
}


text:
package main

type Source struct {
	Repository         string       `json:"repository"`
	Tag                string       `json:"tag"`
	Username           string       `json:"username"`
	Password           string       `json:"password"`
	InsecureRegistries []string     `json:"insecure_registries"`
	RegistryMirror     string       `json:"registry_mirror"`
	DomainCerts        []DomainCert `json:"ca_certs"`

	AWSAccessKeyID     string `json:"aws_access_key_id"`
	AWSSecretAccessKey string `json:"aws_secret_access_key"`
}

type Version struct {
	Digest string `json:"digest"`
}

type CheckRequest struct {
	Source  Source  `json:"source"`
	Version Version `json:"version"`
}

type CheckResponse []Version

type DomainCert struct {
	Domain string `json:"domain"`
	Cert   string `json:"cert"`
}


text:
ACCEPTED

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

#### Published in
Memoirs of the Brooklyn botanical Garden 1: 210 (1918)

#### Original name
Uredo confluens DC., 1815

### Remarks
null