text:
package org.archive.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.regex.Matcher;

/**
 * Sort-friendly URI Reordering Transform.
 *
 * Converts URIs of the form:
 *
 *   scheme://userinfo@domain.tld:port/path?query#fragment
 *
 * ...into...
 *
 *   scheme://(tld,domain,:port@userinfo)/path?query#fragment
 *
 * The '(' ')' characters serve as an unambiguous notice that the so-called
 * 'authority' portion of the URI ([userinfo@]host[:port] in http URIs) has
 * been transformed; the commas prevent confusion with regular hostnames.
 *
 * This remedies the 'problem' with standard URIs that the host portion of a
 * regular URI, with its dotted-domains, is actually in reverse order from
 * the natural hierarchy that's usually helpful for grouping and sorting.
 *
 * The value of respecting URI case variance is considered negligible: it
 * is vanishingly rare for case-variance to be meaningful, while URI case-
 * variance often arises from people's confusion or sloppiness, and they
 * only correct it insofar as necessary to avoid blatant problems. Thus
 * the usual SURT form is considered to be flattened to all lowercase, and
 * not completely reversible.
 *
 * @author gojomo
 */
public class SURT {
    static char DOT = '.';
    static String BEGIN_TRANSFORMED_AUTHORITY = "(";
    static String TRANSFORMED_HOST_DELIM = ",";
    static String END_TRANSFORMED_AUTHORITY = ")";

    // 1: scheme://
    // 2: userinfo (if present)
    // 3: @ (if present)
    // 4: dotted-quad host
    // 5: other host
    // 6: :port
    // 7: path
    static String URI_SPLITTER =
            "^(\\w+://)(?:([-\\w\\.!~\\*'\\(\\)%;:&=+$,]+?)(@))?"+
    //        1           2                                 3
            "(?:((?:\\d{1,3}\\.){3}\\d{1,3})|(\\S+?))(:\\d+)?(/\\S*)?$";
    //           4                            5       6       7

    // RFC2396
    //       reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
    //                     "$" | ","
    //       unreserved  = alphanum | mark
    //       mark        = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
    //       userinfo    = *( unreserved | escaped |
    //                     ";" | ":" | "&" | "=" | "+" | "$" | "," )
    //       escaped     = "%" hex hex

    /**
     * Utility method for creating the SURT form of the URI in the
     * given String.
     *
     * By default, does not preserve casing.
     *
     * @param s String URI to be converted to SURT form
     * @return SURT form
     */
    public static String fromURI(String s) {
        return fromURI(s,false);
    }

    /**
     * Utility method for creating the SURT form of the URI in the
     * given String.
     *
     * If it appears a bit convoluted in its approach, note that it was
     * optimized to minimize object-creation after allocation-sites profiling
     * indicated this method was a top source of garbage in long-running crawls.
     *
     * Assumes that the String URI has already been cleaned/fixed (eg
     * by UURI fixup) in ways that put it in its crawlable form for
     * evaluation.
     *
     * @param s String URI to be converted to SURT form
     * @param preserveCase whether original case should be preserved
     * @return SURT form
     */
    public static String fromURI(String s, boolean preserveCase) {
        Matcher m = TextUtils.getMatcher(URI_SPLITTER,s);
        if(!m.matches()) {
            // not an authority-based URI scheme; return unchanged
            TextUtils.recycleMatcher(m);
            return s;
        }
        // preallocate enough space for SURT form, which includes
        // 3 extra characters ('(', ')', and one more ',' than '.'s
        // in original)
        StringBuffer builder = new StringBuffer(s.length()+3);
        append(builder,s,m.start(1),m.end(1)); // scheme://
        builder.append(BEGIN_TRANSFORMED_AUTHORITY); // '('

        if(m.start(4)>-1) {
            // dotted-quad ip match: don't reverse
            append(builder,s,m.start(4),m.end(4));
        } else {
            // other hostname match: do reverse
            int hostSegEnd = m.end(5);
            int hostStart = m.start(5);
            for(int i = m.end(5)-1; i>=hostStart; i--) {
                if(s.charAt(i-1)!=DOT && i > hostStart) {
                    continue;
                }
                append(builder,s,i,hostSegEnd); // rev host segment
                builder.append(TRANSFORMED_HOST_DELIM);     // ','
                hostSegEnd = i-1;
            }
        }

        append(builder,s,m.start(6),m.end(6)); // :port
        append(builder,s,m.start(3),m.end(3)); // at
        append(builder,s,m.start(2),m.end(2)); // userinfo
        builder.append(END_TRANSFORMED_AUTHORITY); // ')'
        append(builder,s,m.start(7),m.end(7)); // path
        if (!preserveCase) {
            for(int i = 0; i < builder.length(); i++) {
                builder.setCharAt(i,Character.toLowerCase(builder.charAt((i))));
            }
        }
        TextUtils.recycleMatcher(m);
        return builder.toString();
    }

    private static void append(StringBuffer b, CharSequence cs, int start,
            int end) {
        if (start < 0) {
            return;
        }
        b.append(cs, start, end);
    }

    /**
     * Allow class to be used as a command-line tool for converting
     * URL lists (or naked host or host/path fragments implied
     * to be HTTP URLs) to SURT form. Lines that cannot be converted
     * are returned unchanged.
     *
     *
     * Read from stdin or first file argument. Writes to stdout or
     * second argument filename
     *
     * @param args cmd-line arguments
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        InputStream in = args.length > 0 ? new BufferedInputStream(
                new FileInputStream(args[0])) : System.in;
        PrintStream out = args.length > 1 ? new PrintStream(
                new BufferedOutputStream(new FileOutputStream(args[1])))
                : System.out;
        BufferedReader br =
            new BufferedReader(new InputStreamReader(in));
        String line;
        while((line = br.readLine())!=null) {
            if(line.indexOf("#")>0) line=line.substring(0,line.indexOf("#"));
            line = line.trim();
            if(line.length()==0) continue;
            line = ArchiveUtils.addImpliedHttpIfNecessary(line);
            out.println(SURT.fromURI(line));
        }
        br.close();
        out.close();
    }
}


text:
package com.linecorp.armeria.common.logging;

import java.util.concurrent.TimeUnit;

import com.google.common.annotations.VisibleForTesting;

import com.linecorp.armeria.common.Request;
import com.linecorp.armeria.common.util.TextFormatter;

/**
 * A holder class which has the timing information about a connection attempt before a client
 * sends a {@link Request}.
 *
 * @see RequestLog#connectionTimings()
 */
public final class ClientConnectionTimings {

    @VisibleForTesting
    static final int TO_STRING_BUILDER_CAPACITY = 466;

    private final long connectionAcquisitionStartTimeMicros;
    private final long connectionAcquisitionDurationNanos;

    private final long dnsResolutionStartTimeMicros;
    private final long dnsResolutionDurationNanos;
    private final long socketConnectStartTimeMicros;
    private final long socketConnectDurationNanos;
    private final long pendingAcquisitionStartTimeMicros;
    private final long pendingAcquisitionDurationNanos;

    /**
     * Returns a newly created {@link ClientConnectionTimingsBuilder}.
     */
    public static ClientConnectionTimingsBuilder builder() {
        return new ClientConnectionTimingsBuilder();
    }

    ClientConnectionTimings(long connectionAcquisitionStartTimeMicros, long connectionAcquisitionDurationNanos,
                            long dnsResolutionStartTimeMicros, long dnsResolutionDurationNanos,
                            long socketConnectStartTimeMicros, long socketConnectDurationNanos,
                            long pendingAcquisitionStartTimeMicros, long pendingAcquisitionDurationNanos) {
        this.connectionAcquisitionStartTimeMicros = connectionAcquisitionStartTimeMicros;
        this.connectionAcquisitionDurationNanos = connectionAcquisitionDurationNanos;
        this.dnsResolutionStartTimeMicros = dnsResolutionStartTimeMicros;
        this.dnsResolutionDurationNanos = dnsResolutionDurationNanos;
        this.socketConnectStartTimeMicros = socketConnectStartTimeMicros;
        this.socketConnectDurationNanos = socketConnectDurationNanos;
        this.pendingAcquisitionStartTimeMicros = pendingAcquisitionStartTimeMicros;
        this.pendingAcquisitionDurationNanos = pendingAcquisitionDurationNanos;
    }

    /**
     * Returns the time when the client started to acquire a connection, in microseconds since the epoch.
     */
    public long connectionAcquisitionStartTimeMicros() {
        return connectionAcquisitionStartTimeMicros;
    }

    /**
     * Returns the time when the client started to acquire a connection, in milliseconds since the epoch.
     */
    public long connectionAcquisitionStartTimeMillis() {
        return TimeUnit.MICROSECONDS.toMillis(connectionAcquisitionStartTimeMicros);
    }

    /**
     * Returns the duration which was taken to get a connection, in nanoseconds. This value is greater than or
     * equal to the sum of {@link #dnsResolutionDurationNanos()}, {@link #socketConnectDurationNanos()} and
     * {@link #pendingAcquisitionDurationNanos()}.
     */
    public long connectionAcquisitionDurationNanos() {
        return connectionAcquisitionDurationNanos;
    }

    /**
     * Returns the time when the client started to resolve a domain name, in microseconds since the epoch.
     *
     * @return the start time, or {@code -1} if there was no action to resolve a domain name.
     */
    public long dnsResolutionStartTimeMicros() {
        return dnsResolutionStartTimeMicros;
    }

    /**
     * Returns the time when the client started to resolve a domain name, in milliseconds since the epoch.
     *
     * @return the start time, or {@code -1} if there was no action to resolve a domain name.
     */
    public long dnsResolutionStartTimeMillis() {
        if (dnsResolutionStartTimeMicros >= 0) {
            return TimeUnit.MICROSECONDS.toMillis(dnsResolutionStartTimeMicros);
        }
        return -1;
    }

    /**
     * Returns the duration which was taken to resolve a domain name, in nanoseconds.
     *
     * @return the duration, or {@code -1} if there was no action to resolve a domain name.
     */
    public long dnsResolutionDurationNanos() {
        return dnsResolutionDurationNanos;
    }

    /**
     * Returns the time when the client started to connect to a remote peer, in microseconds since the epoch.
     *
     * @return the start time, or {@code -1} if there was no action to connect to a remote peer.
     */
    public long socketConnectStartTimeMicros() {
        return socketConnectStartTimeMicros;
    }

    /**
     * Returns the time when the client started to connect to a remote peer, in milliseconds since the epoch.
     *
     * @return the start time, or {@code -1} if there was no action to connect to a remote peer.
     */
    public long socketConnectStartTimeMillis() {
        if (socketConnectStartTimeMicros >= 0) {
            return TimeUnit.MICROSECONDS.toMillis(socketConnectStartTimeMicros);
        }
        return -1;
    }

    /**
     * Returns the duration which was taken to connect to a remote peer, in nanoseconds.
     *
     * @return the duration, or {@code -1} if there was no action to connect to a remote peer.
     */
    public long socketConnectDurationNanos() {
        return socketConnectDurationNanos;
    }

    /**
     * Returns the time when the client started to wait for the completion of an existing connection attempt,
     * in microseconds since the epoch.
     *
     * @return the start time, or {@code -1} if there was no action to get a pending connection.
     */
    public long pendingAcquisitionStartTimeMicros() {
        return pendingAcquisitionStartTimeMicros;
    }

    /**
     * Returns the time when the client started to wait for the completion of an existing connection attempt,
     * in milliseconds since the epoch.
     *
     * @return the start time, or {@code -1} if there was no action to get a pending connection.
     */
    public long pendingAcquisitionStartTimeMillis() {
        if (pendingAcquisitionStartTimeMicros >= 0) {
            return TimeUnit.MICROSECONDS.toMillis(pendingAcquisitionStartTimeMicros);
        }
        return -1;
    }

    /**
     * Returns the duration which was taken to wait for the completion of an existing connection attempt
     * in order to use one connection for HTTP/2.
     *
     * @return the duration, or {@code -1} if there was no action to get a pending connection.
     */
    public long pendingAcquisitionDurationNanos() {
        return pendingAcquisitionDurationNanos;
    }

    @Override
    public String toString() {
        // 33 + 31 + 26 + 23 + 26 + 23 + 31 + 28 + 45 * 4 + 16 * 4 + 1 = 466
        final StringBuilder buf = new StringBuilder(TO_STRING_BUILDER_CAPACITY);
        buf.append("{connectionAcquisitionStartTime=");
        TextFormatter.appendEpochMicros(buf, connectionAcquisitionStartTimeMicros);
        buf.append(", connectionAcquisitionDuration=");
        TextFormatter.appendElapsed(buf, connectionAcquisitionDurationNanos);

        if (dnsResolutionDurationNanos >= 0) {
            buf.append(", dnsResolutionStartTime=");
            TextFormatter.appendEpochMicros(buf, dnsResolutionStartTimeMicros);
            buf.append(", dnsResolutionDuration=");
            TextFormatter.appendElapsed(buf, dnsResolutionDurationNanos);
        }

        if (socketConnectDurationNanos >= 0) {
            buf.append(", socketConnectStartTime=");
            TextFormatter.appendEpochMicros(buf, socketConnectStartTimeMicros);
            buf.append(", socketConnectDuration=");
            TextFormatter.appendElapsed(buf, socketConnectDurationNanos);
        }
        if (pendingAcquisitionDurationNanos >= 0) {
            buf.append(", pendingAcquisitionStartTime=");
            TextFormatter.appendEpochMicros(buf, pendingAcquisitionStartTimeMicros);
            buf.append(", pendingAcquisitionDuration=");
            TextFormatter.appendElapsed(buf, pendingAcquisitionDurationNanos);
        }
        buf.append('}');
        return buf.toString();
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="scaffolded-by" content="https://github.com/google/stagehand">
    <title>scheduler_react</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="styles.css">

Here will be react content


text:
Yepster SDK for PHP (official)
==============================
Create a Yepster invoice in your application (PHP 5.4+ & Curl)

What is Yepster?
----------------
Yepster is a free online invoicing tool. It is fully integrated with TargetPay, a payment service provider.
The app takes care of making, sending and managing your invoices.
Payments are handled by TargetPay and will be processed instantly.

Requirements
------------
First of all you need a Yepster (TargetPay) account.
Sign up on www.yepster.com
You'll receive a mail from TargetPay with the details they need to process your payments. Please follow the instructions.

Installation
------------
Copy the directory Yepster to your webserver.
Upload it in a 'vendor', 'extensions' or other module directory if you use a framework.
The autoloader of your framework should be able to load the appropriate source files.
If not, please manually 'require_once' the file /path/to/Yepster/autoload.php

Documentation
-------------
A generated HTML class reference can be found in the /doc folder.

API key
-------
Authentication is done using an API key (64-char). It can be found in your Profile in Yepster.
Find 'Profile...' in the upper-right menu in Yepster.
It looks like: 6ba19adb0af1c3ec31220072d73080df04b1ef271ac031ca508ef045bccec357

Creating invoice
------------------
To create an invoice you instantiate CreateInvoice.

	$yep = new Yepster\CreateInvoice;

Then you set the API key:

	$yep->setApiKey ('6ba19adb0af1c3ec31220072d73080df04b1ef271ac031ca508ef045bccec357');

A lot of the fields will be filled with defaults that should be appropriate. Only the name atrribute has to be set.
You can change the rest, e.g.:

	$yep->addDetail ('name', 'Yellow Melon B.V.');

To add invoicelines to your invoice you use for example:

	$yep->addInvoiceLine ('First product', 2.0, 100, 21);

(this will create a line with First product, quantity of 2 @ 100 euro each. VAT is 21%)

Then run:

	$result = $yep->exec();

The result is an array. In case of success:

	['status' => 'success', 'externalid' => *your invoice ID*, 'id' => *yepster invoice id* ]

In case of failure

	['status' => 'fail', 'error' => *error message* ]

Example
-------
Note: that the methods support 'chaining'.

	$result = Yepster\CreateInvoice::model()
	     ->setApiKey ('6ba19adb0af1c3ec31220072d73080df04b1ef271ac031ca508ef045bccec357')
	     ->addDetail ('name', 'Yellow Melon B.V.')
	     ->addDetail ('street', 'Kleine koppel')
	     ->addDetail ('housenumber', '52')
	     ->addDetail ('postcode', '3812PH')
	     ->addDetail ('city', 'Amersfoort')
	     ->addDetail ('email', 'info@yellowmelon.nl')
	     ->addInvoiceLine ('First product', 2.0, 100, 21)
	     ->addInvoiceLine ('Second product', 2.0, 250, 21)
	     ->exec();


text:
package com.chargebee.models;

import com.chargebee.*;
import com.chargebee.internal.*;
import com.chargebee.filters.*;
import com.chargebee.filters.enums.SortOrder;
import com.chargebee.internal.HttpUtil.Method;
import com.chargebee.models.enums.*;
import org.json.*;
import java.io.*;
import java.sql.Timestamp;
import java.util.*;

public class DifferentialPrice extends Resource<DifferentialPrice> {

    public enum Status {
        ACTIVE,
        DELETED,
        _UNKNOWN; /*Indicates unexpected value for this enum. You can get this when there is a
        java-client version incompatibility. We suggest you to upgrade to the latest version */
    }

    public static class Tier extends Resource<Tier> {
        public Tier(JSONObject jsonObj) {
            super(jsonObj);
        }

        public Integer startingUnit() {
            return reqInteger("starting_unit");
        }

        public Integer endingUnit() {
            return optInteger("ending_unit");
        }

        public Long price() {
            return reqLong("price");
        }

        public String startingUnitInDecimal() {
            return optString("starting_unit_in_decimal");
        }

        public String endingUnitInDecimal() {
            return optString("ending_unit_in_decimal");
        }

        public String priceInDecimal() {
            return optString("price_in_decimal");
        }

    }

    public static class ParentPeriod extends Resource<ParentPeriod> {
        public enum PeriodUnit {
             DAY,WEEK,MONTH,YEAR,
            _UNKNOWN; /*Indicates unexpected value for this enum. You can get this when there is a
            java-client version incompatibility. We suggest you to upgrade to the latest version */
        }

        public ParentPeriod(JSONObject jsonObj) {
            super(jsonObj);
        }

        public PeriodUnit periodUnit() {
            return reqEnum("period_unit", PeriodUnit.class);
        }

        public JSONArray period() {
            return optJSONArray("period");
        }

    }

    //Constructors
    //============

    public DifferentialPrice(String jsonStr) {
        super(jsonStr);
    }

    public DifferentialPrice(JSONObject jsonObj) {
        super(jsonObj);
    }

    // Fields
    //=======

    public String id() {
        return reqString("id");
    }

    public String itemPriceId() {
        return reqString("item_price_id");
    }

    public String parentItemId() {
        return reqString("parent_item_id");
    }

    public Long price() {
        return optLong("price");
    }

    public String priceInDecimal() {
        return optString("price_in_decimal");
    }

    public Status status() {
        return optEnum("status", Status.class);
    }

    public Long resourceVersion() {
        return optLong("resource_version");
    }

    public Timestamp updatedAt() {
        return optTimestamp("updated_at");
    }

    public Timestamp createdAt() {
        return reqTimestamp("created_at");
    }

    public Timestamp modifiedAt() {
        return reqTimestamp("modified_at");
    }

    public List<DifferentialPrice.Tier> tiers() {
        return optList("tiers", DifferentialPrice.Tier.class);
    }

    public String currencyCode() {
        return reqString("currency_code");
    }

    public List<DifferentialPrice.ParentPeriod> parentPeriods() {
        return optList("parent_periods", DifferentialPrice.ParentPeriod.class);
    }

    // Operations
    //===========

    public static CreateRequest create(String id) {
        String uri = uri("item_prices", nullCheck(id), "differential_prices");
        return new CreateRequest(Method.POST, uri);
    }

    public static RetrieveRequest retrieve(String id) {
        String uri = uri("differential_prices", nullCheck(id));
        return new RetrieveRequest(Method.GET, uri);
    }

    public static UpdateRequest update(String id) {
        String uri = uri("differential_prices", nullCheck(id));
        return new UpdateRequest(Method.POST, uri);
    }

    public static DeleteRequest delete(String id) {
        String uri = uri("differential_prices", nullCheck(id), "delete");
        return new DeleteRequest(Method.POST, uri);
    }

    public static DifferentialPriceListRequest list() {
        String uri = uri("differential_prices");
        return new DifferentialPriceListRequest(uri);
    }

    // Operation Request Classes
    //==========================

    public static class CreateRequest extends Request<CreateRequest> {

        private CreateRequest(Method httpMeth, String uri) {
            super(httpMeth, uri);
        }

        public CreateRequest parentItemId(String parentItemId) {
            params.add("parent_item_id", parentItemId);
            return this;
        }

        public CreateRequest price(Long price) {
            params.addOpt("price", price);
            return this;
        }

        public CreateRequest priceInDecimal(String priceInDecimal) {
            params.addOpt("price_in_decimal", priceInDecimal);
            return this;
        }

        public CreateRequest parentPeriodPeriodUnit(int index, ParentPeriod.PeriodUnit parentPeriodPeriodUnit) {
            params.add("parent_periods[period_unit][" + index + "]", parentPeriodPeriodUnit);
            return this;
        }
        public CreateRequest parentPeriodPeriod(int index, JSONArray parentPeriodPeriod) {
            params.addOpt("parent_periods[period][" + index + "]", parentPeriodPeriod);
            return this;
        }
        public CreateRequest tierStartingUnit(int index, Integer tierStartingUnit) {
            params.addOpt("tiers[starting_unit][" + index + "]", tierStartingUnit);
            return this;
        }
        public CreateRequest tierEndingUnit(int index, Integer tierEndingUnit) {
            params.addOpt("tiers[ending_unit][" + index + "]", tierEndingUnit);
            return this;
        }
        public CreateRequest tierPrice(int index, Long tierPrice) {
            params.addOpt("tiers[price][" + index + "]", tierPrice);
            return this;
        }
        public CreateRequest tierStartingUnitInDecimal(int index, String tierStartingUnitInDecimal) {
            params.addOpt("tiers[starting_unit_in_decimal][" + index + "]", tierStartingUnitInDecimal);
            return this;
        }
        public CreateRequest tierEndingUnitInDecimal(int index, String tierEndingUnitInDecimal) {
            params.addOpt("tiers[ending_unit_in_decimal][" + index + "]", tierEndingUnitInDecimal);
            return this;
        }
        public CreateRequest tierPriceInDecimal(int index, String tierPriceInDecimal) {
            params.addOpt("tiers[price_in_decimal][" + index + "]", tierPriceInDecimal);
            return this;
        }
        @Override
        public Params params() {
            return params;
        }
    }

    public static class RetrieveRequest extends Request<RetrieveRequest> {

        private RetrieveRequest(Method httpMeth, String uri) {
            super(httpMeth, uri);
        }

        public RetrieveRequest itemPriceId(String itemPriceId) {
            params.add("item_price_id", itemPriceId);
            return this;
        }

        @Override
        public Params params() {
            return params;
        }
    }

    public static class UpdateRequest extends Request<UpdateRequest> {

        private UpdateRequest(Method httpMeth, String uri) {
            super(httpMeth, uri);
        }

        public UpdateRequest itemPriceId(String itemPriceId) {
            params.add("item_price_id", itemPriceId);
            return this;
        }

        public UpdateRequest price(Long price) {
            params.addOpt("price", price);
            return this;
        }

        public UpdateRequest priceInDecimal(String priceInDecimal) {
            params.addOpt("price_in_decimal", priceInDecimal);
            return this;
        }

        public UpdateRequest parentPeriodPeriodUnit(int index, ParentPeriod.PeriodUnit parentPeriodPeriodUnit) {
            params.add("parent_periods[period_unit][" + index + "]", parentPeriodPeriodUnit);
            return this;
        }
        public UpdateRequest parentPeriodPeriod(int index, JSONArray parentPeriodPeriod) {
            params.addOpt("parent_periods[period][" + index + "]", parentPeriodPeriod);
            return this;
        }
        public UpdateRequest tierStartingUnit(int index, Integer tierStartingUnit) {
            params.addOpt("tiers[starting_unit][" + index + "]", tierStartingUnit);
            return this;
        }
        public UpdateRequest tierEndingUnit(int index, Integer tierEndingUnit) {
            params.addOpt("tiers[ending_unit][" + index + "]", tierEndingUnit);
            return this;
        }
        public UpdateRequest tierPrice(int index, Long tierPrice) {
            params.addOpt("tiers[price][" + index + "]", tierPrice);
            return this;
        }
        public UpdateRequest tierStartingUnitInDecimal(int index, String tierStartingUnitInDecimal) {
            params.addOpt("tiers[starting_unit_in_decimal][" + index + "]", tierStartingUnitInDecimal);
            return this;
        }
        public UpdateRequest tierEndingUnitInDecimal(int index, String tierEndingUnitInDecimal) {
            params.addOpt("tiers[ending_unit_in_decimal][" + index + "]", tierEndingUnitInDecimal);
            return this;
        }
        public UpdateRequest tierPriceInDecimal(int index, String tierPriceInDecimal) {
            params.addOpt("tiers[price_in_decimal][" + index + "]", tierPriceInDecimal);
            return this;
        }
        @Override
        public Params params() {
            return params;
        }
    }

    public static class DeleteRequest extends Request<DeleteRequest> {

        private DeleteRequest(Method httpMeth, String uri) {
            super(httpMeth, uri);
        }

        public DeleteRequest itemPriceId(String itemPriceId) {
            params.add("item_price_id", itemPriceId);
            return this;
        }

        @Override
        public Params params() {
            return params;
        }
    }

    public static class DifferentialPriceListRequest extends ListRequest<DifferentialPriceListRequest> {

        private DifferentialPriceListRequest(String uri) {
            super(uri);
        }

        public StringFilter<DifferentialPriceListRequest> itemPriceId() {
            return new StringFilter<DifferentialPriceListRequest>("item_price_id",this).supportsMultiOperators(true);
        }

        public StringFilter<DifferentialPriceListRequest> itemId() {
            return new StringFilter<DifferentialPriceListRequest>("item_id",this).supportsMultiOperators(true);
        }

        public StringFilter<DifferentialPriceListRequest> id() {
            return new StringFilter<DifferentialPriceListRequest>("id",this).supportsMultiOperators(true);
        }

        public StringFilter<DifferentialPriceListRequest> parentItemId() {
            return new StringFilter<DifferentialPriceListRequest>("parent_item_id",this).supportsMultiOperators(true);
        }

        @Override
        public Params params() {
            return params;
        }
    }

}


text:
package org.apache.sis.feature;

import java.util.Set;
import java.util.Map;
import java.util.Collections;
import java.io.IOException;
import org.opengis.parameter.ParameterValueGroup;
import org.opengis.parameter.ParameterDescriptorGroup;
import org.apache.sis.internal.feature.FeatureUtilities;
import org.apache.sis.util.ArgumentChecks;
import org.apache.sis.util.resources.Errors;

/**
 * A link operation, which is like a redirection or an alias.
 * The operation acts like a reference to another property.
 *
 * @author  Johann Sorel (Geomatys)
 * @version 1.1
 * @since   0.6
 * @module
 */
final class LinkOperation extends AbstractOperation {
    /**
     * For cross-version compatibility.
     */
    private static final long serialVersionUID = 765096861589501215L;

    /**
     * The parameter descriptor for the "Link" operation, which does not take any parameter.
     */
    private static final ParameterDescriptorGroup PARAMETERS = FeatureUtilities.parameters("Link");

    /**
     * The type of the result.
     */
    private final AbstractIdentifiedType result;

    /**
     * The name of the referenced attribute or feature association.
     */
    final String referentName;

    /**
     * Creates a new link to the given attribute or association.
     *
     * @param identification  the name of the link, together with optional information.
     * @param referent        the referenced attribute or feature association.
     */
    LinkOperation(final Map<String,?> identification, AbstractIdentifiedType referent) {
        super(identification);
        if (referent instanceof LinkOperation) {
            referent = ((LinkOperation) referent).result;
            // Avoiding links to links may help performance and reduce the risk of circular references.
        }
        result = referent;
        referentName = referent.getName().toString();
        if (referentName.equals(getName().toString())) {
            throw new IllegalArgumentException(Errors.format(Errors.Keys.CircularReference));
        }
    }

    /**
     * Returns a description of the input parameters.
     */
    @Override
    public ParameterDescriptorGroup getParameters() {
        return PARAMETERS;
    }

    /**
     * Returns the expected result type.
     */
    @Override
    public AbstractIdentifiedType getResult() {
        return result;
    }

    /**
     * Returns the names of feature properties that this operation needs for performing its task.
     */
    @Override
    public Set<String> getDependencies() {
        return Collections.singleton(referentName);
    }

    /**
     * Returns the property from the referenced attribute of feature association.
     *
     * @param  feature     the feature from which to get the property.
     * @param  parameters  ignored (can be {@code null}).
     * @return the linked property from the given feature.
     */
    @Override
    public Object apply(final AbstractFeature feature, final ParameterValueGroup parameters) {
        ArgumentChecks.ensureNonNull("feature", feature);
        return feature.getProperty(referentName);
    }

    /**
     * Computes a hash-code value for this operation.
     */
    @Override
    public int hashCode() {
        return super.hashCode() + referentName.hashCode();
    }

    /**
     * Compares this operation with the given object for equality.
     */
    @Override
    public boolean equals(final Object obj) {
        // 'this.result' is compared (indirectly) by the super class.
        return super.equals(obj) && referentName.equals(((LinkOperation) obj).referentName);
    }

    /**
     * Appends a string representation of the "formula" used for computing the result.
     *
     * @param  buffer  where to format the "formula".
     */
    @Override
    void formatResultFormula(final Appendable buffer) throws IOException {
        buffer.append(referentName);
    }
}


text:
<?php
namespace Damienpirsy\Teamwork;

use Damienpirsy\Teamwork\Traits\RestfulTrait;

class Tag extends AbstractObject {

    use RestfulTrait;

    protected $wrapper = 'tag';

    protected $endpoint = 'tags';
}


text:
layout: nav/sections
sections:
  - Meeting the Digital Service Standard
  - Think about each stage
  - Plan ahead
  - Share your findings
  - Where to do user research
---


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateConfigurationsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('configurations', function (Blueprint $table) {
            $table->increments('id');
            $table->string('config_name');
            $table->string('config_value');

            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('configurations');
    }
}


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Xuld.RazorEngine {

    ///
    /// 为在网页中呈现 HTML 窗体控件和执行窗体验证提供支持。
    ///
    public class HtmlHelper {

        /// 通过使用最小编码,返回表示指定对象的 HTML 编码的字符串,该最小编码仅适用于由引号引起来的 HTML 特性。
        /// <returns>表示该对象的 HTML 编码的字符串。</returns>
        /// <param name="value">要编码的对象。</param>
        public string AttributeEncode(object value) {
            return AttributeEncode(Convert.ToString(value, CultureInfo.InvariantCulture));
        }

        /// 通过使用最小编码,返回表示指定字符串的 HTML 编码的字符串,该最小编码仅适用于由引号引起来的 HTML 特性。
        /// <returns>表示原始字符串的 HTML 编码的字符串。</returns>
        /// <param name="value">要编码的字符串。</param>
        public string AttributeEncode(string value) {
            if (string.IsNullOrEmpty(value)) {
                return string.Empty;
            }
            return HttpUtility.HtmlAttributeEncode(value);
        }

        /// 通过使用适用于任意 HTML 的完整编码返回一个表示指定对象的 HTML 编码的字符串。
        /// <returns>表示该对象的 HTML 编码的字符串。</returns>
        /// <param name="value">要编码的对象。</param>
        public string Encode(object value) {
            return this.Encode(Convert.ToString(value, CultureInfo.InvariantCulture));
        }

        /// 通过使用适用于任意 HTML 的完整编码返回一个表示指定字符串的 HTML 编码的字符串。
        /// <returns>表示原始字符串的 HTML 编码的字符串。</returns>
        /// <param name="value">要编码的字符串。</param>
        public string Encode(string value) {
            if (string.IsNullOrEmpty(value)) {
                return string.Empty;
            }
            return HttpUtility.HtmlEncode(value);
        }

        /// 包装 <see cref="T:System.Web.HtmlString" /> 实例中的 HTML 标记,以便将其解释为 HTML 标记。
        /// <returns>未编码的 HTML。</returns>
        /// <param name="value">要呈现其 HTML 的对象。</param>
        public Action<TextWriter> Raw(object value) {
            return (writer) => {
                writer.Write(value);
            };
        }

        /// 包装 <see cref="T:System.Web.HtmlString" /> 实例中的 HTML 标记,以便将其解释为 HTML 标记。
        /// <returns>未编码的 HTML。</returns>
        /// <param name="value">要解释为 HTML 标记而不是进行 HTML 编码的字符串。</param>
        public HtmlString Raw(string value) {
            return new HtmlString(value);
        }

        internal readonly static HtmlHelper Instance = new HtmlHelper();

    }

}


text:
import os.path

CFG_DIR = os.path.expanduser('~/.debs')


text:
require 'active_support'
require 'action_dispatch'
require 'action_controller'
require './lib/passages'


text:
package com.jayway.jsonpath.matchers;

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.matchers.helpers.StrictParsingConfiguration;
import com.jayway.jsonpath.matchers.helpers.TestingMatchers;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.StringDescription;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.File;

import static com.jayway.jsonpath.matchers.JsonPathMatchers.isJson;
import static com.jayway.jsonpath.matchers.helpers.ResourceHelpers.resource;
import static com.jayway.jsonpath.matchers.helpers.ResourceHelpers.resourceAsFile;
import static com.jayway.jsonpath.matchers.helpers.TestingMatchers.withPathEvaluatedTo;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;

public class IsJsonTest {
    private static final String VALID_JSON = resource("example.json");
    private static final String INVALID_JSON = "{ invalid-json }";
    private static final String BOOKS_JSON_STRING = resource("books.json");
    private static final File BOOKS_JSON_FILE = resourceAsFile("books.json");
    private static final Object BOOKS_JSON_PARSED = parseJson(BOOKS_JSON_STRING);

    @BeforeClass
    public static void setupStrictJsonParsing() {
        Configuration.setDefaults(new StrictParsingConfiguration());
    }

    @AfterClass
    public static void setupDefaultJsonParsing() {
        Configuration.setDefaults(null);
    }

    @Test
    public void shouldMatchOnEmptyJsonObject() {
        assertThat("{}", isJson());
    }

    @Test
    public void shouldMatchOnJsonObject() {
        assertThat("{ \"hi\" : \"there\" }", isJson());
    }

    @Test
    public void shouldMatchOnEmptyJsonArray() {
        assertThat("[]", isJson());
    }

    @Test
    public void shouldMatchOnJsonArray() {
        assertThat("[\"hi\", \"there\"]", isJson());
    }

    @Test
    public void shouldMatchValidJson() {
        assertThat(VALID_JSON, isJson());
        assertThat(BOOKS_JSON_STRING, isJson());
    }

    @Test
    public void shouldNotMatchInvalidJson() {
        assertThat(INVALID_JSON, not(isJson()));
        assertThat(new Object(), not(isJson()));
        assertThat(new Object[]{}, not(isJson()));
        assertThat("hi there", not(isJson()));
        assertThat(new Integer(42), not(isJson()));
        assertThat(Boolean.TRUE, not(isJson()));
        assertThat(false, not(isJson()));
        assertThat(null, not(isJson()));
    }

    @Test
    public void shouldMatchJsonObjectEvaluatedToTrue() {
        assertThat(BOOKS_JSON_PARSED, isJson(withPathEvaluatedTo(true)));
    }

    @Test
    public void shouldNotMatchJsonObjectEvaluatedToFalse() {
        assertThat(BOOKS_JSON_PARSED, not(isJson(withPathEvaluatedTo(false))));
    }

    @Test
    public void shouldMatchJsonStringEvaluatedToTrue() {
        assertThat(BOOKS_JSON_STRING, isJson(withPathEvaluatedTo(true)));
    }

    @Test
    public void shouldNotMatchJsonStringEvaluatedToFalse() {
        assertThat(BOOKS_JSON_STRING, not(isJson(withPathEvaluatedTo(false))));
    }

    @Test
    public void shouldMatchJsonFileEvaluatedToTrue() {
        assertThat(BOOKS_JSON_FILE, isJson(withPathEvaluatedTo(true)));
    }

    @Test
    public void shouldNotMatchJsonFileEvaluatedToFalse() {
        assertThat(BOOKS_JSON_FILE, not(isJson(withPathEvaluatedTo(false))));
    }

    @Test
    public void shouldNotMatchNonExistingJsonFile() {
        File nonExistingFile = new File("missing-file");
        assertThat(nonExistingFile, not(isJson()));
    }

    @Test
    public void shouldBeDescriptive() {
        Matcher<Object> matcher = isJson(withPathEvaluatedTo(true));
        Description description = new StringDescription();
        matcher.describeTo(description);
        assertThat(description.toString(), startsWith("is json"));
        assertThat(description.toString(), containsString(TestingMatchers.MATCH_TRUE_TEXT));
    }

    @Test
    public void shouldDescribeMismatchOfValidJson() {
        Matcher<Object> matcher = isJson(withPathEvaluatedTo(true));
        Description description = new StringDescription();
        matcher.describeMismatch(BOOKS_JSON_STRING, description);
        assertThat(description.toString(), containsString(TestingMatchers.MISMATCHED_TEXT));
    }

    @Test
    public void shouldDescribeMismatchOfInvalidJson() {
        Matcher<Object> matcher = isJson(withPathEvaluatedTo(true));
        Description description = new StringDescription();
        matcher.describeMismatch("invalid-json", description);
        assertThat(description.toString(), containsString("\"invalid-json\""));
    }

    private static Object parseJson(String json) {
        return Configuration.defaultConfiguration().jsonProvider().parse(json);
    }

}


text:
package br.edu.ufcg.splab.designmetrics.mocks.cbo1;

public class ClassL {

    private ClassF f;

    public String getStrD() {
        ClassD d = new ClassD();
        f.setD(d);
        return "";
    }

    public String getStrE() {
        f.setE1(new ClassE());
        return "";
    }

    public Object getD() {
        return new ClassD();
    }
}


text:
package liquibase.statement;

import static org.junit.Assert.*;
import org.junit.Test;

public class AutoIncrementConstraintTest {

    @Test
    public void ctor() {
        AutoIncrementConstraint constraint = new AutoIncrementConstraint("COL_NAME");
        assertEquals("COL_NAME", constraint.getColumnName());
    }
}


text:
<?php
namespace Hawk\Filter;

use Hawk\Interfaces\Filter\FilterInterface;

/**
 *
 */
class NameFilter implements FilterInterface
{
	/**
	 * [filter description]
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public function filter($data)
	{
		return preg_replace('/[^\p{L} ]/u', '', $data); // /u allows unicode characters, e.g. á, ẽ, õ, etc.
	}
}


text:
---
uid: SolidEdgePart.Model.ContourFlanges
summary:
remarks:
example: [*content]
---
[!code-vb[Main](..\snippets\SolidEdgePart.Model.ContourFlanges.vb]
[!code-csharp[Main](..\snippets\SolidEdgePart.Model.ContourFlanges.cs]


text:
from os.path import dirname, abspath, join
from setuptools import find_packages, setup

URL = 'https://github.com/cereigido/django-sortedmanytomany/'
VERSION = __import__('sortedmanytomany').__version__

with open(abspath(join(dirname(__file__), 'README.md'))) as fileobj:
    README = fileobj.read().strip()

setup(
    name='django-sortedmanytomany',
    packages=find_packages(),
    version=VERSION,
    author='Paulo Cereigido',
    author_email='paulocereigido@gmail.com',
    description=('An extension of Django ManyToMany with ordering'),
    long_description=README,
    url=URL,
    download_url='%s/tarball/%s' % (URL, VERSION),
    zip_safe=False,
    include_package_data=True,
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Database',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
        'Topic :: Internet :: WWW/HTTP :: Site Management',
        'Topic :: Software Development :: Libraries :: Application Frameworks',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
    install_requires=[
        'Django>=1.9',
    ],
)


text:
<!DOCTYPE HTML>

    <meta http-equiv="Content-type" content="text/html; charset=utf-8">

Opacity should be applied after reflection, so you should see a green rectangle below. The overlap between the original and reflection should not be visible.


text:
layout: default
ref: index
lang: en
prevTitle: Previous Events
nextTitle: Upcoming Events
location: wix
regLink: 'http://'
callForSpeakers: If you want to share something with the community, we encourage you to drop us a line

founders:
 - klymyshyn
 - djafarov

orgs:
 - listochkin
 - john
 - tkachenko
 - frolov
---


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

package com.facebook.presto.sql.planner.optimizations;

import com.facebook.presto.Session;
import com.facebook.presto.spi.plan.AggregationNode;
import com.facebook.presto.sql.planner.Plan;
import com.facebook.presto.sql.planner.assertions.BasePlanTest;
import com.facebook.presto.sql.planner.assertions.ExpectedValueProvider;
import com.facebook.presto.sql.planner.assertions.PlanMatchPattern;
import com.facebook.presto.sql.planner.plan.ExchangeNode;
import com.facebook.presto.sql.planner.plan.GroupIdNode;
import com.facebook.presto.sql.tree.FunctionCall;
import com.facebook.presto.testing.TestingSession;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.testng.annotations.Test;

import java.util.Optional;
import java.util.function.BiConsumer;

import static com.facebook.presto.SystemSessionProperties.AGGREGATION_PARTITIONING_MERGING_STRATEGY;
import static com.facebook.presto.SystemSessionProperties.EXCHANGE_MATERIALIZATION_STRATEGY;
import static com.facebook.presto.SystemSessionProperties.JOIN_DISTRIBUTION_TYPE;
import static com.facebook.presto.SystemSessionProperties.JOIN_REORDERING_STRATEGY;
import static com.facebook.presto.SystemSessionProperties.PARTITIONING_PRECISION_STRATEGY;
import static com.facebook.presto.SystemSessionProperties.TASK_CONCURRENCY;
import static com.facebook.presto.SystemSessionProperties.USE_STREAMING_EXCHANGE_FOR_MARK_DISTINCT;
import static com.facebook.presto.execution.QueryManagerConfig.ExchangeMaterializationStrategy.ALL;
import static com.facebook.presto.spi.plan.AggregationNode.Step.SINGLE;
import static com.facebook.presto.sql.analyzer.FeaturesConfig.JoinDistributionType.PARTITIONED;
import static com.facebook.presto.sql.analyzer.FeaturesConfig.JoinReorderingStrategy.ELIMINATE_CROSS_JOINS;
import static com.facebook.presto.sql.analyzer.FeaturesConfig.PartitioningPrecisionStrategy.PREFER_EXACT_PARTITIONING;
import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.aggregation;
import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.anySymbol;
import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.anyTree;
import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.equiJoinClause;
import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.exchange;
import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.join;
import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.node;
import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.semiJoin;
import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.singleGroupingSet;
import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.tableScan;
import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.values;
import static com.facebook.presto.sql.planner.optimizations.PlanNodeSearcher.searchFrom;
import static com.facebook.presto.sql.planner.plan.ExchangeNode.Scope.LOCAL;
import static com.facebook.presto.sql.planner.plan.ExchangeNode.Scope.REMOTE_MATERIALIZED;
import static com.facebook.presto.sql.planner.plan.ExchangeNode.Scope.REMOTE_STREAMING;
import static com.facebook.presto.sql.planner.plan.ExchangeNode.Type.REPARTITION;
import static com.facebook.presto.sql.planner.plan.JoinNode.Type.INNER;
import static org.testng.Assert.assertEquals;

/**
 * These are plan tests similar to what we have for other optimizers (e.g. {@link com.facebook.presto.sql.planner.TestPredicatePushdown})
 * They test that the plan for a query after the optimizer runs is as expected.
 * These are separate from {@link TestAddExchanges} because those are unit tests for
 * how layouts get chosen.
 */
public class TestAddExchangesPlans
        extends BasePlanTest
{
    @Test
    public void testRepartitionForUnionWithAnyTableScans()
    {
        assertDistributedPlan("SELECT nationkey FROM nation UNION select regionkey from region",
                anyTree(
                        aggregation(ImmutableMap.of(),
                                anyTree(
                                        anyTree(
                                                exchange(REMOTE_STREAMING, REPARTITION,
                                                        anyTree(
                                                                tableScan("nation")))),
                                        anyTree(
                                                exchange(REMOTE_STREAMING, REPARTITION,
                                                        anyTree(
                                                                tableScan("region"))))))));
        assertDistributedPlan("SELECT nationkey FROM nation UNION select 1",
                anyTree(
                        aggregation(ImmutableMap.of(),
                                anyTree(
                                        anyTree(
                                                exchange(REMOTE_STREAMING, REPARTITION,
                                                        anyTree(
                                                                tableScan("nation")))),
                                        anyTree(
                                                exchange(REMOTE_STREAMING, REPARTITION,
                                                        anyTree(
                                                                values())))))));
    }

    @Test
    public void testRepartitionForUnionAllBeforeHashJoin()
    {
        Session session = Session.builder(this.getQueryRunner().getDefaultSession())
                .setSystemProperty(JOIN_REORDERING_STRATEGY, ELIMINATE_CROSS_JOINS.name())
                .setSystemProperty(JOIN_DISTRIBUTION_TYPE, PARTITIONED.name())
                .build();
        assertPlanWithSession("SELECT * FROM (SELECT nationkey FROM nation UNION ALL select nationkey from nation) n join region r on n.nationkey = r.regionkey",
                session,
                false,
                anyTree(
                        join(INNER, ImmutableList.of(equiJoinClause("nationkey", "regionkey")),
                                anyTree(
                                        exchange(REMOTE_STREAMING, REPARTITION,
                                                anyTree(
                                                        tableScan("nation", ImmutableMap.of("nationkey", "nationkey")))),
                                        exchange(REMOTE_STREAMING, REPARTITION,
                                                anyTree(
                                                        tableScan("nation")))),
                                anyTree(
                                        exchange(REMOTE_STREAMING, REPARTITION,
                                                anyTree(
                                                        tableScan("region", ImmutableMap.of("regionkey", "regionkey"))))))));

        assertPlanWithSession("SELECT * FROM (SELECT nationkey FROM nation UNION ALL select 1) n join region r on n.nationkey = r.regionkey",
                session,
                false,
                anyTree(
                        join(INNER, ImmutableList.of(equiJoinClause("nationkey", "regionkey")),
                                anyTree(
                                        exchange(REMOTE_STREAMING, REPARTITION,
                                                anyTree(
                                                        tableScan("nation", ImmutableMap.of("nationkey", "nationkey")))),
                                        exchange(REMOTE_STREAMING, REPARTITION,
                                                anyTree(
                                                        values()))),
                                anyTree(
                                        exchange(REMOTE_STREAMING, REPARTITION,
                                                anyTree(
                                                        tableScan("region", ImmutableMap.of("regionkey", "regionkey"))))))));
    }

    private void assertPlanWithMergePartitionStrategy(
            String sql,
            String partitionMergingStrategy,
            int remoteRepartitionExchangeCount,
            PlanMatchPattern pattern)
    {
        Session session = Session.builder(this.getQueryRunner().getDefaultSession())
                .setSystemProperty(AGGREGATION_PARTITIONING_MERGING_STRATEGY, partitionMergingStrategy)
                .setSystemProperty(TASK_CONCURRENCY, "2")
                .build();
        BiConsumer<Plan, Integer> validateMultipleRemoteRepartitionExchange = (plan, count) -> assertEquals(
                searchFrom(plan.getRoot()).where(node -> node instanceof ExchangeNode && ((ExchangeNode) node).getScope() == REMOTE_STREAMING && ((ExchangeNode) node).getType() == REPARTITION).count(),
                count.intValue());

        assertPlanWithSession(sql, session, false, pattern, plan -> validateMultipleRemoteRepartitionExchange.accept(plan, remoteRepartitionExchangeCount));
    }

    @Test
    public void testMergePartitionWithGroupingSets()
    {
        String sql = "SELECT orderkey, count(distinct(custkey)) FROM orders GROUP BY GROUPING SETS((orderkey), ())";

        assertPlanWithMergePartitionStrategy(sql, "bottom_up", 2,
                anyTree(node(AggregationNode.class,
                        anyTree(exchange(REMOTE_STREAMING, REPARTITION,
                                node(AggregationNode.class,
                                        anyTree(node(AggregationNode.class,
                                                anyTree(exchange(REMOTE_STREAMING, REPARTITION,
                                                        node(AggregationNode.class,
                                                                anyTree(node(GroupIdNode.class,
                                                                        tableScan("orders"))))))))))))));
        assertPlanWithMergePartitionStrategy(sql, "top_down", 2,
                anyTree(node(AggregationNode.class,
                        anyTree(exchange(REMOTE_STREAMING, REPARTITION,
                                node(AggregationNode.class,
                                        anyTree(node(AggregationNode.class,
                                                anyTree(exchange(REMOTE_STREAMING, REPARTITION,
                                                        node(AggregationNode.class,
                                                                anyTree(node(GroupIdNode.class,
                                                                        tableScan("orders"))))))))))))));
    }

    @Test
    public void testMergePartitionWithAggregation()
    {
        String sql = "SELECT count(orderdate), custkey FROM (SELECT orderdate, custkey FROM orders GROUP BY orderdate, custkey) GROUP BY custkey";

        // disable merging partition preference
        assertPlanWithMergePartitionStrategy(sql, "bottom_up", 2,
                anyTree(node(AggregationNode.class,
                        anyTree(exchange(REMOTE_STREAMING, REPARTITION,
                                anyTree(node(AggregationNode.class,
                                        node(AggregationNode.class,
                                                anyTree(exchange(REMOTE_STREAMING, REPARTITION,
                                                        node(AggregationNode.class,
                                                                anyTree(tableScan("orders")))))))))))));

        // enable merging partition preference
        assertPlanWithMergePartitionStrategy(sql, "top_down", 1,
                anyTree(node(AggregationNode.class,
                        node(AggregationNode.class,
                                anyTree(exchange(REMOTE_STREAMING, REPARTITION,
                                        anyTree(node(AggregationNode.class,
                                                anyTree(tableScan("orders"))))))))));
    }

    @Test
    public void testAggregateIsExactlyPartitioned()
    {
        assertExactDistributedPlan(
                "SELECT\n" +
                        "    AVG(1)\n" +
                        "FROM (\n" +
                        "    SELECT\n" +
                        "        orderkey,\n" +
                        "        orderstatus,\n" +
                        "        COUNT(*)\n" +
                        "    FROM orders\n" +
                        "    WHERE\n" +
                        "        orderdate > CAST('2042-01-01' AS DATE)\n" +
                        "    GROUP BY\n" +
                        "        orderkey,\n" +
                        "        orderstatus\n" +
                        ")\n" +
                        "GROUP BY\n" +
                        "    orderkey",
                anyTree(
                        exchange(REMOTE_STREAMING, REPARTITION,
                                anyTree(
                                        exchange(REMOTE_STREAMING, REPARTITION,
                                                anyTree(
                                                        tableScan("orders", ImmutableMap.of(
                                                                "ordertatus", "orderstatus",
                                                                "orderkey", "orderkey",
                                                                "orderdate", "orderdate"))))))));
    }

    @Test
    public void testWindowIsExactlyPartitioned()
    {
        assertExactDistributedPlan(
                "SELECT\n" +
                        "    AVG(otherwindow) OVER (\n" +
                        "        PARTITION BY\n" +
                        "            orderkey\n" +
                        "    )\n" +
                        "FROM (\n" +
                        "    SELECT\n" +
                        "        orderkey,\n" +
                        "        orderstatus,\n" +
                        "        COUNT(*) OVER (\n" +
                        "            PARTITION BY\n" +
                        "                orderkey,\n" +
                        "                orderstatus\n" +
                        "        ) AS otherwindow\n" +
                        "    FROM orders\n" +
                        "    WHERE\n" +
                        "        orderdate > CAST('2042-01-01' AS DATE)\n" +
                        ")",
                anyTree(
                        exchange(REMOTE_STREAMING, REPARTITION,
                                anyTree(
                                        exchange(REMOTE_STREAMING, REPARTITION,
                                                anyTree(
                                                        tableScan("orders", ImmutableMap.of(
                                                                "orderkey", "orderkey",
                                                                "orderdate", "orderdate"))))))));
    }

    @Test
    public void testRowNumberIsExactlyPartitioned()
    {
        assertExactDistributedPlan(
                "SELECT\n" +
                        "    *\n" +
                        "FROM (\n" +
                        "    SELECT\n" +
                        "        a,\n" +
                        "        ROW_NUMBER() OVER (\n" +
                        "            PARTITION BY\n" +
                        "                a\n" +
                        "        ) rn\n" +
                        "    FROM (\n" +
                        "        VALUES\n" +
                        "            (1)\n" +
                        "    ) t (a)\n" +
                        ") t",
                anyTree(
                        exchange(REMOTE_STREAMING, REPARTITION,
                                anyTree(
                                        values("a")))));
    }

    @Test
    public void testTopNRowNumberIsExactlyPartitioned()
    {
        assertExactDistributedPlan(
                "SELECT\n" +
                        "    a,\n" +
                        "    ROW_NUMBER() OVER (\n" +
                        "        PARTITION BY\n" +
                        "            a\n" +
                        "        ORDER BY\n" +
                        "            a\n" +
                        "    ) rn\n" +
                        "FROM (\n" +
                        "    SELECT\n" +
                        "        a,\n" +
                        "        b,\n" +
                        "        COUNT(*)\n" +
                        "    FROM (\n" +
                        "        VALUES\n" +
                        "            (1, 2),\n" +
                        "            (1, 2)\n" +
                        "    ) t (a, b)\n" +
                        "    GROUP BY\n" +
                        "        a,\n" +
                        "        b\n" +
                        ")\n" +
                        "LIMIT\n" +
                        "    2",
                anyTree(
                        exchange(REMOTE_STREAMING, REPARTITION,
                                anyTree(
                                        values("a", "b")))));
    }

    @Test
    public void testJoinExactlyPartitioned()
    {
        ExpectedValueProvider<FunctionCall> arbitrary = PlanMatchPattern.functionCall("arbitrary", false, ImmutableList.of(anySymbol()));
        assertExactDistributedPlan(
                "SELECT\n" +
                        "    orders.orderkey,\n" +
                        "    orders.orderstatus\n" +
                        "FROM (\n" +
                        "    SELECT\n" +
                        "        orderkey,\n" +
                        "        ARBITRARY(orderstatus) AS orderstatus,\n" +
                        "        COUNT(*)\n" +
                        "    FROM orders\n" +
                        "    GROUP BY\n" +
                        "        orderkey\n" +
                        ") t,\n" +
                        "orders\n" +
                        "WHERE\n" +
                        "    orders.orderkey = t.orderkey\n" +
                        "    AND orders.orderstatus = t.orderstatus",
                anyTree(
                        join(INNER, ImmutableList.of(
                                equiJoinClause("ORDERKEY_LEFT", "ORDERKEY_RIGHT"),
                                equiJoinClause("orderstatus", "ORDERSTATUS_RIGHT")),
                                exchange(REMOTE_STREAMING, REPARTITION,
                                        anyTree(
                                                aggregation(
                                                        singleGroupingSet("ORDERKEY_LEFT"),
                                                        ImmutableMap.of(Optional.of("orderstatus"), arbitrary),
                                                        ImmutableList.of("ORDERKEY_LEFT"),
                                                        ImmutableMap.of(),
                                                        Optional.empty(),
                                                        SINGLE,
                                                        tableScan("orders", ImmutableMap.of(
                                                                "ORDERKEY_LEFT", "orderkey",
                                                                "ORDERSTATUS_LEFT", "orderstatus"))))),
                                exchange(LOCAL, REPARTITION,
                                        exchange(REMOTE_STREAMING, REPARTITION,
                                                anyTree(
                                                        tableScan("orders", ImmutableMap.of(
                                                                "ORDERKEY_RIGHT", "orderkey",
                                                                "ORDERSTATUS_RIGHT", "orderstatus"))))))));
    }

    @Test
    public void testSemiJoinExactlyPartitioned()
    {
        assertExactDistributedPlan(
                "SELECT\n" +
                        "    orderkey\n" +
                        "FROM orders\n" +
                        "WHERE\n" +
                        "    orderkey IN (\n" +
                        "        SELECT\n" +
                        "            orderkey\n" +
                        "        FROM orders\n" +
                        "        WHERE\n" +
                        "            orderkey IS NULL\n" +
                        "            AND orderstatus IS NULL\n" +
                        "    )",
                anyTree(
                        semiJoin("ORDERKEY_OK", "VALUE_ORDERKEY", "S",
                                exchange(REMOTE_STREAMING, REPARTITION,
                                        anyTree(
                                                tableScan("orders", ImmutableMap.of(
                                                        "ORDERKEY_OK", "orderkey")))),
                                anyTree(

                                        exchange(REMOTE_STREAMING, REPARTITION,
                                                anyTree(
                                                        values("VALUE_ORDERKEY")))))));
    }

    @Test
    public void testMarkDistinctIsExactlyPartitioned()
    {
        assertExactDistributedPlan(
                "    SELECT\n" +
                        "        orderkey,\n" +
                        "        orderstatus,\n" +
                        "        COUNT(DISTINCT orderdate),\n" +
                        "        COUNT(DISTINCT clerk)\n" +
                        "    FROM orders\n" +
                        "    WHERE\n" +
                        "        orderdate > CAST('2042-01-01' AS DATE)\n" +
                        "    GROUP BY\n" +
                        "        orderkey,\n" +
                        "        orderstatus\n",
                anyTree(
                        exchange(REMOTE_STREAMING, REPARTITION,
                                anyTree(
                                        exchange(REMOTE_STREAMING, REPARTITION,
                                                anyTree(
                                                        exchange(REMOTE_STREAMING, REPARTITION,
                                                                anyTree(
                                                                        tableScan("orders", ImmutableMap.of(
                                                                                "orderstatus", "orderstatus",
                                                                                "orderkey", "orderkey",
                                                                                "clerk", "clerk",
                                                                                "orderdate", "orderdate"))))))))));
    }

    @Test
    public void testMarkDistinctStreamingExchange()
    {
        assertMaterializedWithStreamingMarkDistinctDistributedPlan(
                "    SELECT\n" +
                        "        orderkey,\n" +
                        "        orderstatus,\n" +
                        "        COUNT(DISTINCT orderdate),\n" +
                        "        COUNT(DISTINCT clerk)\n" +
                        "    FROM orders\n" +
                        "    WHERE\n" +
                        "        orderdate > CAST('2042-01-01' AS DATE)\n" +
                        "    GROUP BY\n" +
                        "        orderkey,\n" +
                        "        orderstatus\n",
                anyTree(
                        exchange(REMOTE_MATERIALIZED, REPARTITION,
                                anyTree(
                                        exchange(REMOTE_STREAMING, REPARTITION,
                                                anyTree(
                                                        exchange(REMOTE_STREAMING, REPARTITION,
                                                                anyTree(
                                                                        tableScan("orders", ImmutableMap.of(
                                                                                "orderstatus", "orderstatus",
                                                                                "orderkey", "orderkey",
                                                                                "clerk", "clerk",
                                                                                "orderdate", "orderdate"))))))))));
    }

    void assertMaterializedWithStreamingMarkDistinctDistributedPlan(String sql, PlanMatchPattern pattern)
    {
        assertDistributedPlan(
                sql,
                TestingSession.testSessionBuilder()
                        .setCatalog("local")
                        .setSchema("tiny")
                        .setSystemProperty(PARTITIONING_PRECISION_STRATEGY, PREFER_EXACT_PARTITIONING.toString())
                        .setSystemProperty(EXCHANGE_MATERIALIZATION_STRATEGY, ALL.toString())
                        .setSystemProperty(USE_STREAMING_EXCHANGE_FOR_MARK_DISTINCT, "true")
                        .build(),
                pattern);
    }

    void assertExactDistributedPlan(String sql, PlanMatchPattern pattern)
    {
        assertDistributedPlan(
                sql,
                TestingSession.testSessionBuilder()
                        .setCatalog("local")
                        .setSchema("tiny")
                        .setSystemProperty(JOIN_REORDERING_STRATEGY, ELIMINATE_CROSS_JOINS.toString())
                        .setSystemProperty(JOIN_DISTRIBUTION_TYPE, PARTITIONED.toString())
                        .setSystemProperty(PARTITIONING_PRECISION_STRATEGY, PREFER_EXACT_PARTITIONING.toString())
                        .build(),
                pattern);
    }
}


text:
var markdown = require('./markdown');

exports.toMarkdown = function(snippets, config) {
    var page, isNew, snippet;

    isNew = true;

    for (var j = 0; j < snippets.length; j += 1) {
        snippet = snippets[j];
        if (isNew) {
            isNew = false;
            page = markdown.header(snippet, config);
            page += markdown.example(snippet, j, false);
        } else {
            page += markdown.example(snippet, j, true);
        }
    }
    page += markdown.footer(snippets.length);
    return page;
};

exports.toYaml = function(snippet) {
    return snippet;
};


text:
require "formula"

class Tpl < Formula
  homepage "http://troydhanson.github.io/tpl/"
  url "https://github.com/troydhanson/tpl/archive/v1.6.1.tar.gz"
  sha1 "2ee92627e8f67400061d8fc606b601988ed90217"
  head "https://github.com/troydhanson/tpl.git"

  depends_on "autoconf" => :build
  depends_on "automake" => :build
  depends_on "libtool" => :build

  def install
    system "autoreconf", "-fvi"
    system "./configure", "--disable-dependency-tracking",
                          "--disable-silent-rules",
                          "--prefix=#{prefix}"
    system "make", "install"
    system "make", "-C", "tests"
  end
end


text:
include makes/env.mk
include makes/docker.mk

.PHONY: migrate
migrate:
	touch data/dzone.db
	sqlite3 data/dzone.db < migration/2017-03-16-create-reading-list.sql

.PHONY: run
run: build
run:
	chmod +x bin/web
	bin/web

.PHONY: build
build:
	go build -i -o bin/web cmd/web/main.go

.PHONY: profile-local
profile-local:
	go tool pprof $(strip $(ARGS)) $(shell curl http://localhost:8080/debug/pprof/cmdline) http://127.0.0.1:8080/debug/pprof/profile

.PHONY: profile-goroutine-local
profile-goroutine-local:
	go tool pprof $(strip $(ARGS)) $(shell curl http://localhost:8080/debug/pprof/cmdline) http://127.0.0.1:8080/debug/pprof/goroutine

.PHONY: profile-threadcreate-local
profile-threadcreate-local:
	go tool pprof $(strip $(ARGS)) $(shell curl http://localhost:8080/debug/pprof/cmdline) http://127.0.0.1:8080/debug/pprof/threadcreate

# useful ARGS=-alloc_objects, -inuse_objects, -alloc_space
.PHONY: profile-heap-local
profile-heap-local:
	go tool pprof $(strip $(ARGS)) $(shell curl http://localhost:8080/debug/pprof/cmdline) http://127.0.0.1:8080/debug/pprof/heap

.PHONY: profile-block-local
profile-block-local:
	go tool pprof $(strip $(ARGS)) $(shell curl http://localhost:8080/debug/pprof/cmdline) http://127.0.0.1:8080/debug/pprof/block

.PHONY: profile-mutex-local
profile-mutex-local:
	go tool pprof $(strip $(ARGS)) $(shell curl http://localhost:8080/debug/pprof/cmdline) http://127.0.0.1:8080/debug/pprof/mutex


text:
.class public final Landroid/media/ClosedCaption$Justification;
.super Ljava/lang/Object;
.source "ClosedCaption.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/media/ClosedCaption;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "Justification"
.end annotation

# instance fields
.field public final horizontalJustification:I

.field public final verticalJustification:I

# direct methods
.method public constructor <init>(II)V
    .locals 0
    .param p1, "horizontal"    # I
    .param p2, "vertical"    # I

    .prologue
    .line 184
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 185
    iput p1, p0, Landroid/media/ClosedCaption$Justification;->horizontalJustification:I

    .line 186
    iput p2, p0, Landroid/media/ClosedCaption$Justification;->verticalJustification:I

    .line 187
    return-void
.end method


text:
using static System.Runtime.Intrinsics.X86.Avx;
using static System.Runtime.Intrinsics.X86.Sse;
using System.Runtime.Intrinsics.X86;
using System.Runtime.Intrinsics;
using System.Runtime.CompilerServices;
using System;

internal struct VectorPacket256
{
    public Vector256<float> Xs;
    public Vector256<float> Ys;
    public Vector256<float> Zs;
    public Vector256<float> Lengths
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        get
        {
            return Sqrt(DotProduct(this, this));
        }
    }

    public readonly static int Packet256Size = 8;

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public VectorPacket256(Vector256<float> init)
    {
        Xs = init;
        Ys = init;
        Zs = init;
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public VectorPacket256(float xs, float ys, float zs)
    {
        Xs = Vector256.Create(xs);
        Ys = Vector256.Create(ys);
        Zs = Vector256.Create(zs);
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public VectorPacket256(Vector256<float> _Xs, Vector256<float> _ys, Vector256<float> _Zs)
    {
        Xs = _Xs;
        Ys = _ys;
        Zs = _Zs;
    }

    // Convert AoS vectors to SoA Packet256
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public unsafe VectorPacket256(float* vectors)
    {
        Vector256<float> m03 = LoadVector128(&vectors[0]).ToVector256(); // load lower halves
        Vector256<float> m14 = LoadVector128(&vectors[4]).ToVector256();
        Vector256<float> m25 = LoadVector128(&vectors[8]).ToVector256();
        m03 = InsertVector128(m03, LoadVector128(&vectors[12]), 1);  // load higher halves
        m14 = InsertVector128(m14, LoadVector128(&vectors[16]), 1);
        m25 = InsertVector128(m25, LoadVector128(&vectors[20]), 1);

        var xy = Shuffle(m14, m25, 2 << 6 | 1 << 4 | 3 << 2 | 2);
        var yz = Shuffle(m03, m14, 1 << 6 | 0 << 4 | 2 << 2 | 1);
        var _Xs = Shuffle(m03, xy, 2 << 6 | 0 << 4 | 3 << 2 | 0);
        var _ys = Shuffle(yz, xy, 3 << 6 | 1 << 4 | 2 << 2 | 0);
        var _Zs = Shuffle(yz, m25, 3 << 6 | 0 << 4 | 3 << 2 | 1);

        Xs = _Xs;
        Ys = _ys;
        Zs = _Zs;
    }

    // Convert SoA VectorPacket256 to AoS
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public VectorPacket256 Transpose()
    {
        var rxy = Shuffle(Xs, Ys, 2 << 6 | 0 << 4 | 2 << 2 | 0);
        var ryz = Shuffle(Ys, Zs, 3 << 6 | 1 << 4 | 3 << 2 | 1);
        var rzx = Shuffle(Zs, Xs, 3 << 6 | 1 << 4 | 2 << 2 | 0);

        var r03 = Shuffle(rxy, rzx, 2 << 6 | 0 << 4 | 2 << 2 | 0);
        var r14 = Shuffle(ryz, rxy, 3 << 6 | 1 << 4 | 2 << 2 | 0);
        var r25 = Shuffle(rzx, ryz, 3 << 6 | 1 << 4 | 3 << 2 | 1);

        var m0 = r03.GetLower();
        var m1 = r14.GetLower();
        var m2 = r25.GetLower();
        var m3 = ExtractVector128(r03, 1);
        var m4 = ExtractVector128(r14, 1);
        var m5 = ExtractVector128(r25, 1);

        var _Xs = Vector256.Create(m0, m1);
        var _ys = Vector256.Create(m2, m3);
        var _Zs = Vector256.Create(m4, m5);

        return new VectorPacket256(_Xs, _ys, _Zs);
    }

    // Convert SoA VectorPacket256 to an incomplete AoS
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public VectorPacket256 FastTranspose()
    {
        var rxy = Shuffle(Xs, Ys, 2 << 6 | 0 << 4 | 2 << 2 | 0);
        var ryz = Shuffle(Ys, Zs, 3 << 6 | 1 << 4 | 3 << 2 | 1);
        var rzx = Shuffle(Zs, Xs, 3 << 6 | 1 << 4 | 2 << 2 | 0);

        var r03 = Shuffle(rxy, rzx, 2 << 6 | 0 << 4 | 2 << 2 | 0);
        var r14 = Shuffle(ryz, rxy, 3 << 6 | 1 << 4 | 2 << 2 | 0);
        var r25 = Shuffle(rzx, ryz, 3 << 6 | 1 << 4 | 3 << 2 | 1);

        return new VectorPacket256(r03, r14, r25);
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static VectorPacket256 operator +(VectorPacket256 left, VectorPacket256 right)
    {
        return new VectorPacket256(Add(left.Xs, right.Xs), Add(left.Ys, right.Ys), Add(left.Zs, right.Zs));
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static VectorPacket256 operator -(VectorPacket256 left, VectorPacket256 right)
    {
        return new VectorPacket256(Subtract(left.Xs, right.Xs), Subtract(left.Ys, right.Ys), Subtract(left.Zs, right.Zs));
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static VectorPacket256 operator /(VectorPacket256 left, VectorPacket256 right)
    {
        return new VectorPacket256(Divide(left.Xs, right.Xs), Divide(left.Ys, right.Ys), Divide(left.Zs, right.Zs));
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static Vector256<float> DotProduct(VectorPacket256 left, VectorPacket256 right)
    {
        var x2 = Multiply(left.Xs, right.Xs);
        var y2 = Multiply(left.Ys, right.Ys);
        var z2 = Multiply(left.Zs, right.Zs);
        return Add(Add(x2, y2), z2);
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static VectorPacket256 CrossProduct(VectorPacket256 left, VectorPacket256 right)
    {
        return new VectorPacket256(Subtract(Multiply(left.Ys, right.Zs), Multiply(left.Zs, right.Ys)),
                                   Subtract(Multiply(left.Zs, right.Xs), Multiply(left.Xs, right.Zs)),
                                   Subtract(Multiply(left.Xs, right.Ys), Multiply(left.Ys, right.Xs)));
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static VectorPacket256 operator *(Vector256<float> left, VectorPacket256 right)
    {
        return new VectorPacket256(Multiply(left, right.Xs), Multiply(left, right.Ys), Multiply(left, right.Zs));
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public VectorPacket256 Normalize()
    {
        var length = this.Lengths;
        return new VectorPacket256(Divide(Xs, length), Divide(Ys, length), Divide(Zs, length));
    }
}


text:
/* global io */

/**
 * @ngdoc service
 * @name  Socket
 * @todo  add namespacing (io.for(projectId)) to decrease traffic and make sure more projects can be active at once.
 * @description Manages socket operations.
 */
angular.module('projiSeApp')
    .factory('socket', function(socketFactory) {
    'use strict';

    // Websockets on openshift
    // var ioSocket = io('http://projise-klind.rhcloud.com:8000/', {
    // socket.io now auto-configures its connection when we ommit a connection url
    var ioSocket = io(null, {
        // Send auth token on connection, you will need to DI the Auth service above
        // 'query': 'token=' + Auth.getToken()
    });

    var socket = socketFactory({
        ioSocket: ioSocket
    });

    return {
        socket: socket,

        /**
         * @ngdoc function
         * @name  syncUpdates
         * @param {String} modelName
         * @param {Array} array
         * @param {Function} cb
         * @description Register listeners to sync an array with updates on a model
         *
         * Takes the array we want to sync, the model name that socket updates are sent from,
         * and an optional callback function after new items are updated.
         */
        syncUpdates: function(modelName, array, isSprintBacklog, cb) {
            cb = cb || angular.noop;

            /**
             * Syncs item creation/updates on 'model:save'
             */
            socket.on(modelName + ':save', function(item) {
                var oldItem;

                if (item === null) {
                    return;
                }
                if (!_.isArray(array)) {

                    if (!array) {
                        angular.copy(item, array);
                        cb('updated', item, array);
                    }
                    if (!_.isArray(item) && !_.isArray(array)) {
                        if (array._id === item._id) {
                            angular.copy(item, array);
                            cb('updated', item, array);
                        }
                    }
                } else {
                    oldItem = _.find(array, {
                        _id: item._id
                    });
                    var index = array.indexOf(oldItem);
                    var event = 'created';

                    if (oldItem) {
                        if (modelName === 'story' && oldItem.sprintId && !item.sprintId && isSprintBacklog === true) {
                            _.remove(array, {_id: item._id});
                        } else {
                            array.splice(index, 1, item);
                            event = 'updated';
                        }
                    } else {
                        array.push(item);
                    }

                    cb(event, item, array);
                }
            });

            /**
             * Syncs removed items on 'model:remove'
             */
            socket.on(modelName + ':remove', function(item) {
                var event = 'deleted';
                _.remove(array, {
                    _id: item._id
                });
                cb(event, item, array);
            });
        },

        /**
         * @ngdoc function
         * @name  unsyncUpdates
         * @param modelName
         * @description Removes listeners for a models updates on the socket
         */
        unsyncUpdates: function(modelName) {
            socket.removeAllListeners(modelName + ':save');
            socket.removeAllListeners(modelName + ':remove');
        }
    };
});


text:
<?php

namespace CachetHQ\Tests\Cachet;

use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestListener as PHPUnitTestListener;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Framework\Warning;

/**
 * This is the test listener class.
 *
 * @author Connor S. Parks <connor@connorvg.tv>
 */
class TestListener implements PHPUnitTestListener
{
    /**
     * An error occurred.
     */
    public function addError(Test $test, \Throwable $t, float $time): void
    {
        //
    }

    /**
     * A warning occurred.
     */
    public function addWarning(Test $test, Warning $e, float $time): void
    {
        //
    }

    /**
     * A failure occurred.
     */
    public function addFailure(Test $test, AssertionFailedError $e, float $time): void
    {
        //
    }

    /**
     * Incomplete test.
     */
    public function addIncompleteTest(Test $test, \Throwable $t, float $time): void
    {
        //
    }

    /**
     * Risky test.
     */
    public function addRiskyTest(Test $test, \Throwable $t, float $time): void
    {
        //
    }

    /**
     * Skipped test.
     */
    public function addSkippedTest(Test $test, \Throwable $t, float $time): void
    {
        //
    }

    /**
     * A test suite started.
     */
    public function startTestSuite(TestSuite $suite): void
    {
        //
    }

    /**
     * A test suite ended.
     */
    public function endTestSuite(TestSuite $suite): void
    {
        if ($suite->getName() !== 'Cachet Test Suite') {
            return;
        }

        foreach (glob(__DIR__.'/../bootstrap/cache{,t}/*.php', GLOB_BRACE) as $file) {
            unlink($file);
        }
    }

    /**
     * A test started.
     */
    public function startTest(Test $test): void
    {
        //
    }

    /**
     * A test ended.
     */
    public function endTest(Test $test, float $time): void
    {
        //
    }
}


text:
package org.lognet.springboot.grpc.validation;

import io.grpc.ForwardingServerCall;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.lognet.springboot.grpc.FailureHandlingSupport;
import org.lognet.springboot.grpc.MessageBlockingServerCallListener;
import org.lognet.springboot.grpc.recovery.GRpcRuntimeExceptionWrapper;
import org.lognet.springboot.grpc.validation.group.RequestMessage;
import org.lognet.springboot.grpc.validation.group.ResponseMessage;
import org.springframework.core.Ordered;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import java.util.Optional;
import java.util.Set;

public class ValidatingInterceptor implements ServerInterceptor, Ordered {
    private final Validator validator;

    @Setter
    @Accessors(fluent = true)
    private Integer order;

    private final FailureHandlingSupport failureHandlingSupport;

    public ValidatingInterceptor(Validator validator,FailureHandlingSupport failureHandlingSupport) {
        this.validator = validator;
        this.failureHandlingSupport = failureHandlingSupport;
    }

    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {

        final ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT> validationServerCall = new ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT>(call) {

            @Override
            public void sendMessage(RespT message) {
                final Set<ConstraintViolation<RespT>> violations = validator.validate(message, ResponseMessage.class);
                if (!violations.isEmpty()) {
                    GRpcRuntimeExceptionWrapper exception = new GRpcRuntimeExceptionWrapper(new ConstraintViolationException(violations), Status.FAILED_PRECONDITION);
                    failureHandlingSupport.closeCall(exception, this , headers, b -> b.response(message));
                } else {
                    super.sendMessage(message);
                }
            }
        };
        ServerCall.Listener<ReqT> listener = next.startCall(validationServerCall, headers);

        return new MessageBlockingServerCallListener<ReqT>(listener) {

            @Override
            public void onMessage(ReqT message) {
                final Set<ConstraintViolation<ReqT>> violations = validator.validate(message, RequestMessage.class);
                if (!violations.isEmpty()) {
                    blockMessage();
                    final GRpcRuntimeExceptionWrapper exception = new GRpcRuntimeExceptionWrapper(new ConstraintViolationException(violations), Status.INVALID_ARGUMENT);
                    failureHandlingSupport.closeCall(exception,  validationServerCall, headers, b -> b.request(message));
                } else {
                    super.onMessage(message);
                }

            }
        };

    }

    @Override
    public int getOrder() {
        return Optional.ofNullable(order).orElse(HIGHEST_PRECEDENCE + 10);
    }
}


text:
#if !USE_PRODUCTION_API
using System;
using System.Reactive.Disposables;
using CoreGraphics;
using Toggl.Core.UI.Extensions;
using Toggl.Core.UI.Navigation;
using Toggl.Core.UI.ViewModels;
using Toggl.Core.Services;
using Toggl.iOS.Extensions;
using Toggl.iOS.Extensions.Reactive;
using Toggl.Shared.Extensions;
using UIKit;
using Foundation;

namespace Toggl.iOS.DebugHelpers
{
    public class ErrorTriggeringViewController : UIViewController
    {
        private readonly CompositeDisposable disposeBag = new CompositeDisposable();

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            View.Layer.CornerRadius = 3;
            View.BackgroundColor = UIColor.White;

            var screenWidth = UIScreen.MainScreen.Bounds.Width;
            PreferredContentSize = new CGSize
            {
                // ScreenWidth - 32 for 16pt margins on both sides
                Width = screenWidth > 320 ? screenWidth - 32 : 312,
                Height = 233
            };

            var tokenReset = createButton("Token reset error");
            var noWorkspace = createButton("No workspace error");
            var noDefaultWorkspace = createButton("No default workspace error");
            var outdatedApp = createButton("Outdated client error");
            var outdatedApi = createButton("Outdated API error");
            var outdatedAppPermanently = createButton("Permanent outdated client error");
            var outdatedApiPermanently = createButton("Permanent outdated API error");
            var shareUnsyncableEntitiesDump = createButton("Share unsyncable entities dump");
            var resetOnboarding = createButton("Reset onboarding");

            tokenReset.Rx().Tap()
                .Subscribe(dismissAndThenRun(tokenResetErrorTriggered))
                .DisposedBy(disposeBag);

            noWorkspace.Rx().Tap()
                .Subscribe(dismissAndThenRun(noWorkspaceErrorTriggered))
                .DisposedBy(disposeBag);

            noDefaultWorkspace.Rx().Tap()
                .Subscribe(dismissAndThenRun(noDefaultWorkspaceErrorTriggered))
                .DisposedBy(disposeBag);

            outdatedApp.Rx().Tap()
                .Subscribe(dismissAndThenRun(outdatedAppErrorTriggered))
                .DisposedBy(disposeBag);

            outdatedApi.Rx().Tap()
                .Subscribe(dismissAndThenRun(outdatedApiErrorTriggered))
                .DisposedBy(disposeBag);

            outdatedAppPermanently.Rx().Tap()
                .Subscribe(dismissAndThenRun(outdatedAppPermanentlyErrorTriggered))
                .DisposedBy(disposeBag);

            outdatedApiPermanently.Rx().Tap()
                .Subscribe(dismissAndThenRun(outdatedApiPermanentlyErrorTriggered))
                .DisposedBy(disposeBag);

            shareUnsyncableEntitiesDump.Rx().Tap()
                .Subscribe(showShareDialog)
                .DisposedBy(disposeBag);

            resetOnboarding.Rx().Tap()
                .Subscribe(dismissAndThenRun(resetOnboardingTriggered))
                .DisposedBy(disposeBag);

            var buttons = new[]
            {
                tokenReset,
                noWorkspace,
                noDefaultWorkspace,
                outdatedApp,
                outdatedApi,
                outdatedAppPermanently,
                outdatedApiPermanently,
                shareUnsyncableEntitiesDump,
                resetOnboarding
            };

            View.Add(new UIStackView(buttons)
            {
                BackgroundColor = UIColor.Red,
                Axis = UILayoutConstraintAxis.Vertical,
                Distribution = UIStackViewDistribution.FillEqually,
                Frame = new CGRect(20, 20, PreferredContentSize.Width - 40, PreferredContentSize.Height - 40)
            });
        }

        private UIButton createButton(string text)
        {
            var button = new UIButton();
            button.SetTitle(text, UIControlState.Normal);
            button.SetTitleColor(UIColor.Black, UIControlState.Normal);
            return button;
        }

        private Action dismissAndThenRun(Action callback)
            => () =>
            {
                this.Dismiss();
                callback?.Invoke();
            };

        private void tokenResetErrorTriggered()
        {
            var container = IosDependencyContainer.Instance;
            container.NavigationService.Navigate<TokenResetViewModel>(null);
        }

        private void noWorkspaceErrorTriggered()
        {
            var container = IosDependencyContainer.Instance;
            container.NavigationService.Navigate<NoWorkspaceViewModel>(null);
        }

        private void noDefaultWorkspaceErrorTriggered()
        {
            var container = IosDependencyContainer.Instance;
            container.NavigationService.Navigate<SelectDefaultWorkspaceViewModel>(null);
        }

        private void outdatedAppErrorTriggered()
        {
            var container = IosDependencyContainer.Instance;
            container.NavigationService.Navigate<OutdatedAppViewModel>(null);
        }

        private void outdatedApiErrorTriggered()
        {
            var container = IosDependencyContainer.Instance;
            container.NavigationService.Navigate<OutdatedAppViewModel>(null);
        }

        private void outdatedAppPermanentlyErrorTriggered()
        {
            var container = IosDependencyContainer.Instance;
            container.AccessRestrictionStorage.SetApiOutdated();

            outdatedAppErrorTriggered();
        }

        private void outdatedApiPermanentlyErrorTriggered()
        {
            var container = IosDependencyContainer.Instance;
            container.AccessRestrictionStorage.SetClientOutdated();
            outdatedApiErrorTriggered();
        }

        private void showShareDialog()
        {
            var fileURL = new NSUrl(IUnsyncedDataPersistenceService.UnsyncedDataFilePath, false);
            var activityController = new UIActivityViewController(new NSObject[] { fileURL }, null);

            PresentViewController(activityController, true, null);
        }

        private void resetOnboardingTriggered()
        {
            IosDependencyContainer.Instance
                .OnboardingStorage
                .Reset();
        }
    }
}
#endif


text:
package org.encog.ml.train.strategy;

import org.encog.ml.train.MLTrain;

/**
 * Training strategies can be added to training algorithms.  Training
 * strategies allow different additional logic to be added to an existing
 * training algorithm.  There are a number of different training strategies
 * that can perform various tasks, such as adjusting the learning rate or
 * momentum, or terminating training when improvement diminishes.  Other
 * strategies are provided as well.
 *
 * @author jheaton
 *
 */
public interface Strategy {

	/**
	 * Initialize this strategy.
	 * @param train The training algorithm.
	 */
	void init(MLTrain train);

	/**
	 * Called just before a training iteration.
	 */
	void preIteration();

	/**
	 * Called just after a training iteration.
	 */
	void postIteration();

}