text:
package sql_test

import (
	"bytes"
	gosql "database/sql"
	"fmt"
	"math/rand"
	"sync"
	"sync/atomic"
	"testing"

	_ "github.com/go-sql-driver/mysql"

	"github.com/cockroachdb/cockroach/pkg/base"
	"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
	"github.com/cockroachdb/cockroach/pkg/testutils/testcluster"
	"github.com/cockroachdb/cockroach/pkg/util/tracing"
	_ "github.com/lib/pq"
)

func benchmarkCockroach(b *testing.B, f func(b *testing.B, db *gosql.DB)) {
	defer tracing.Disable()()
	s, db, _ := serverutils.StartServer(
		b, base.TestServerArgs{UseDatabase: "bench"})
	defer s.Stopper().Stop()

	if _, err := db.Exec(`CREATE DATABASE IF NOT EXISTS bench`); err != nil {
		b.Fatal(err)
	}

	f(b, db)
}

func benchmarkMultinodeCockroach(b *testing.B, f func(b *testing.B, db *gosql.DB)) {
	defer tracing.Disable()()
	tc := testcluster.StartTestCluster(b, 3,
		base.TestClusterArgs{
			ReplicationMode: base.ReplicationAuto,
			ServerArgs: base.TestServerArgs{
				UseDatabase: "bench",
			},
		})
	if _, err := tc.Conns[0].Exec(`CREATE DATABASE bench`); err != nil {
		b.Fatal(err)
	}
	if err := tc.WaitForFullReplication(); err != nil {
		b.Fatal(err)
	}
	defer tc.Stopper().Stop()

	f(b, tc.Conns[0])
}

func benchmarkPostgres(b *testing.B, f func(b *testing.B, db *gosql.DB)) {
	// Note: the following uses SSL. To run this, make sure your local
	// Postgres server has SSL enabled. To use Cockroach's checked-in
	// testing certificates for Postgres' SSL, first determine the
	// location of your Postgres server's configuration file:
	// ```
	// $ psql -h localhost -p 5432 -c 'SHOW config_file'
	//                config_file
	// -----------------------------------------
	//  /usr/local/var/postgres/postgresql.conf
	// (1 row)
	//```
	//
	// Now open this file and set the following values:
	// ```
	// $ cat /usr/local/var/postgres/postgresql.conf | grep ssl
	// ssl = on                            # (change requires restart)
	// ssl_cert_file = '$GOATH/src/github.com/cockroachdb/cockroach/resource/test_certs/node.server.crt'             # (change requires restart)
	// ssl_key_file = '$GOATH/src/github.com/cockroachdb/cockroach/resource/test_certs/node.server.key'              # (change requires restart)
	// ssl_ca_file = '$GOATH/src/github.com/cockroachdb/cockroach/resource/test_certs/ca.crt'                        # (change requires restart)
	// ```
	// Where `$GOATH/src/github.com/cockroachdb/cockroach`
	// is replaced with your local Cockroach source directory.
	// Be sure to restart Postgres for this to take effect.

	db, err := gosql.Open("postgres", "sslmode=require host=localhost port=5432")
	if err != nil {
		b.Fatal(err)
	}
	defer db.Close()

	if _, err := db.Exec(`CREATE SCHEMA IF NOT EXISTS bench`); err != nil {
		b.Fatal(err)
	}

	f(b, db)
}

func benchmarkMySQL(b *testing.B, f func(b *testing.B, db *gosql.DB)) {
	db, err := gosql.Open("mysql", "root@tcp(localhost:3306)/")
	if err != nil {
		b.Fatal(err)
	}
	defer db.Close()

	if _, err := db.Exec(`CREATE DATABASE IF NOT EXISTS bench`); err != nil {
		b.Fatal(err)
	}

	f(b, db)
}

func runBenchmarkSelect1(b *testing.B, db *gosql.DB) {
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		rows, err := db.Query(`SELECT 1`)
		if err != nil {
			b.Fatal(err)
		}
		rows.Close()
	}
	b.StopTimer()
}

func BenchmarkSelect1_Cockroach(b *testing.B) {
	benchmarkCockroach(b, runBenchmarkSelect1)
}

func BenchmarkSelect1Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, runBenchmarkSelect1)
}

func BenchmarkSelect1_Postgres(b *testing.B) {
	benchmarkPostgres(b, runBenchmarkSelect1)
}

func BenchmarkSelect1_MySQL(b *testing.B) {
	benchmarkMySQL(b, runBenchmarkSelect1)
}

func runBenchmarkSelectWithTargetsAndFilter(
	b *testing.B, db *gosql.DB, targets, filter string, args ...interface{},
) {
	if _, err := db.Exec(`DROP TABLE IF EXISTS bench.select`); err != nil {
		b.Fatal(err)
	}
	if _, err := db.Exec(`CREATE TABLE bench.select (k INT PRIMARY KEY, a INT, b INT, c INT, d INT)`); err != nil {
		b.Fatal(err)
	}

	var buf bytes.Buffer
	buf.WriteString(`INSERT INTO bench.select VALUES `)

	// We insert all combinations of values between 1 and num for columns a, b, c. The intention is
	// to benchmark the expression parsing and query setup so we don't want to have many rows to go
	// through.
	const num = 3
	row := 0
	for i := 1; i <= num; i++ {
		for j := 1; j <= num; j++ {
			for k := 1; k <= num; k++ {
				if row > 0 {
					buf.WriteString(", ")
				}
				row++
				fmt.Fprintf(&buf, "(%d, %d, %d, %d)", row, i, j, k)
			}
		}
	}
	if _, err := db.Exec(buf.String()); err != nil {
		b.Fatal(err)
	}

	defer func() {
		if _, err := db.Exec(`DROP TABLE bench.select`); err != nil {
			b.Fatal(err)
		}
	}()

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		rows, err := db.Query(fmt.Sprintf(`SELECT %s FROM bench.select WHERE %s`, targets, filter), args...)
		if err != nil {
			b.Fatal(err)
		}
		rows.Close()
	}
	b.StopTimer()
}

// runBenchmarkSelect2 runs a SELECT query with non-trivial expressions. The main purpose is to
// detect major regressions in query expression processing.
func runBenchmarkSelect2(b *testing.B, db *gosql.DB) {
	targets := `a, b, c, a+b, a+1, (a+2)*(b+3)*(c+4)`
	filter := `(a = 1) OR ((a = 2) and (b = c)) OR (a + b = 3) OR (2*a + 4*b = 4*c)`
	runBenchmarkSelectWithTargetsAndFilter(b, db, targets, filter)
}

func BenchmarkSelect2_Cockroach(b *testing.B) {
	benchmarkCockroach(b, runBenchmarkSelect2)
}

func BenchmarkSelect2Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, runBenchmarkSelect2)
}

func BenchmarkSelect2_Postgres(b *testing.B) {
	benchmarkPostgres(b, runBenchmarkSelect2)
}

func BenchmarkSelect2_MySQL(b *testing.B) {
	benchmarkMySQL(b, runBenchmarkSelect2)
}

// runBenchmarkSelect3 runs a SELECT query with non-trivial expressions. The main purpose is to
// quantify regressions in numeric type processing.
func runBenchmarkSelect3(b *testing.B, db *gosql.DB) {
	targets := `a/b, b/c, c != 3.3 + $1, a = 2.0, c * 9.0`
	filter := `a > 1 AND b < 4.5`
	args := []interface{}{1.0}
	runBenchmarkSelectWithTargetsAndFilter(b, db, targets, filter, args...)
}

func BenchmarkSelect3_Cockroach(b *testing.B) {
	benchmarkCockroach(b, runBenchmarkSelect3)
}

func BenchmarkSelect3Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, runBenchmarkSelect3)
}

func BenchmarkSelect3_Postgres(b *testing.B) {
	benchmarkPostgres(b, runBenchmarkSelect3)
}

func BenchmarkSelect3_MySQL(b *testing.B) {
	benchmarkMySQL(b, runBenchmarkSelect3)
}

// runBenchmarkInsert benchmarks inserting count rows into a table.
func runBenchmarkInsert(b *testing.B, db *gosql.DB, count int) {
	if _, err := db.Exec(`DROP TABLE IF EXISTS bench.insert`); err != nil {
		b.Fatal(err)
	}
	if _, err := db.Exec(`CREATE TABLE bench.insert (k INT PRIMARY KEY)`); err != nil {
		b.Fatal(err)
	}
	defer func() {
		if _, err := db.Exec(`DROP TABLE bench.insert`); err != nil {
			b.Fatal(err)
		}
	}()

	b.ResetTimer()
	var buf bytes.Buffer
	val := 0
	for i := 0; i < b.N; i++ {
		buf.Reset()
		buf.WriteString(`INSERT INTO bench.insert VALUES `)
		for j := 0; j < count; j++ {
			if j > 0 {
				buf.WriteString(", ")
			}
			fmt.Fprintf(&buf, "(%d)", val)
			val++
		}
		if _, err := db.Exec(buf.String()); err != nil {
			b.Fatal(err)
		}
	}
	b.StopTimer()

}

func runBenchmarkInsert1(b *testing.B, db *gosql.DB) {
	runBenchmarkInsert(b, db, 1)
}

func runBenchmarkInsert10(b *testing.B, db *gosql.DB) {
	runBenchmarkInsert(b, db, 10)
}

func runBenchmarkInsert100(b *testing.B, db *gosql.DB) {
	runBenchmarkInsert(b, db, 100)
}

func runBenchmarkInsert1000(b *testing.B, db *gosql.DB) {
	runBenchmarkInsert(b, db, 1000)
}

func BenchmarkInsert1_Cockroach(b *testing.B) {
	benchmarkCockroach(b, runBenchmarkInsert1)
}

func BenchmarkInsert1Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, runBenchmarkInsert1)
}

func BenchmarkInsert1_Postgres(b *testing.B) {
	benchmarkPostgres(b, runBenchmarkInsert1)
}

func BenchmarkInsert10_Cockroach(b *testing.B) {
	benchmarkCockroach(b, runBenchmarkInsert10)
}

func BenchmarkInsert10Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, runBenchmarkInsert10)
}

func BenchmarkInsert10_Postgres(b *testing.B) {
	benchmarkPostgres(b, runBenchmarkInsert10)
}

func BenchmarkInsert100_Cockroach(b *testing.B) {
	benchmarkCockroach(b, runBenchmarkInsert100)
}

func BenchmarkInsert100Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, runBenchmarkInsert100)
}

func BenchmarkInsert100_Postgres(b *testing.B) {
	benchmarkPostgres(b, runBenchmarkInsert100)
}

func BenchmarkInsert1000_Cockroach(b *testing.B) {
	benchmarkCockroach(b, runBenchmarkInsert1000)
}

func BenchmarkInsert1000Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, runBenchmarkInsert1000)
}

func BenchmarkInsert1000_Postgres(b *testing.B) {
	benchmarkPostgres(b, runBenchmarkInsert1000)
}

// runBenchmarkUpdate benchmarks updating count random rows in a table.
func runBenchmarkUpdate(b *testing.B, db *gosql.DB, count int) {
	rows := 10000
	if _, err := db.Exec(`DROP TABLE IF EXISTS bench.update`); err != nil {
		b.Fatal(err)
	}
	if _, err := db.Exec(`CREATE TABLE bench.update (k INT PRIMARY KEY, v INT)`); err != nil {
		b.Fatal(err)
	}

	var buf bytes.Buffer
	buf.WriteString(`INSERT INTO bench.update VALUES `)
	for i := 0; i < rows; i++ {
		if i > 0 {
			buf.WriteString(", ")
		}
		fmt.Fprintf(&buf, "(%d, %d)", i, i)
	}
	if _, err := db.Exec(buf.String()); err != nil {
		b.Fatal(err)
	}

	defer func() {
		if _, err := db.Exec(`DROP TABLE bench.update`); err != nil {
			b.Fatal(err)
		}
	}()

	s := rand.New(rand.NewSource(5432))

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		buf.Reset()
		buf.WriteString(`UPDATE bench.update SET v = v + 1 WHERE k IN (`)
		for j := 0; j < count; j++ {
			if j > 0 {
				buf.WriteString(", ")
			}
			fmt.Fprintf(&buf, `%d`, s.Intn(rows))
		}
		buf.WriteString(`)`)
		if _, err := db.Exec(buf.String()); err != nil {
			b.Fatal(err)
		}
	}
	b.StopTimer()
}

func runBenchmarkUpdate1(b *testing.B, db *gosql.DB) {
	runBenchmarkUpdate(b, db, 1)
}

func runBenchmarkUpdate10(b *testing.B, db *gosql.DB) {
	runBenchmarkUpdate(b, db, 10)
}

func runBenchmarkUpdate100(b *testing.B, db *gosql.DB) {
	runBenchmarkUpdate(b, db, 100)
}

func runBenchmarkUpdate1000(b *testing.B, db *gosql.DB) {
	runBenchmarkUpdate(b, db, 1000)
}

func BenchmarkUpdate1_Cockroach(b *testing.B) {
	benchmarkCockroach(b, runBenchmarkUpdate1)
}

func BenchmarkUpdate1Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, runBenchmarkUpdate1)
}

func BenchmarkUpdate1_Postgres(b *testing.B) {
	benchmarkPostgres(b, runBenchmarkUpdate1)
}

func BenchmarkUpdate10_Cockroach(b *testing.B) {
	benchmarkCockroach(b, runBenchmarkUpdate10)
}

func BenchmarkUpdate10Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, runBenchmarkUpdate10)
}

func BenchmarkUpdate10_Postgres(b *testing.B) {
	benchmarkPostgres(b, runBenchmarkUpdate10)
}

func BenchmarkUpdate100_Cockroach(b *testing.B) {
	benchmarkCockroach(b, runBenchmarkUpdate100)
}

func BenchmarkUpdate100Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, runBenchmarkUpdate100)
}

func BenchmarkUpdate100_Postgres(b *testing.B) {
	benchmarkPostgres(b, runBenchmarkUpdate100)
}

func BenchmarkUpdate1000_Cockroach(b *testing.B) {
	benchmarkCockroach(b, runBenchmarkUpdate1000)
}

func BenchmarkUpdate1000Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, runBenchmarkUpdate1000)
}

func BenchmarkUpdate1000_Postgres(b *testing.B) {
	benchmarkPostgres(b, runBenchmarkUpdate1000)
}

// runBenchmarkUpsert benchmarks upserting count rows in a table.
func runBenchmarkUpsert(b *testing.B, db *gosql.DB, count int) {
	if _, err := db.Exec(`DROP TABLE IF EXISTS bench.upsert`); err != nil {
		b.Fatal(err)
	}
	if _, err := db.Exec(`CREATE TABLE bench.upsert (k INT PRIMARY KEY, v INT)`); err != nil {
		b.Fatal(err)
	}
	defer func() {
		if _, err := db.Exec(`DROP TABLE bench.upsert`); err != nil {
			b.Fatal(err)
		}
	}()

	s := rand.New(rand.NewSource(5432))

	b.ResetTimer()
	// Upsert in Cockroach doesn't let you conflict the same row twice in one
	// statement (fwiw, neither does Postgres), so build one statement that
	// inserts half the values requested by `count` followed by a statement that
	// updates each of the values just inserted. This also weighs the benchmark
	// 50/50 for inserts vs updates.
	var insertBuf bytes.Buffer
	var updateBuf bytes.Buffer
	key := 0
	for i := 0; i < b.N; i++ {
		// TODO(dan): Once the long form is implemented, use it here so we can have
		// Postgres benchmarks.
		insertBuf.Reset()
		insertBuf.WriteString(`UPSERT INTO bench.upsert VALUES `)
		updateBuf.Reset()
		updateBuf.WriteString(`UPSERT INTO bench.upsert VALUES `)
		j := 0
		for ; j < count; j += 2 {
			if j > 0 {
				insertBuf.WriteString(`, `)
				updateBuf.WriteString(`, `)
			}
			fmt.Fprintf(&insertBuf, "(%d, %d)", key, s.Int())
			fmt.Fprintf(&updateBuf, "(%d, %d)", key, s.Int())
			key++
		}
		insertBuf.WriteString(`; `)
		updateBuf.WriteTo(&insertBuf)
		if _, err := db.Exec(insertBuf.String()); err != nil {
			b.Fatal(err)
		}
	}
	b.StopTimer()
}

func runBenchmarkUpsert1(b *testing.B, db *gosql.DB) {
	runBenchmarkUpsert(b, db, 1)
}

func runBenchmarkUpsert10(b *testing.B, db *gosql.DB) {
	runBenchmarkUpsert(b, db, 10)
}

func runBenchmarkUpsert100(b *testing.B, db *gosql.DB) {
	runBenchmarkUpsert(b, db, 100)
}

func runBenchmarkUpsert1000(b *testing.B, db *gosql.DB) {
	runBenchmarkUpsert(b, db, 1000)
}

func BenchmarkUpsert1_Cockroach(b *testing.B) {
	benchmarkCockroach(b, runBenchmarkUpsert1)
}

func BenchmarkUpsert10_Cockroach(b *testing.B) {
	benchmarkCockroach(b, runBenchmarkUpsert10)
}

func BenchmarkUpsert100_Cockroach(b *testing.B) {
	benchmarkCockroach(b, runBenchmarkUpsert100)
}

func BenchmarkUpsert1000_Cockroach(b *testing.B) {
	benchmarkCockroach(b, runBenchmarkUpsert1000)
}

func BenchmarkUpsert1Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, runBenchmarkUpsert1)
}

func BenchmarkUpsert10Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, runBenchmarkUpsert10)
}

func BenchmarkUpsert100Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, runBenchmarkUpsert100)
}

func BenchmarkUpsert1000Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, runBenchmarkUpsert1000)
}

// runBenchmarkDelete benchmarks deleting count rows from a table.
func runBenchmarkDelete(b *testing.B, db *gosql.DB, rows int) {
	if _, err := db.Exec(`DROP TABLE IF EXISTS bench.delete`); err != nil {
		b.Fatal(err)
	}
	if _, err := db.Exec(`CREATE TABLE bench.delete (k INT PRIMARY KEY, v1 INT, v2 INT, v3 INT)`); err != nil {
		b.Fatal(err)
	}
	defer func() {
		if _, err := db.Exec(`DROP TABLE bench.delete`); err != nil {
			b.Fatal(err)
		}
	}()

	b.ResetTimer()
	var buf bytes.Buffer
	for i := 0; i < b.N; i++ {
		b.StopTimer()
		buf.Reset()
		buf.WriteString(`INSERT INTO bench.delete VALUES `)
		for j := 0; j < rows; j++ {
			if j > 0 {
				buf.WriteString(", ")
			}
			fmt.Fprintf(&buf, "(%d, %d, %d, %d)", j, j, j, j)
		}
		if _, err := db.Exec(buf.String()); err != nil {
			b.Fatal(err)
		}
		b.StartTimer()

		buf.Reset()
		buf.WriteString(`DELETE FROM bench.delete WHERE k IN (`)
		for j := 0; j < rows; j++ {
			if j > 0 {
				buf.WriteString(", ")
			}
			fmt.Fprintf(&buf, `%d`, j)
		}
		buf.WriteString(`)`)
		if _, err := db.Exec(buf.String()); err != nil {
			b.Fatal(err)
		}
	}
	b.StopTimer()
}

func runBenchmarkDelete1(b *testing.B, db *gosql.DB) {
	runBenchmarkDelete(b, db, 1)
}

func runBenchmarkDelete10(b *testing.B, db *gosql.DB) {
	runBenchmarkDelete(b, db, 10)
}

func runBenchmarkDelete100(b *testing.B, db *gosql.DB) {
	runBenchmarkDelete(b, db, 100)
}

func runBenchmarkDelete1000(b *testing.B, db *gosql.DB) {
	runBenchmarkDelete(b, db, 1000)
}

func BenchmarkDelete1_Cockroach(b *testing.B) {
	benchmarkCockroach(b, runBenchmarkDelete1)
}

func BenchmarkDelete1Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, runBenchmarkDelete1)
}

func BenchmarkDelete1_Postgres(b *testing.B) {
	benchmarkPostgres(b, runBenchmarkDelete1)
}

func BenchmarkDelete10_Cockroach(b *testing.B) {
	benchmarkCockroach(b, runBenchmarkDelete10)
}

func BenchmarkDelete10Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, runBenchmarkDelete10)
}

func BenchmarkDelete10_Postgres(b *testing.B) {
	benchmarkPostgres(b, runBenchmarkDelete10)
}

func BenchmarkDelete100_Cockroach(b *testing.B) {
	benchmarkCockroach(b, runBenchmarkDelete100)
}

func BenchmarkDelete100Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, runBenchmarkDelete100)
}

func BenchmarkDelete100_Postgres(b *testing.B) {
	benchmarkPostgres(b, runBenchmarkDelete100)
}

func BenchmarkDelete1000_Cockroach(b *testing.B) {
	benchmarkCockroach(b, runBenchmarkDelete1000)
}

func BenchmarkDelete1000Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, runBenchmarkDelete1000)
}

func BenchmarkDelete1000_Postgres(b *testing.B) {
	benchmarkPostgres(b, runBenchmarkDelete1000)
}

// runBenchmarkScan benchmarks scanning a table containing count rows.
func runBenchmarkScan(b *testing.B, db *gosql.DB, count int, limit int) {
	if _, err := db.Exec(`DROP TABLE IF EXISTS bench.scan`); err != nil {
		b.Fatal(err)
	}
	if _, err := db.Exec(`CREATE TABLE bench.scan (k INT PRIMARY KEY)`); err != nil {
		b.Fatal(err)
	}

	var buf bytes.Buffer
	buf.WriteString(`INSERT INTO bench.scan VALUES `)
	for i := 0; i < count; i++ {
		if i > 0 {
			buf.WriteString(", ")
		}
		fmt.Fprintf(&buf, "(%d)", i)
	}
	if _, err := db.Exec(buf.String()); err != nil {
		b.Fatal(err)
	}

	query := `SELECT * FROM bench.scan`
	if limit != 0 {
		query = fmt.Sprintf(`%s LIMIT %d`, query, limit)
	}

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		rows, err := db.Query(query)
		if err != nil {
			b.Fatal(err)
		}
		n := 0
		for rows.Next() {
			n++
		}
		rows.Close()
		if err := rows.Err(); err != nil {
			b.Fatal(err)
		}
		expected := count
		if limit != 0 {
			expected = limit
		}
		if n != expected {
			b.Fatalf("unexpected result count: %d (expected %d)", n, expected)
		}
	}
	b.StopTimer()

	if _, err := db.Exec(`DROP TABLE bench.scan`); err != nil {
		b.Fatal(err)
	}
}

func BenchmarkScan1_Cockroach(b *testing.B) {
	benchmarkCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkScan(b, db, 1, 0) })
}

func BenchmarkScan1Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkScan(b, db, 1, 0) })
}

func BenchmarkScan1_Postgres(b *testing.B) {
	benchmarkPostgres(b, func(b *testing.B, db *gosql.DB) { runBenchmarkScan(b, db, 1, 0) })
}

func BenchmarkScan10_Cockroach(b *testing.B) {
	benchmarkCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkScan(b, db, 10, 0) })
}

func BenchmarkScan10Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkScan(b, db, 10, 0) })
}

func BenchmarkScan10_Postgres(b *testing.B) {
	benchmarkPostgres(b, func(b *testing.B, db *gosql.DB) { runBenchmarkScan(b, db, 10, 0) })
}

func BenchmarkScan100_Cockroach(b *testing.B) {
	benchmarkCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkScan(b, db, 100, 0) })
}

func BenchmarkScan100Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkScan(b, db, 100, 0) })
}

func BenchmarkScan100_Postgres(b *testing.B) {
	benchmarkPostgres(b, func(b *testing.B, db *gosql.DB) { runBenchmarkScan(b, db, 100, 0) })
}

func BenchmarkScan1000_Cockroach(b *testing.B) {
	benchmarkCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkScan(b, db, 1000, 0) })
}

func BenchmarkScan1000Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkScan(b, db, 1000, 0) })
}

func BenchmarkScan1000_Postgres(b *testing.B) {
	benchmarkPostgres(b, func(b *testing.B, db *gosql.DB) { runBenchmarkScan(b, db, 1000, 0) })
}

func BenchmarkScan10000_Cockroach(b *testing.B) {
	benchmarkCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkScan(b, db, 10000, 0) })
}

func BenchmarkScan10000Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkScan(b, db, 10000, 0) })
}

func BenchmarkScan10000_Postgres(b *testing.B) {
	benchmarkPostgres(b, func(b *testing.B, db *gosql.DB) { runBenchmarkScan(b, db, 10000, 0) })
}

func BenchmarkScan1000Limit1_Cockroach(b *testing.B) {
	benchmarkCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkScan(b, db, 1000, 1) })
}

func BenchmarkScan1000Limit1Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkScan(b, db, 1000, 1) })
}

func BenchmarkScan1000Limit1_Postgres(b *testing.B) {
	benchmarkPostgres(b, func(b *testing.B, db *gosql.DB) { runBenchmarkScan(b, db, 1000, 1) })
}

func BenchmarkScan1000Limit10_Cockroach(b *testing.B) {
	benchmarkCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkScan(b, db, 1000, 10) })
}

func BenchmarkScan1000Limit10Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkScan(b, db, 1000, 10) })
}

func BenchmarkScan1000Limit10_Postgres(b *testing.B) {
	benchmarkPostgres(b, func(b *testing.B, db *gosql.DB) { runBenchmarkScan(b, db, 1000, 10) })
}

func BenchmarkScan1000Limit100_Cockroach(b *testing.B) {
	benchmarkCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkScan(b, db, 1000, 100) })
}

func BenchmarkScan1000Limit100Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkScan(b, db, 1000, 100) })
}

func BenchmarkScan1000Limit100_Postgres(b *testing.B) {
	benchmarkPostgres(b, func(b *testing.B, db *gosql.DB) { runBenchmarkScan(b, db, 1000, 100) })
}

// runBenchmarkScanFilter benchmarks scanning (w/filter) from a table containing count1 * count2 rows.
func runBenchmarkScanFilter(
	b *testing.B, db *gosql.DB, count1, count2 int, limit int, filter string,
) {
	if _, err := db.Exec(`DROP TABLE IF EXISTS bench.scan2`); err != nil {
		b.Fatal(err)
	}
	if _, err := db.Exec(`CREATE TABLE bench.scan2 (a INT, b INT, PRIMARY KEY (a, b))`); err != nil {
		b.Fatal(err)
	}

	var buf bytes.Buffer
	buf.WriteString(`INSERT INTO bench.scan2 VALUES `)
	for i := 0; i < count1; i++ {
		for j := 0; j < count2; j++ {
			if i+j > 0 {
				buf.WriteString(", ")
			}
			fmt.Fprintf(&buf, "(%d, %d)", i, j)
		}
	}
	if _, err := db.Exec(buf.String()); err != nil {
		b.Fatal(err)
	}

	query := fmt.Sprintf(`SELECT * FROM bench.scan2 WHERE %s`, filter)
	if limit != 0 {
		query += fmt.Sprintf(` LIMIT %d`, limit)
	}

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		rows, err := db.Query(query)
		if err != nil {
			b.Fatal(err)
		}
		n := 0
		for rows.Next() {
			n++
		}
		rows.Close()
		if err := rows.Err(); err != nil {
			b.Fatal(err)
		}
	}
	b.StopTimer()

	if _, err := db.Exec(`DROP TABLE bench.scan2`); err != nil {
		b.Fatal(err)
	}
}

func filterLimitBenchFn(limit int) func(*testing.B, *gosql.DB) {
	return func(b *testing.B, db *gosql.DB) {
		runBenchmarkScanFilter(b, db, 25, 400, limit,
			`a IN (1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 20, 21, 23) AND b < 10*a`)
	}
}

func BenchmarkScan10000FilterLimit1_Cockroach(b *testing.B) {
	benchmarkCockroach(b, filterLimitBenchFn(1))
}

func BenchmarkScan10000FilterLimit1Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, filterLimitBenchFn(1))
}

func BenchmarkScan10000FilterLimit1_Postgres(b *testing.B) {
	benchmarkPostgres(b, filterLimitBenchFn(1))
}

func BenchmarkScan10000FilterLimit10_Cockroach(b *testing.B) {
	benchmarkCockroach(b, filterLimitBenchFn(10))
}

func BenchmarkScan10000FilterLimit10Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, filterLimitBenchFn(10))
}

func BenchmarkScan10000FilterLimit10_Postgres(b *testing.B) {
	benchmarkPostgres(b, filterLimitBenchFn(10))
}

func BenchmarkScan10000FilterLimit50_Cockroach(b *testing.B) {
	benchmarkCockroach(b, filterLimitBenchFn(50))
}

func BenchmarkScan10000FilterLimit50Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, filterLimitBenchFn(50))
}

func BenchmarkScan10000FilterLimit50_Postgres(b *testing.B) {
	benchmarkPostgres(b, filterLimitBenchFn(50))
}

func runBenchmarkInterleavedSelect(b *testing.B, db *gosql.DB, count int) {
	if _, err := db.Exec(`DROP TABLE IF EXISTS bench.interleaved_select1`); err != nil {
		b.Fatal(err)
	}
	if _, err := db.Exec(`DROP TABLE IF EXISTS bench.interleaved_select2`); err != nil {
		b.Fatal(err)
	}
	if _, err := db.Exec(`CREATE TABLE bench.interleaved_select1 (a INT PRIMARY KEY, b INT)`); err != nil {
		b.Fatal(err)
	}
	if _, err := db.Exec(`CREATE TABLE bench.interleaved_select2 (c INT PRIMARY KEY, d INT) INTERLEAVE IN PARENT interleaved_select1 (c)`); err != nil {
		b.Fatal(err)
	}

	var buf1 bytes.Buffer
	var buf2 bytes.Buffer
	buf1.WriteString(`INSERT INTO bench.interleaved_select1 VALUES `)
	buf2.WriteString(`INSERT INTO bench.interleaved_select2 VALUES `)
	for i := 0; i < count; i++ {
		if i > 0 {
			buf1.WriteString(", ")
		}
		fmt.Fprintf(&buf1, "(%d, %d)", i, i)
		if i%4 == 0 {
			if i > 0 {
				buf2.WriteString(", ")
			}
			fmt.Fprintf(&buf2, "(%d, %d)", i, i)
		}
	}
	if _, err := db.Exec(buf1.String()); err != nil {
		b.Fatal(err)
	}
	if _, err := db.Exec(buf2.String()); err != nil {
		b.Fatal(err)
	}

	query := `SELECT * FROM bench.interleaved_select1 is1 INNER JOIN bench.interleaved_select2 is2 on is1.a = is2.c`

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		rows, err := db.Query(query)
		if err != nil {
			b.Fatal(err)
		}
		n := 0
		for rows.Next() {
			n++
		}
		rows.Close()
		if err := rows.Err(); err != nil {
			b.Fatal(err)
		}
		expected := count / 4
		if n != expected {
			b.Fatalf("unexpected result count: %d (expected %d)", n, expected)
		}
	}
	b.StopTimer()
}

func BenchmarkInterleavedSelect1000_Cockroach(b *testing.B) {
	benchmarkCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkInterleavedSelect(b, db, 1000) })
}

// runBenchmarkOrderBy benchmarks scanning a table and sorting the results.
func runBenchmarkOrderBy(b *testing.B, db *gosql.DB, count int, limit int, distinct bool) {
	if _, err := db.Exec(`DROP TABLE IF EXISTS bench.sort`); err != nil {
		b.Fatal(err)
	}
	if _, err := db.Exec(`CREATE TABLE bench.sort (k INT PRIMARY KEY, v INT, w INT)`); err != nil {
		b.Fatal(err)
	}

	var buf bytes.Buffer
	buf.WriteString(`INSERT INTO bench.sort VALUES `)
	for i := 0; i < count; i++ {
		if i > 0 {
			buf.WriteString(", ")
		}
		fmt.Fprintf(&buf, "(%d, %d, %d)", i, i%(count*4/limit), i%2)
	}
	if _, err := db.Exec(buf.String()); err != nil {
		b.Fatal(err)
	}

	var dist string
	if distinct {
		dist = `DISTINCT `
	}
	query := fmt.Sprintf(`SELECT %sv FROM bench.sort`, dist)
	if limit != 0 {
		query = fmt.Sprintf(`%s ORDER BY v DESC, w ASC, k DESC LIMIT %d`, query, limit)
	}

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		rows, err := db.Query(query)
		if err != nil {
			b.Fatal(err)
		}
		n := 0
		for rows.Next() {
			n++
		}
		rows.Close()
		if err := rows.Err(); err != nil {
			b.Fatal(err)
		}
		expected := count
		if limit != 0 {
			expected = limit
		}
		if n != expected {
			b.Fatalf("unexpected result count: %d (expected %d)", n, expected)
		}
	}
	b.StopTimer()

	if _, err := db.Exec(`DROP TABLE bench.sort`); err != nil {
		b.Fatal(err)
	}
}

func BenchmarkSort100000Limit10_Cockroach(b *testing.B) {
	benchmarkCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkOrderBy(b, db, 100000, 10, false) })
}

func BenchmarkSort100000Limit10Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkOrderBy(b, db, 100000, 10, false) })
}

func BenchmarkSort100000Limit10_Postgres(b *testing.B) {
	benchmarkPostgres(b, func(b *testing.B, db *gosql.DB) { runBenchmarkOrderBy(b, db, 100000, 10, false) })
}

func BenchmarkSort100000Limit10Distinct_Cockroach(b *testing.B) {
	benchmarkCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkOrderBy(b, db, 100000, 10, true) })
}

func BenchmarkSort100000Limit10DistinctMultinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkOrderBy(b, db, 100000, 10, true) })
}

func BenchmarkSort100000Limit10Distinct_Postgres(b *testing.B) {
	benchmarkPostgres(b, func(b *testing.B, db *gosql.DB) { runBenchmarkOrderBy(b, db, 100000, 10, true) })
}

func runBenchmarkTrackChoices(b *testing.B, db *gosql.DB, batchSize int) {
	const numOptions = 10000

	if _, err := db.Exec(`DROP TABLE IF EXISTS bench.track_choices`); err != nil {
		b.Fatal(err)
	}
	// The CREATE INDEX statements are separate in order to be compatible with
	// Postgres.
	const createStmt = `
CREATE TABLE IF NOT EXISTS bench.track_choices (
  user_id bigint NOT NULL DEFAULT 0,
  track_id bigint NOT NULL DEFAULT 0,
  created_at timestamp NOT NULL,
  PRIMARY KEY (user_id, track_id)
);
CREATE INDEX user_created_at ON bench.track_choices (user_id, created_at);
CREATE INDEX track_created_at ON bench.track_choices (track_id, created_at);
`
	if _, err := db.Exec(createStmt); err != nil {
		b.Fatal(err)
	}

	b.ResetTimer()
	var buf bytes.Buffer
	for i := 0; i < b.N; i += batchSize {
		buf.Reset()
		buf.WriteString(`INSERT INTO bench.track_choices VALUES `)
		count := b.N - i
		if count > batchSize {
			count = batchSize
		}
		for j := 0; j < count; j++ {
			if j > 0 {
				buf.WriteString(", ")
			}
			fmt.Fprintf(&buf, "(%d, %d, NOW())", rand.Int63(), rand.Int63n(numOptions))
		}
		if _, err := db.Exec(buf.String()); err != nil {
			b.Fatal(err)
		}
	}
	b.StopTimer()
}

func BenchmarkTrackChoices1_Cockroach(b *testing.B) {
	benchmarkCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkTrackChoices(b, db, 1) })
}

func BenchmarkTrackChoices10_Cockroach(b *testing.B) {
	benchmarkCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkTrackChoices(b, db, 10) })
}

func BenchmarkTrackChoices100_Cockroach(b *testing.B) {
	benchmarkCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkTrackChoices(b, db, 100) })
}

func BenchmarkTrackChoices1000_Cockroach(b *testing.B) {
	benchmarkCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkTrackChoices(b, db, 1000) })
}

func BenchmarkTrackChoices1Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkTrackChoices(b, db, 1) })
}

func BenchmarkTrackChoices10Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkTrackChoices(b, db, 10) })
}

func BenchmarkTrackChoices100Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkTrackChoices(b, db, 100) })
}

func BenchmarkTrackChoices1000Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkTrackChoices(b, db, 1000) })
}

func BenchmarkTrackChoices1_Postgres(b *testing.B) {
	benchmarkPostgres(b, func(b *testing.B, db *gosql.DB) { runBenchmarkTrackChoices(b, db, 1) })
}

func BenchmarkTrackChoices10_Postgres(b *testing.B) {
	benchmarkPostgres(b, func(b *testing.B, db *gosql.DB) { runBenchmarkTrackChoices(b, db, 10) })
}

func BenchmarkTrackChoices100_Postgres(b *testing.B) {
	benchmarkPostgres(b, func(b *testing.B, db *gosql.DB) { runBenchmarkTrackChoices(b, db, 100) })
}

func BenchmarkTrackChoices1000_Postgres(b *testing.B) {
	benchmarkPostgres(b, func(b *testing.B, db *gosql.DB) { runBenchmarkTrackChoices(b, db, 1000) })
}

// Benchmark inserting distinct rows in batches where the min and max rows in
// separate batches overlap. This stresses the command queue implementation and
// verifies that we're allowing parallel execution of commands where possible.
func runBenchmarkInsertDistinct(b *testing.B, db *gosql.DB, numUsers int) {
	if _, err := db.Exec(`DROP TABLE IF EXISTS bench.insert_distinct`); err != nil {
		b.Fatal(err)
	}
	const schema = `
CREATE TABLE bench.insert_distinct (
  articleID INT,
  userID INT,
  uniqueID INT DEFAULT unique_rowid(),
  PRIMARY KEY (articleID, userID, uniqueID))
`
	if _, err := db.Exec(schema); err != nil {
		b.Fatal(err)
	}

	b.ResetTimer()

	var wg sync.WaitGroup
	wg.Add(numUsers)

	var count int64
	for i := 0; i < numUsers; i++ {
		go func(i int) {
			defer wg.Done()
			var buf bytes.Buffer

			rnd := rand.New(rand.NewSource(int64(i)))
			// Article IDs are chosen from a zipf distribution. These values select
			// articleIDs that are mostly <10000. The parameters were experimentally
			// determined, but somewhat arbitrary.
			zipf := rand.NewZipf(rnd, 2, 10000, 100000)

			for {
				n := atomic.AddInt64(&count, 1)
				if int(n) >= b.N {
					return
				}

				// Insert between [1,100] articles in a batch.
				numArticles := 1 + rnd.Intn(100)
				buf.Reset()
				buf.WriteString(`INSERT INTO bench.insert_distinct VALUES `)
				for j := 0; j < numArticles; j++ {
					if j > 0 {
						buf.WriteString(", ")
					}
					fmt.Fprintf(&buf, "(%d, %d)", zipf.Uint64(), n)
				}

				if _, err := db.Exec(buf.String()); err != nil {
					b.Fatal(err)
				}
			}
		}(i)
	}

	wg.Wait()
	b.StopTimer()
}

func BenchmarkInsertDistinct1_Cockroach(b *testing.B) {
	benchmarkCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkInsertDistinct(b, db, 1) })
}

func BenchmarkInsertDistinct10_Cockroach(b *testing.B) {
	benchmarkCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkInsertDistinct(b, db, 10) })
}

func BenchmarkInsertDistinct100_Cockroach(b *testing.B) {
	benchmarkCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkInsertDistinct(b, db, 100) })
}

func BenchmarkInsertDistinct1Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkInsertDistinct(b, db, 1) })
}

func BenchmarkInsertDistinct10Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkInsertDistinct(b, db, 10) })
}

func BenchmarkInsertDistinct100Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkInsertDistinct(b, db, 100) })
}

// runBenchmarkWideTable measures performance on a table with a large number of
// columns (20).
func runBenchmarkWideTable(b *testing.B, db *gosql.DB, count int) {
	if _, err := db.Exec(`DROP TABLE IF EXISTS bench.widetable`); err != nil {
		b.Fatal(err)
	}
	const schema = `CREATE TABLE bench.widetable (
    f1 INT, f2 INT, f3 INT, f4 INT, f5 INT, f6 INT, f7 INT, f8 INT, f9 INT, f10 INT,
    f11 INT, f12 INT, f13 INT, f14 INT, f15 INT, f16 INT, f17 INT, f18 INT, f19 INT, f20 INT,
    PRIMARY KEY (f1, f2, f3)
  )`
	if _, err := db.Exec(schema); err != nil {
		b.Fatal(err)
	}

	defer func() {
		if _, err := db.Exec(`DROP TABLE bench.widetable`); err != nil {
			b.Fatal(err)
		}
	}()

	s := rand.New(rand.NewSource(5432))

	var buf bytes.Buffer

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		buf.Reset()

		fmt.Fprintf(&buf, `INSERT INTO bench.widetable VALUES`)
		for j := 0; j < count; j++ {
			if j != 0 {
				buf.WriteString(`,`)
			}
			buf.WriteString(`(`)
			for k := 0; k < 20; k++ {
				if k != 0 {
					buf.WriteString(`,`)
				}
				fmt.Fprintf(&buf, "%d", i*count+j)
			}
			buf.WriteString(`)`)
		}
		buf.WriteString(`;`)

		// These UPSERTS are all updates, but it's done with UPSERT for convenience.
		fmt.Fprintf(&buf, `UPSERT INTO bench.widetable (f1, f2, f3, f4, f5, f6, f7, f8, f9, f10) VALUES`)
		for j := 0; j < count; j++ {
			if j != 0 {
				buf.WriteString(`,`)
			}
			fmt.Fprintf(&buf, `(%d,%d,%d,`, i*count+j, i*count+j, i*count+j)
			for k := 0; k < 7; k++ {
				if k != 0 {
					buf.WriteString(`,`)
				}
				fmt.Fprintf(&buf, "%d", s.Intn(j+1))
			}
			buf.WriteString(`)`)
		}
		buf.WriteString(`;`)

		fmt.Fprintf(&buf, `DELETE FROM bench.widetable WHERE f1 in (`)
		for j := 0; j < count; j++ {
			if j != 0 {
				buf.WriteString(`,`)
			}
			fmt.Fprintf(&buf, "%d", j)
		}
		buf.WriteString(`);`)

		if _, err := db.Exec(buf.String()); err != nil {
			b.Fatal(err)
		}
	}
	b.StopTimer()
}

func BenchmarkWideTable1_Cockroach(b *testing.B) {
	benchmarkCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkWideTable(b, db, 1) })
}

func BenchmarkWideTable10_Cockroach(b *testing.B) {
	benchmarkCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkWideTable(b, db, 10) })
}

func BenchmarkWideTable100_Cockroach(b *testing.B) {
	benchmarkCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkWideTable(b, db, 100) })
}

func BenchmarkWideTable1000_Cockroach(b *testing.B) {
	benchmarkCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkWideTable(b, db, 1000) })
}

func BenchmarkWideTable1Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkWideTable(b, db, 1) })
}

func BenchmarkWideTable10Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkWideTable(b, db, 10) })
}

func BenchmarkWideTable100Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkWideTable(b, db, 100) })
}

func BenchmarkWideTable1000Multinode_Cockroach(b *testing.B) {
	benchmarkMultinodeCockroach(b, func(b *testing.B, db *gosql.DB) { runBenchmarkWideTable(b, db, 1000) })
}


text:
[![Join the chat at https://gitter.im/shelljs/shelljs](https://badges.gitter.im/shelljs/shelljs.svg)](https://gitter.im/shelljs/shelljs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Build Status](https://travis-ci.org/shelljs/benchmarks.svg?branch=master)](https://travis-ci.org/shelljs/benchmarks)

Collection of benchmarks for ShellJS

Note: benchmark results will be moving to Github Pages - stay tuned.

This is a comparison of [ShellJS]() and bash for performance. Each test case
runs scripts with equivalent output and compares Bash's runtime with ShellJS's.
Surprisingly, ShellJS is often the winner, sometimes being up to **12x faster**!
Woohoo! See below for [ShellJS performance wins](#shelljs-performance-wins).

## Results

### ShellJS performance wins

 - [echoIntoFile](test/echoIntoFile)
 - [ls10k](test/ls10k)
 - [touchSyntax0.6](test/touchSyntax0.6)

## System Information:

 - Linux

 - 4.2.0-30-generic

 - x64

 - Intel(R) Core(TM) i5-3317U CPU @ 1.70GHz × 4

## Node information

 - Node.js: v5.3.0

 - V8: 4.6.85.31

## Shell Information:

 - name: `/bin/bash`

 - version: GNU bash, version 4.3.42(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

### [echoIntoFile](test/echoIntoFile)

 - [Bash](test/echoIntoFile/echoIntoFile.sh) took `842` milliseconds

 - [ShellJS 0.5.3](test/echoIntoFile/echoIntoFile.js) took `252` milliseconds

 - [ShellJS 0.6.0](test/echoIntoFile/echoIntoFile.js) took `270` milliseconds

 - [ShellJS latest](test/echoIntoFile/echoIntoFile.js) took `178` milliseconds

ShellJS was `4.730` times faster than Bash

### [envVariable](test/envVariable)

 - [Bash](test/envVariable/envVar.sh) took `314` milliseconds

 - [ShellJS 0.5.3](test/envVariable/envVar.js) took `281` milliseconds

 - [ShellJS 0.6.0](test/envVariable/envVar.js) took `293` milliseconds

 - [ShellJS latest](test/envVariable/envVar.js) took `618` milliseconds

Bash was `1.968` times faster than ShellJS

### [forLoopAlternateSyntax](test/forLoopAlternateSyntax)

 - [Bash](test/forLoopAlternateSyntax/helloworld10k.sh) took `91` milliseconds

 - [ShellJS 0.5.3](test/forLoopAlternateSyntax/helloworld10k.js) took `184` milliseconds

 - [ShellJS 0.6.0](test/forLoopAlternateSyntax/helloworld10k.js) took `185` milliseconds

 - [ShellJS latest](test/forLoopAlternateSyntax/helloworld10k.js) took `235` milliseconds

Bash was `2.582` times faster than ShellJS

### [helloworld](test/helloworld)

 - [Bash](test/helloworld/helloworld.sh) took `84` milliseconds

 - [ShellJS 0.5.3](test/helloworld/helloworld.js) took `195` milliseconds

 - [ShellJS 0.6.0](test/helloworld/helloworld.js) took `175` milliseconds

 - [ShellJS latest](test/helloworld/helloworld.js) took `175` milliseconds

Bash was `2.083` times faster than ShellJS

### [helloworld10k](test/helloworld10k)

 - [Bash](test/helloworld10k/helloworld10k.sh) took `208` milliseconds

 - [ShellJS 0.5.3](test/helloworld10k/helloworld10k.js) took `326` milliseconds

 - [ShellJS 0.6.0](test/helloworld10k/helloworld10k.js) took `264` milliseconds

 - [ShellJS latest](test/helloworld10k/helloworld10k.js) took `760` milliseconds

Bash was `3.654` times faster than ShellJS

### [ls10k](test/ls10k)

 - [Bash](test/ls10k/ls10k.sh) took `10334` milliseconds

 - [ShellJS 0.5.3](test/ls10k/ls10k.js) took `690` milliseconds

 - [ShellJS 0.6.0](test/ls10k/ls10k.js) took `748` milliseconds

 - [ShellJS latest](test/ls10k/ls10k.js) took `1115` milliseconds

ShellJS was `9.268` times faster than Bash

### [pwd10k](test/pwd10k)

 - [Bash](test/pwd10k/path10k.sh) took `632` milliseconds

 - [ShellJS 0.5.3](test/pwd10k/path10k.js) took `1625` milliseconds

 - [ShellJS 0.6.0](test/pwd10k/path10k.js) took `2343` milliseconds

 - [ShellJS latest](test/pwd10k/path10k.js) took `6133` milliseconds

Bash was `9.704` times faster than ShellJS

### [touchSyntax0.6](test/touchSyntax0.6)

 - [Bash](test/touchSyntax0.6/touchrm10k.sh) took `1392` milliseconds

 - Skipping test for ShellJS 0.5.3

 - [ShellJS 0.6.0](test/touchSyntax0.6/touchrm10k.js) took `270` milliseconds

 - [ShellJS latest](test/touchSyntax0.6/touchrm10k.js) took `465` milliseconds

ShellJS was `2.994` times faster than Bash

redpajama_set_name: RedPajamaGithub


text:
package ie.rkie.sm.service;

import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;

import java.util.Base64;

import ie.rkie.sm.db.Game;
import ie.rkie.sm.db.GameType;
import ie.rkie.sm.db.User;

import org.junit.Before;
import org.junit.Test;

public class SimpleTokenFactoryTest {

	private SimpleTokenFactory factory;
	private Game game1;
	private Game game2;

	@Before
	public void before() {
		factory = new SimpleTokenFactory();
		game1 = new Game();
		game1.setGid(100);
		GameType type = new GameType();
		type.setName("chess");
		game1.setGameType(type);
		User owner = new User("email", "username");
		game1.setOwner(owner);
		game1.setStatus("SETUP");

		game2 = new Game();
		game2.setGid(101);
		type.setName("chess");
		game2.setGameType(type);
		game2.setOwner(owner);
		game2.setStatus("SETUP");
	}

	/**
	 * A bit arbitrary but should flag any changes to the initial implementation.
	 */
	@Test
	public void testTokenGeneration() {
		final String expected = "dXNlcm5hbWUsMTAwLGNoZXNz";

		// test
		String actual = factory.createToken(game1);

		// check
		assertThat(actual, is(expected));
	}

	/**
	 * Different game ids should generate different tokens
	 */
	@Test
	public void testTokensDifferent() {
		// test
		String actual1 = factory.createToken(game1);
		String actual2 = factory.createToken(game2);

		// check
		assertThat(actual1, not(is(actual2)));
	}

	/**
	 * Should be able to decode a token.
	 */
	@Test
	public void testDecodeToken() {
		final String expected = "username,100,chess";

		String actual = factory.createToken(game1);
		String result = new String(Base64.getDecoder().decode(actual));

		assertThat(result, is(expected));
	}
}


text:
<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        // replace this example code with whatever you need
        return $this->render('default/index.html.twig', [
            'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
        ]);
    }

    /**
     * @Route("/hello/{name}", name="Hello")
     * @param $name: desired name
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function helloAction($name){
        return $this->render('default/hello.html.twig', array('name' =>$name));
    }

    /**
     * @Route("bite/{title}", name="Anime2")
     * @param $title
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function animeTitleAction($title){
        return $this->render('default/anime.html.twig', array('title' =>$title));
    }

    /**
     * @Route("legacy", name="legacy")
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function firstLayoutAction(){
        return $this->render('default/main.html.twig');
    }

    /**
     * @Route("contact", name="Contact")
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function contactAction(){
        return $this->render('default/contact.html.twig');
    }
}


text:
function Add-VSKinesisAnalyticsApplicationOutputOutput {
    <#
    .SYNOPSIS
        Adds an AWS::KinesisAnalytics::ApplicationOutput.Output resource property to the template. Describes application output configuration in which you identify an in-application stream and a destination where you want the in-application stream data to be written. The destination can be an Amazon Kinesis stream or an Amazon Kinesis Firehose delivery stream.

    .DESCRIPTION
        Adds an AWS::KinesisAnalytics::ApplicationOutput.Output resource property to the template.
Describes application output configuration in which you identify an in-application stream and a destination where you want the in-application stream data to be written. The destination can be an Amazon Kinesis stream or an Amazon Kinesis Firehose delivery stream.

For limits on how many destinations an application can write and other limitations, see Limits: https://docs.aws.amazon.com/kinesisanalytics/latest/dev/limits.html.

    .LINK
        http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-output.html

    .PARAMETER DestinationSchema
        Describes the data format when records are written to the destination. For more information, see Configuring Application Output: https://docs.aws.amazon.com/kinesisanalytics/latest/dev/how-it-works-output.html.

        Type: DestinationSchema
        Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-output.html#cfn-kinesisanalytics-applicationoutput-output-destinationschema
        UpdateType: Mutable

    .PARAMETER LambdaOutput
        Identifies an AWS Lambda function as the destination.

        Type: LambdaOutput
        Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-output.html#cfn-kinesisanalytics-applicationoutput-output-lambdaoutput
        UpdateType: Mutable

    .PARAMETER KinesisFirehoseOutput
        Identifies an Amazon Kinesis Firehose delivery stream as the destination.

        Type: KinesisFirehoseOutput
        Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-output.html#cfn-kinesisanalytics-applicationoutput-output-kinesisfirehoseoutput
        UpdateType: Mutable

    .PARAMETER KinesisStreamsOutput
        Identifies an Amazon Kinesis stream as the destination.

        Type: KinesisStreamsOutput
        Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-output.html#cfn-kinesisanalytics-applicationoutput-output-kinesisstreamsoutput
        UpdateType: Mutable

    .PARAMETER Name
        Name of the in-application stream.

        Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-output.html#cfn-kinesisanalytics-applicationoutput-output-name
        PrimitiveType: String
        UpdateType: Immutable

    .FUNCTIONALITY
        Vaporshell
    #>
    [OutputType('Vaporshell.Resource.KinesisAnalytics.ApplicationOutput.Output')]
    [cmdletbinding()]
    Param
    (
        [parameter(Mandatory = $true)]
        $DestinationSchema,
        [parameter(Mandatory = $false)]
        $LambdaOutput,
        [parameter(Mandatory = $false)]
        $KinesisFirehoseOutput,
        [parameter(Mandatory = $false)]
        $KinesisStreamsOutput,
        [parameter(Mandatory = $false)]
        [ValidateScript( {
                $allowedTypes = "System.String","Vaporshell.Function","Vaporshell.Condition"
                if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") {
                    $true
                }
                else {
                    $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")."))
                }
            })]
        $Name
    )
    Begin {
        $obj = [PSCustomObject]@{}
        $commonParams = @('Verbose','Debug','ErrorAction','WarningAction','InformationAction','ErrorVariable','WarningVariable','InformationVariable','OutVariable','OutBuffer','PipelineVariable')
    }
    Process {
        foreach ($key in $PSBoundParameters.Keys | Where-Object {$commonParams -notcontains $_}) {
            switch ($key) {
                Default {
                    $obj | Add-Member -MemberType NoteProperty -Name $key -Value $PSBoundParameters.$key
                }
            }
        }
    }
    End {
        $obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.KinesisAnalytics.ApplicationOutput.Output'
        Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n$($obj | ConvertTo-Json -Depth 5)`n"
    }
}


text:
.class Lcom/android/server/hdmi/HdmiCecController$7$1;
.super Ljava/lang/Object;
.source "HdmiCecController.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/server/hdmi/HdmiCecController$7;->run()V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$1:Lcom/android/server/hdmi/HdmiCecController$7;

.field final synthetic val$callback:Lcom/android/server/hdmi/HdmiControlService$SendMessageCallback;

.field final synthetic val$finalError:I

# direct methods
.method constructor <init>(Lcom/android/server/hdmi/HdmiCecController$7;Lcom/android/server/hdmi/HdmiControlService$SendMessageCallback;I)V
    .locals 0
    .param p1, "this$1"    # Lcom/android/server/hdmi/HdmiCecController$7;
    .param p2, "val$callback"    # Lcom/android/server/hdmi/HdmiControlService$SendMessageCallback;
    .param p3, "val$finalError"    # I

    .prologue
    .line 586
    iput-object p1, p0, Lcom/android/server/hdmi/HdmiCecController$7$1;->this$1:Lcom/android/server/hdmi/HdmiCecController$7;

    iput-object p2, p0, Lcom/android/server/hdmi/HdmiCecController$7$1;->val$callback:Lcom/android/server/hdmi/HdmiControlService$SendMessageCallback;

    iput p3, p0, Lcom/android/server/hdmi/HdmiCecController$7$1;->val$finalError:I

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

    return-void
.end method

# virtual methods
.method public run()V
    .locals 2

    .prologue
    .line 589
    iget-object v0, p0, Lcom/android/server/hdmi/HdmiCecController$7$1;->val$callback:Lcom/android/server/hdmi/HdmiControlService$SendMessageCallback;

    iget v1, p0, Lcom/android/server/hdmi/HdmiCecController$7$1;->val$finalError:I

    invoke-interface {v0, v1}, Lcom/android/server/hdmi/HdmiControlService$SendMessageCallback;->onSendCompleted(I)V

    .line 588
    return-void
.end method


text:
package com.twu.model;

public class Book {
    String name;
    String author;
    int publishedYear;
    Boolean isCheckout;
    public Book(String name,String author,int publishedYear){
        this.name = name;
        this.author = author;
        this.publishedYear = publishedYear;
        this.isCheckout = false;
    }
    public String toString(){
        return "Book name: "+ name
                +" Author:" + author
                + " Published in " + publishedYear +"\n";
    }

    public String getName() {
        return this.name;
    }

    public Book checkout() {
        this.isCheckout = true;
        return this;
    }

    public Book returnBack() {
        this.isCheckout = false;
        return this;
    }
}


text:
    text-align: center;
}

#calendar .weekdays-row th {
    background-color: #fff;
}

#calendar .calendar-selected-day {
    font-weight: bold;
}


text:
/* ###
 * IP: GHIDRA
 *
 * 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 agent.lldb.manager.evt;

import SWIG.StateType;

public class LldbRunningEvent extends AbstractLldbEvent<String> {
	private final String id;

	/**
	 * Construct a new event, parsing the tail for information
	 *
	 * A thread ID must be specified by lldb.
	 *
	 * @param id the event info
	 */
	public LldbRunningEvent(String id) {
		super(id);
		this.id = id;
	}

	/**
	 * Get the ID of the thread causing the event
	 *
	 * @return the thread ID
	 */
	public String getThreadId() {
		return id;
	}

	@Override
	public StateType newState() {
		return StateType.eStateRunning;
	}

}


text:
namespace cc {

ViewTransitionElementId::ViewTransitionElementId() = default;

ViewTransitionElementId::ViewTransitionElementId(uint32_t document_tag)
    : document_tag_(document_tag) {}

ViewTransitionElementId::ViewTransitionElementId(ViewTransitionElementId&&) =
    default;

ViewTransitionElementId::ViewTransitionElementId(
    const ViewTransitionElementId&) = default;

ViewTransitionElementId::~ViewTransitionElementId() = default;

void ViewTransitionElementId::AddIndex(uint32_t index) {
  DCHECK_NE(document_tag_, 0u);
  element_indices_.insert(index);
}

bool ViewTransitionElementId::Matches(uint32_t document_tag,
                                      uint32_t index) const {
  return document_tag_ == document_tag && element_indices_.count(index) != 0;
}

std::string ViewTransitionElementId::ToString() const {
  std::ostringstream str;
  str << "ViewTransitionElementId{ document_tag: " << document_tag_
      << " element_indices: [";
  std::string separator = "";
  for (auto index : element_indices_) {
    str << separator << index;
    separator = ", ";
  }
  str << "]}";
  return str.str();
}

}  // namespace cc


text:
from IPython.nbconvert.preprocessors import Preprocessor
from IPython.utils.traitlets import List, Unicode, Bool

class NbGraderPreprocessor(Preprocessor):

    default_language = Unicode('ipython')
    display_data_priority = List(['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'])
    enabled = Bool(True, config=True, help="Whether to use this preprocessor when running nbgrader")


text:
require 'spec_helper'

describe 'User squashes a merge request', :js do
  let(:user) { create(:user) }
  let(:project) { create(:project, :repository) }
  let(:source_branch) { 'csv' }

  let!(:original_head) { project.repository.commit('master') }

  shared_examples 'squash' do
    it 'squashes the commits into a single commit, and adds a merge commit' do
      expect(page).to have_content('Merged')

      latest_master_commits = project.repository.commits_between(original_head.sha, 'master').map(&:raw)

      squash_commit = an_object_having_attributes(sha: a_string_matching(/\h{40}/),
                                                  message: "Csv\n",
                                                  author_name: user.name,
                                                  committer_name: user.name)

      merge_commit = an_object_having_attributes(sha: a_string_matching(/\h{40}/),
                                                 message: a_string_starting_with("Merge branch 'csv' into 'master'"),
                                                 author_name: user.name,
                                                 committer_name: user.name)

      expect(project.repository).not_to be_merged_to_root_ref(source_branch)
      expect(latest_master_commits).to match([squash_commit, merge_commit])
    end
  end

  shared_examples 'no squash' do
    it 'accepts the merge request without squashing' do
      expect(page).to have_content('Merged')
      expect(project.repository).to be_merged_to_root_ref(source_branch)
    end
  end

  def accept_mr
    expect(page).to have_button('Merge')

    uncheck 'Remove source branch'
    click_on 'Merge'
  end

  before do
    # Prevent source branch from being removed so we can use be_merged_to_root_ref
    # method to check if squash was performed or not
    allow_any_instance_of(MergeRequest).to receive(:force_remove_source_branch?).and_return(false)
    project.add_maintainer(user)

    sign_in user
  end

  context 'when the MR has only one commit' do
    before do
      merge_request = create(:merge_request, source_project: project, target_project: project, source_branch: 'master', target_branch: 'branch-merged')

      visit project_merge_request_path(project, merge_request)
    end

    it 'does not show the squash checkbox' do
      expect(page).not_to have_field('squash')
    end
  end

  context 'when squash is enabled on merge request creation' do
    before do
      visit project_new_merge_request_path(project, merge_request: { target_branch: 'master', source_branch: source_branch })
      check 'merge_request[squash]'
      click_on 'Submit merge request'
      wait_for_requests
    end

    it 'shows the squash checkbox as checked' do
      expect(page).to have_checked_field('squash')
    end

    context 'when accepting with squash checked' do
      before do
        accept_mr
      end

      include_examples 'squash'
    end

    context 'when accepting and unchecking squash' do
      before do
        uncheck 'squash'
        accept_mr
      end

      include_examples 'no squash'
    end
  end

  context 'when squash is not enabled on merge request creation' do
    before do
      visit project_new_merge_request_path(project, merge_request: { target_branch: 'master', source_branch: source_branch })
      click_on 'Submit merge request'
      wait_for_requests
    end

    it 'shows the squash checkbox as unchecked' do
      expect(page).to have_unchecked_field('squash')
    end

    context 'when accepting and checking squash' do
      before do
        check 'squash'
        accept_mr
      end

      include_examples 'squash'
    end

    context 'when accepting with squash unchecked' do
      before do
        accept_mr
      end

      include_examples 'no squash'
    end
  end
end


text:
package e2e

import (
	"strings"
	"testing"

	"gotest.tools/v3/assert"
)

func TestComposePull(t *testing.T) {
	c := NewParallelCLI(t)

	t.Run("Verify image pulled", func(t *testing.T) {
		// cleanup existing images
		c.RunDockerComposeCmd(t, "--project-directory", "fixtures/compose-pull/simple", "down", "--rmi", "all")

		res := c.RunDockerComposeCmd(t, "--project-directory", "fixtures/compose-pull/simple", "pull")
		output := res.Combined()

		assert.Assert(t, strings.Contains(output, "simple Pulled"))
		assert.Assert(t, strings.Contains(output, "another Pulled"))

		// verify default policy is 'always' for pull command
		res = c.RunDockerComposeCmd(t, "--project-directory", "fixtures/compose-pull/simple", "pull")
		output = res.Combined()

		assert.Assert(t, strings.Contains(output, "simple Pulled"))
		assert.Assert(t, strings.Contains(output, "another Pulled"))
	})

	t.Run("Verify a image is pulled once", func(t *testing.T) {
		// cleanup existing images
		c.RunDockerComposeCmd(t, "--project-directory", "fixtures/compose-pull/duplicate-images", "down", "--rmi", "all")

		res := c.RunDockerComposeCmd(t, "--project-directory", "fixtures/compose-pull/duplicate-images", "pull")
		output := res.Combined()

		if strings.Contains(output, "another Pulled") {
			assert.Assert(t, strings.Contains(output, "another Pulled"))
			assert.Assert(t, strings.Contains(output, "Skipped - Image is already being pulled by another"))
		} else {
			assert.Assert(t, strings.Contains(output, "simple Pulled"))
			assert.Assert(t, strings.Contains(output, "Skipped - Image is already being pulled by simple"))
		}
	})

	t.Run("Verify skipped pull if image is already present locally", func(t *testing.T) {
		// make sure the required image is present
		c.RunDockerComposeCmd(t, "--project-directory", "fixtures/compose-pull/image-present-locally", "pull")

		res := c.RunDockerComposeCmd(t, "--project-directory", "fixtures/compose-pull/image-present-locally", "pull")
		output := res.Combined()

		assert.Assert(t, strings.Contains(output, "simple Skipped - Image is already present locally"))
		// image with :latest tag gets pulled regardless if pull_policy: missing or if_not_present
		assert.Assert(t, strings.Contains(output, "latest Pulled"))
	})

	t.Run("Verify skipped no image to be pulled", func(t *testing.T) {
		res := c.RunDockerComposeCmd(t, "--project-directory", "fixtures/compose-pull/no-image-name-given", "pull")
		output := res.Combined()

		assert.Assert(t, strings.Contains(output, "Skipped - No image to be pulled"))
	})
}


text:
package org.lodgvideon.hpalm.entity;

public class TestSetFolderBuilder extends AbstractEntityBuilder {

    public TestSetFolderBuilder() {
        super("test-set-folder");
    }

    public TestSetFolderBuilder setParentId(long id) {
        setValue("parent-id", DF_INTEGER.format(id));
        return this;
    }

    public TestSetFolderBuilder setName(String name) {
        setValue("name", name);
        return this;
    }

}


text:
class Core {
public:
    std::vector<ProcInfo> GetAllWindows();
    std::vector<ProcInfo> GetChildWindowsById(HWND hwnd);
    void SendCharByScanCode(int scanCode);
    void SendKeyByVkValue(int vk);
    void SendKey(std::string vkKey);
    void KeyDownByVKValue(int vk);
    void KeyDown(std::string vkKey);
    void KeyUpByVKValue(int vk);
    void KeyUp(std::string vkKey);
    void SendChar(char ch);
    void CombinationKeyByVKValue(std::vector<int> vks);
    void CombinationKey(std::vector<std::string> vkKeys);

    void MouseMove(int x, int y);//mouse move by screen coord
    void MouseMoveRelative(int x, int y);//mouse move by active window coord
    void MouseMoveOffset(int x, int y);//mouse move by cursor position
    int GetScreenX();
    int GetScreenY();
    Size Core::GetWinSize(HWND hwnd);
    Size Core::GetWinSize();
    Rect Core::GetWinRect(HWND hwnd);
    Rect Core::GetWinRect();
    void SetActiveWindow(HWND hwnd);
    void SetActiveWindow(std::string name);
    Point GetMousePosition();
    boolean RegisterHotKeyWithId(int id, unsigned int modifierKey, unsigned int key);
    WPARAM GetMessageReceived();
    long GetPixelAtCursorPosition();
    long GetPixelAt(int x, int y);
    Color PixelToColor(long pixelValue);
    void AppendProcInfo(ProcInfo procInfo);
    void AppendPropInfo(PropInfo propInfo);
    ProcInfo GetProcInfoByName(std::string name);
    void SwitchToWindow(HWND hwnd);
    void SwitchToWindow(std::string name);
    void MouseLeftDown();
    void MouseLeftUp();
    void MouseMiddleDown();
    void MouseMiddleUp();
    void MouseRightDown();
    void MouseRightUp();
    void MouseWheel(int value);
    void HideWindow(HWND hwnd);
    void HideWindow(std::string name);
    void DestroyWindow(HWND hwnd);
    void DestroyWindow(std::string name);
    void CaptureScreenToClipBoard(HWND hwnd);
    ImageData CaptureScreen(HWND hwnd, int left, int top, int width, int height);
    ImageData CaptureScreen(HWND hwnd);
    std::string GetTextById(HWND hwnd);
    std::vector<PropInfo> GetWindowProperties(HWND hwnd);
    static void Recycle();
    static Core* GetInstance();
    Size DesktopSize;
    Rect ActiveWindowRect;
private:
    Core();
    void Init();
    void SendKeyInput(KEYBDINPUT ki);
    void SendMouseInput(MOUSEINPUT mi);
    int ToScreenPosX(int x);
    int ToScreenPosY(int y);
    int ToAbsoluteScreenPosX(int x);
    int ToAbsoluteScreenPosY(int y);
    int ToOffsetPosX(int x, Point pt);
    int ToOffsetPosY(int y, Point pt);
    std::vector<ProcInfo> _procInfos;
    std::vector<PropInfo> _propInfos;
};


text:
<?php

namespace Omniship\Address;

use Omniship\Interfaces\ArrayableInterface;
use Omniship\Interfaces\ComponentInterface;
use Omniship\Interfaces\JsonableInterface;
use Omniship\Traits\Parameters;
use Omniship\Traits\ArrayAccess AS TraitArrayAccess;

class City implements ComponentInterface, ArrayableInterface, \JsonSerializable, JsonableInterface, \ArrayAccess
{

    use Parameters, TraitArrayAccess;

    /**
     * Create a new item with the specified parameters
     *
     * @param array|null $parameters An array of parameters to set on the new object
     */
    public function __construct(array $parameters = null)
    {
        $this->initialize($parameters);
    }

    /**
     * Get city id
     */
    public function getId()
    {
        return $this->getParameter('id');
    }

    /**
     * Set city id
     * @param $value
     * @return $this
     */
    public function setId($value)
    {
        return $this->setParameter('id', $value);
    }

    /**
     * Get city name
     */
    public function getName()
    {
        return $this->getParameter('name');
    }

    /**
     * Set city name
     * @param $value
     * @return $this
     */
    public function setName($value)
    {
        return $this->setParameter('name', $value);
    }

    /**
     * Get city ascii name
     */
    public function getAsciiName()
    {
        return $this->getParameter('ascii_name');
    }

    /**
     * Set city ascii name
     * @param $value
     * @return $this
     */
    public function setAsciiName($value)
    {
        return $this->setParameter('ascii_name', $value);
    }

    /**
     * Get city post_code
     */
    public function getPostCode()
    {
        return $this->getParameter('post_code');
    }

    /**
     * Set city post_code
     * @param $value
     * @return $this
     */
    public function setPostCode($value)
    {
        return $this->setParameter('post_code', $value);
    }

    /**
     * Get city type
     */
    public function getType()
    {
        return $this->getParameter('type');
    }

    /**
     * Set city type
     * @param $value
     * @return $this
     */
    public function setType($value)
    {
        return $this->setParameter('type', $value);
    }

    /**
     * Get city country ID
     */
    public function getCountryId()
    {
        return $this->getParameter('country_id');
    }

    /**
     * Set city country ID
     * @param $value
     * @return $this
     */
    public function setCountryId($value)
    {
        return $this->setParameter('country_id', $value);
    }

    /**
     * Get city country
     */
    public function getCountry()
    {
        return $this->getParameter('country');
    }

    /**
     * Set city country
     * @param $value
     * @return $this
     */
    public function setCountry($value)
    {
        return $this->setParameter('country', $value);
    }
}


text:
SYNONYM

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

#### Published in
null

#### Original name
Cylindrium septatum Bonord., 1851

### Remarks
null


text:
class ConvocationFireman < ActiveRecord::Base

  belongs_to :convocation
  belongs_to :fireman

  delegate :title, :place, :date, :to => :convocation, :prefix => true
  delegate :firstname, :lastname, :to => :fireman, :prefix => true

  scope :newer, -> { order('convocations.date DESC').includes(:convocation).limit(5) }
  scope :with_email, -> { includes(:fireman).where(["COALESCE(firemen.email, '') <> ''"])
                                            .references(:fireman) }

  before_create :set_grade_and_status

  scope :with_sha1, lambda { |sha1|
    where(['SHA1(id) = ?', sha1])
  }

  protected

  def set_grade_and_status
    self.grade = self.fireman.grade
    self.status = self.fireman.status
  end

end


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using AutoMapper;
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using MongoDB.Driver;
using MongoDB.Driver.GridFS;
using Newtonsoft.Json.Serialization;
using Owin;
using SnakeBattleNet.Core;
using SnakeBattleNet.Core.Contract;
using SnakeBattleNet.Web;
using SnakeBattleNet.Web.Core;
using SnakeBattleNet.Web.Core.Auth;
using SnakeBattleNet.Web.DependencyResolution;
using SnakeBattleNet.Web.DependencyResolution.Providers;
using SnakeBattleNet.Web.Models.Snake;
using StructureMap;

[assembly: OwinStartup(typeof(Bootstrap), "RegisterOwin")]
[assembly: WebActivator.PreApplicationStartMethod(typeof(Bootstrap), "RegisterDependencies")]

namespace SnakeBattleNet.Web
{
    public class Bootstrap
    {
        public static void RegisterOwin(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                LogoutPath = new PathString("/Account/Logout"),
                Provider = new CookieAuthenticationProvider()
            });
        }

        public static void RegisterApis(HttpConfiguration config)
        {
            // Use camel case for JSON data.
            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                );
        }

        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jb").Include(
                "~/js/jquery-{version}.js",
                "~/js/bootstrap.js"
                ));

            bundles.Add(new ScriptBundle("~/bundles/ks").Include(
                "~/js/kinetic-v5.1.0.js",
                "~/js/site.js"
                ));

            bundles.Add(new StyleBundle("~/bundles/css").Include(
                 "~/css/bootstrap.css",
                 "~/css/site.css"));
        }

        public static void RegisterDependencies()
        {
            ObjectFactory.Initialize(x =>
            {
                x.Scan(scan =>
                {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
                });
                x.For<IUserStore<UserIdentity>>().Use<CustomUserStore<UserIdentity>>();
                x.For<IUserRoleStore<UserIdentity>>().Use<CustomUserStore<UserIdentity>>();
                x.For<IUserSearch<UserIdentity>>().Use<CustomUserStore<UserIdentity>>();
                x.For<IAuthenticationManager>().HttpContextScoped().Use(() => HttpContext.Current.Request.GetOwinContext().Authentication);

                // Mongo
                x.For<MongoDatabaseProvider>().Use<MongoDatabaseProvider>()
                    .Ctor<string>().Is(ConfigurationManager.AppSettings.Get("MONGOLAB_URI") ?? "mongodb://localhost/SnakeBattle");

                x.For<MongoDatabase>().Singleton().Use(c => c.GetInstance<MongoDatabaseProvider>().ProvideDatabase());
                x.For(typeof(MongoCollection<>)).Use(c => c.GetInstance<MongoCollectionProvider>().ProvideCollection(c));
                x.For<ISnakeStore>().Singleton().Use<SnakeStore>();
                x.For<IFileStore>().Singleton().Use<FileStore>()
                    .Ctor<MongoGridFS>().Is(c => c.GetInstance<MongoDatabase>().GridFS);
            });

            var container = ObjectFactory.Container;
            DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
            GlobalConfiguration.Configuration.DependencyResolver = new StructureMapDependencyResolver(container);
        }

        public static void RegisterMappings()
        {
            Mapper.CreateMap<ChipCell, ChipCellViewModel>()
                .ConvertUsing(v => new ChipCellViewModel
                {
                    P = new Position { X = v.X, Y = v.Y },
                    C = v.Content,
                    Color = v.Color.Name,
                    Exclude = v.Exclude,
                    IsSelf = v.IsSelf
                });
            Mapper.CreateMap<ChipCellViewModel, ChipCell>()
                .ConvertUsing(v => new ChipCell
                {
                    X = v.P.X,
                    Y = v.P.Y,
                    Color = Color.All[v.Color],
                    Content = v.C,
                    Exclude = v.Exclude,
                    IsSelf = v.IsSelf
                });

            Mapper.CreateMap<Replay, ReplayViewModel>();
            Mapper.CreateMap<BattleField, IEnumerable<ContentViewModel>>()
                .ConvertUsing(v =>
                {
                    var models = new List<ContentViewModel>();
                    for (var x = 0; x < v.SideLength; x++)
                        for (var y = 0; y < v.SideLength; y++)
                            models.Add(new ContentViewModel { C = v[x, y], P = new Position { X = x, Y = y } });
                    return models;
                });
            Mapper.CreateMap<Cell<Content>, ContentViewModel>()
                .ConvertUsing(v => new ContentViewModel { C = v.Content, P = new Position { X = v.X, Y = v.Y } });

            Mapper.CreateMap<Snake, SnakeViewModel>();

            Mapper.CreateMap<Tuple<Snake, SnakeViewModel>, Snake>()
                .ForMember(d => d.Name, o => o.MapFrom(s => s.Item2.Name))
                .ForMember(d => d.Chips, o => o.MapFrom(s => s.Item2.Chips))

                .ForMember(d => d.Id, o => o.MapFrom(s => s.Item1.Id))
                .ForMember(d => d.OwnerId, o => o.MapFrom(s => s.Item1.OwnerId))
                .ForMember(d => d.Created, o => o.MapFrom(s => s.Item1.Created))
                .ForMember(d => d.Score, o => o.MapFrom(s => s.Item1.Score))
                .ForMember(d => d.Wins, o => o.MapFrom(s => s.Item1.Wins))
                .ForMember(d => d.Loses, o => o.MapFrom(s => s.Item1.Loses))
                .ForMember(d => d.Matches, o => o.MapFrom(s => s.Item1.Matches));
        }
    }
}


text:
require 'rails_helper'

RSpec.describe ActiveAdmin::MenuCollection do

  let(:menus) { ActiveAdmin::MenuCollection.new }

  describe "#add" do

    it "should initialize a new menu when first item" do
      menus.add :default, label: "Hello World"

      expect(menus.fetch(:default).items.size).to eq 1
      expect(menus.fetch(:default)["Hello World"]).to be_an_instance_of(ActiveAdmin::MenuItem)
    end

    it "should add items to an existing menu" do
      menus.add :default, label: "Hello World"
      menus.add :default, label: "Hello World Again"

      expect(menus.fetch(:default).items.size).to eq 2
    end

  end

  describe "#clear!" do

    it "should remove all menus" do
      menus.add :default, label: "Hello World"

      menus.clear!

      expect {
        menus.fetch(:non_default_menu)
      }.to raise_error(ActiveAdmin::NoMenuError)

    end

  end

  describe "#on_build" do

    it "runs a callback when fetching a menu" do
      menus.on_build do |m|
        m.add :default, label: "Hello World"
      end

      expect(menus.fetch(:default)["Hello World"]).to_not eq nil
    end

    it "re-runs the callbacks when the menu is cleared" do
      menus.on_build do |m|
        m.add :default, label: "Hello World"
      end

      expect(menus.fetch(:default)["Hello World"]).to_not eq nil
      menus.clear!
      expect(menus.fetch(:default)["Hello World"]).to_not eq nil
    end

  end

end


text:
<?php

/* PortfolioBundle:About:add.html.twig */
class __TwigTemplate_4a563a632b0c6c4a58fe22c72fcc2ca063ff2f92b66292b0c50971d04297bb2d extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("::admin.html.twig");

        $this->blocks = array(
            'title' => array($this, 'block_title'),
            'header' => array($this, 'block_header'),
            'body' => array($this, 'block_body'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "::admin.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 2
    public function block_title($context, array $blocks = array())
    {
        echo "Portfolio : Administration : About";
    }

    // line 3
    public function block_header($context, array $blocks = array())
    {
        echo "
Protfolio : administration : About : Add
";
    }

    // line 4
    public function block_body($context, array $blocks = array())
    {
        // line 5
        echo "
";
        // line 6
        $context['_parent'] = (array) $context;
        $context['_seq'] = twig_ensure_traversable($this->getAttribute($this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "session"), "flashbag"), "get", array(0 => "info"), "method"));
        foreach ($context['_seq'] as $context["_key"] => $context["flashMessage"]) {
            // line 7
            echo "

        ";
            // line 8
            echo twig_escape_filter($this->env, (isset($context["flashMessage"]) ? $context["flashMessage"] : $this->getContext($context, "flashMessage")), "html", null, true);
            echo "

";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['_key'], $context['flashMessage'], $context['_parent'], $context['loop']);
        $context = array_intersect_key($context, $_parent) + $_parent;
        // line 11
        echo "<form action=\"\" method=\"post\" ";
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'enctype');
        echo " class=\"form-horizontal\" >
    ";
        // line 13
        echo "    ";
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'errors');
        echo "

        ";
        // line 16
        echo "        ";
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "description"), 'label', array("label_attr" => array("class" => "control-label"), "label" => "description"));
        echo "

            ";
        // line 18
        echo "
            ";
        // line 19
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "description"), 'errors');
        echo "
            ";
        // line 21
        echo "            ";
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "description"), 'widget', array("attr" => array("class" => "description")));
        echo "

        ";
        // line 26
        echo "        ";
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "active"), 'label', array("label_attr" => array("class" => "control-label"), "label" => "Acive"));
        echo "

            ";
        // line 28
        echo "
            ";
        // line 29
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "active"), 'errors');
        echo "
            ";
        // line 31
        echo "            ";
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "active"), 'widget', array("attr" => array("class" => "active")));
        echo "

            env->getExtension('routing')->getPath("portfolio_about_admin");
        echo "\" class=\"btn btn-primary\" style=\"margin-right: 126px;\" >Back
            ";
        // line 37
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'rest');
        echo "
            ";
        // line 38
        echo "
            <input type=\"submit\" name=\"add\" value=\"Add\" id=\"add\" class=\"btn btn-warning\" >

</form>
";
    }

    public function getTemplateName()
    {
        return "PortfolioBundle:About:add.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  126 => 38,  122 => 37,  118 => 36,  109 => 31,  105 => 29,  102 => 28,  96 => 26,  88 => 21,  84 => 19,  81 => 18,  75 => 16,  69 => 13,  64 => 11,  55 => 8,  52 => 7,  48 => 6,  45 => 5,  42 => 4,  36 => 3,  30 => 2,);
    }
}


text:
[![Build Status](https://travis-ci.org/cmars/usso-login.svg?branch=master)](https://travis-ci.org/cmars/usso-login)

# usso-login

Authenticate to [Ubuntu SSO](https://login.ubuntu.com) from the command-line.

This is useful for browserless, command-line interaction with APIs that use
Ubuntu SSO OAuth/OpenID for authentication. For example, Launchpad or Juju
Charms.

Consider this experimental and unsupported. Pull requests welcome.

# Build Dependencies

Developed and tested with Go 1.5.

# Build

## I'm feeling lucky

This might not work if any of the dependencies introduce breaking changes.

    $ go get github.com/cmars/usso-login

## With known-good versions of dependencies

    $ go get launchpad.net/godeps
    $ go get -d github.com/cmars/usso-login
    $ (cd $GOPATH; $GOPATH/bin/godeps -u dependencies.tsv)
    $ go install github.com/cmars/usso-login

# Typical Usage

## Log in and store an Ubuntu SSO cookie

    $ usso-login
    Email: azurediamond@hotmail.com
    Password: *******
    Two-Factor Auth: ******
    $

You'll be prompted for email, password, and possibly two-factor auth if you
have it set up. The cookie is then stored in `$HOME/.usso-cookies`.

## Non-interactive Use

If you're not using two-factor auth, you can log in non-interactively with
environment variables. This is useful when you don't have a terminal.

    $ export USSO_EMAIL=azurediamond@hotmail.com
    $  export USSO_PASSWORD=hunter2  # prefix with a space to keep it out of your .bash_history
    $ ... usso-login will use environment variables for these instead of prompting ...

## Using for command-line authentication

    $ export BROWSER=/path/to/usso-login
    $ charm publish /my/awesome/charm

...

    Email: azurediamond@hotmail.com
    Password: *******
    Two-Factor Auth: ******

...

# Known Issues

Reading input from terminal will fail if stdin is not hooked up to a terminal.
When using as a $BROWSER, in some cases the process is launched without stdin.
The best way to work around this is to log in ahead of time to store the
cookie.

Depends on the page contents and behavior of Ubuntu SSO. If that changes, this
will probably break.

# Debugging

    $ export USSO_DEBUG=1

Will print requests and responses to the terminal to help debug HTTP interactions.

---

Copyright 2015 Casey Marshall

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.


text:
package org.conqat.engine.cpp.preprocessor.parser;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.regex.Pattern;

import org.conqat.engine.core.core.ConQATException;
import org.conqat.engine.core.logging.IConQATLogger;
import org.conqat.engine.sourcecode.resource.ITokenElement;
import org.conqat.lib.commons.collections.CollectionUtils;
import org.conqat.lib.scanner.ETokenType;
import org.conqat.lib.scanner.IToken;

/**
 * Parser for preprocessor conditionals. This does not (yet) deal with macros
 * (#define) and includes.
 *
 * @author $Author: feilkas $
 * @version $Rev: 41746 $
 * @ConQAT.Rating GREEN Hash: F8EC1AFB42F3CC55D0E678E45EDE2171
 */
public class PreprocessorParser {

	/** Pattern for the #if/#if(n)def. */
	private static final Pattern IF_PATTERN = Pattern
			.compile("(?is)^#\\s*if(?:n?def)?((\\s|[(]).*)$");

	/** Pattern for the #elif. */
	private static final Pattern ELIF_PATTERN = Pattern
			.compile("(?is)^#\\s*elif((\\s|[(]).*)$");

	/** Pattern for the #if/#if(n)def/#elif. First group matches condition. */
	/* package */static final Pattern IF_OR_ELIF_PATTERN = Pattern
			.compile("(?is)^#\\s*(?:el)?if(?:n?def)?((\\s|[(]).*)$");

	/** Pattern for the #else. */
	private static final Pattern ELSE_PATTERN = Pattern
			.compile("(?is)^#\\s*else.*");

	/** Pattern for the #endif. */
	private static final Pattern ENDIF_PATTERN = Pattern
			.compile("(?is)^#\\s*endif.*");

	/** The result list. */
	private final List<PreprocessorNodeBase> result = new ArrayList<PreprocessorNodeBase>();

	/** Stack of currently open conditions. */
	private final Stack<PreprocessorConditionNode> openCondition = new Stack<PreprocessorConditionNode>();

	/** Constructor. */
	private PreprocessorParser() {
		// prevent instantiation
	}

	/**
	 * Performs the actual parsing. This should be only called once for a newly
	 * constructed instance.
	 */
	private List<PreprocessorNodeBase> doParse(List<IToken> tokens)
			throws ConQATException {
		for (IToken token : tokens) {
			if (token.getType() != ETokenType.PREPROCESSOR_DIRECTIVE) {
				insertToken(token);
			} else if (isIfToken(token)) {
				PreprocessorConditionNode condition = new PreprocessorConditionNode(
						token);
				// important: insert first, then push, as we might insert to the
				// head of the stack
				insertCondition(condition);
				openCondition.push(condition);
			} else if (isElifToken(token) || isElseToken(token)) {
				if (openCondition.isEmpty()) {
					throw new ConQATException(
							"Found #elif/#else without previous #if* in line "
									+ token.getLineNumber());
				}
				openCondition.peek().addBranch(token);
			} else if (isEndifToken(token)) {
				if (openCondition.isEmpty()) {
					throw new ConQATException(
							"Found #endif without previous #if* in line "
									+ token.getLineNumber());
				}
				openCondition.pop().close(token);
			} else {
				// handle #define, #error, etc. just as normal tokens
				insertToken(token);
			}
		}

		if (!openCondition.isEmpty()) {
			throw new ConQATException("There are unclosed conditionals!");
		}

		return result;
	}

	/** Returns if the given pattern is an #if, #ifdef, or #ifndef token. */
	public static boolean isIfToken(IToken token) {
		return IF_PATTERN.matcher(token.getText()).matches();
	}

	/** Returns if the given pattern is an #else token. */
	public static boolean isElseToken(IToken token) {
		return ELSE_PATTERN.matcher(token.getText()).matches();
	}

	/** Returns if the given pattern is an #elif token. */
	public static boolean isElifToken(IToken token) {
		return ELIF_PATTERN.matcher(token.getText()).matches();
	}

	/** Returns if the given pattern is an #endif token. */
	public static boolean isEndifToken(IToken token) {
		return ENDIF_PATTERN.matcher(token.getText()).matches();
	}

	/**
	 * Inserts a new condition node into the currently open condition branch or
	 * the result list.
	 */
	private void insertCondition(PreprocessorConditionNode node) {
		if (openCondition.isEmpty()) {
			result.add(node);
		} else {
			openCondition.peek().getLastBranch().containedCode.add(node);
		}
	}

	/**
	 * Inserts a token into the currently open condition branch or the result
	 * list.
	 */
	private void insertToken(IToken token) {
		if (openCondition.isEmpty()) {
			insertIntoNodeList(token, result);
		} else {
			insertIntoNodeList(token,
					openCondition.peek().getLastBranch().containedCode);
		}
	}

	/** Inserts a non-preprocessor token into a list of nodes. */
	private void insertIntoNodeList(IToken token,
			List<PreprocessorNodeBase> nodeList) {
		PreprocessorNodeBase lastNode = null;
		if (!nodeList.isEmpty()) {
			lastNode = CollectionUtils.getLast(nodeList);
		}

		if (!(lastNode instanceof TokenSequencePreprocessorNode)) {
			lastNode = new TokenSequencePreprocessorNode();
			nodeList.add(lastNode);
		}
		((TokenSequencePreprocessorNode) lastNode).addToken(token);
	}

	/** Parses the given element. */
	public static List<PreprocessorNodeBase> parse(ITokenElement element,
			IConQATLogger logger) throws ConQATException {
		return parse(element.getTokens(logger));
	}

	/** Parses the given tokens. */
	private static List<PreprocessorNodeBase> parse(List<IToken> tokens)
			throws ConQATException {
		return new PreprocessorParser().doParse(tokens);
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Fungal Diversity 31: 88 (2008)

#### Original name
Cosmospora cupularis J. Luo & W.Y. Zhuang

### Remarks
null


text:
'use strict';
import ReactDOM from 'react-dom';
import assign from 'object-assign';

var checkSpecKeys = function (spec, keysArray) {
  return keysArray.reduce((value, key) => {
    return value && spec.hasOwnProperty(key);
  }, true) ? null : console.error('Keys Missing', spec);
};

export var round = function(value) {
  /*
   * http://keithclark.co.uk/articles/gpu-text-rendering-in-webkit/
   * If we want a size divisible by 2:
   * return (Math.ceil(value) / 2) * 2;
   */
  return Math.ceil(value);
};

export var getTrackCSS = function(spec) {
  checkSpecKeys(spec, [
    'left', 'variableWidth', 'slideCount', 'slidesToShow', 'slideWidth'
  ]);

  var trackWidth, trackHeight;

  const trackChildren = (spec.slideCount + 2 * spec.slidesToShow);

  if (!spec.vertical) {
    if (spec.variableWidth) {
      trackWidth = (spec.slideCount + 2*spec.slidesToShow) * spec.slideWidth;
    } else if (spec.centerMode) {
      trackWidth = (spec.slideCount + 2*(spec.slidesToShow + 1)) * spec.slideWidth;
    } else {
      trackWidth = (spec.slideCount + 2*spec.slidesToShow) * spec.slideWidth;
    }
  } else {
    trackHeight = trackChildren * spec.slideHeight;
  }

  var style = {
    opacity: 1,
    WebkitTransform: !spec.vertical ? 'translate3d(' + spec.left + 'px, 0px, 0px)' : 'translate3d(0px, ' + spec.left + 'px, 0px)',
    transform: !spec.vertical ? 'translate3d(' + spec.left + 'px, 0px, 0px)' : 'translate3d(0px, ' + spec.left + 'px, 0px)',
    transition: '',
    WebkitTransition: '',
    msTransform: !spec.vertical ? 'translateX(' + spec.left + 'px)' : 'translateY(' + spec.left + 'px)',
  };

  if (trackWidth) {
    assign(style, { width: round(trackWidth) });
  }

  if (trackHeight) {
    assign(style, { height: round(trackHeight) });
  }

  // Fallback for IE8
  if (window && !window.addEventListener && window.attachEvent) {
    if (!spec.vertical) {
      style.marginLeft = spec.left + 'px';
    } else {
      style.marginTop = spec.left + 'px';
    }
  }

  return style;
};

export var getTrackAnimateCSS = function (spec) {
  checkSpecKeys(spec, [
    'left', 'variableWidth', 'slideCount', 'slidesToShow', 'slideWidth', 'speed', 'cssEase'
  ]);

  var style = getTrackCSS(spec);
  // useCSS is true by default so it can be undefined
  style.WebkitTransition = '-webkit-transform ' + spec.speed + 'ms ' + spec.cssEase;
  style.transition = 'transform ' + spec.speed + 'ms ' + spec.cssEase;
  return style;
};

export var getTrackLeft = function (spec) {

  checkSpecKeys(spec, [
   'slideIndex', 'trackRef', 'infinite', 'centerMode', 'slideCount', 'slidesToShow',
   'slidesToScroll', 'slideWidth', 'listWidth', 'variableWidth', 'slideHeight']);

  var slideOffset = 0;
  var targetLeft;
  var targetSlide;
  var verticalOffset = 0;

  if (spec.fade) {
    return 0;
  }

  if (spec.infinite) {
    if (spec.slideCount >= spec.slidesToShow) {
      slideOffset = (spec.slideWidth * spec.slidesToShow) * -1;
      verticalOffset = (spec.slideHeight * spec.slidesToShow) * -1;
    }
    if (spec.slideCount % spec.slidesToScroll !== 0) {
      if (spec.slideIndex + spec.slidesToScroll > spec.slideCount && spec.slideCount > spec.slidesToShow) {
          if(spec.slideIndex > spec.slideCount) {
            slideOffset = ((spec.slidesToShow - (spec.slideIndex - spec.slideCount)) * spec.slideWidth) * -1;
            verticalOffset = ((spec.slidesToShow - (spec.slideIndex - spec.slideCount)) * spec.slideHeight) * -1;
          } else {
            slideOffset = ((spec.slideCount % spec.slidesToScroll) * spec.slideWidth) * -1;
            verticalOffset = ((spec.slideCount % spec.slidesToScroll) * spec.slideHeight) * -1;
          }
      }
    }
  } else {

    if (spec.slideCount % spec.slidesToScroll !== 0) {
      if (spec.slideIndex + spec.slidesToScroll > spec.slideCount && spec.slideCount > spec.slidesToShow) {
          var slidesToOffset = spec.slidesToShow - (spec.slideCount % spec.slidesToScroll);
          slideOffset = slidesToOffset * spec.slideWidth;
      }
    }
  }

  if (spec.centerMode) {
    if(spec.infinite) {
      slideOffset += spec.slideWidth * Math.floor(spec.slidesToShow / 2);
    } else {
      slideOffset = spec.slideWidth * Math.floor(spec.slidesToShow / 2);
    }
  }

  if (!spec.vertical) {
    targetLeft = ((spec.slideIndex * spec.slideWidth) * -1) + slideOffset;
  } else {
    targetLeft = ((spec.slideIndex * spec.slideHeight) * -1) + verticalOffset;
  }

  if (spec.variableWidth === true) {
      var targetSlideIndex;
      if(spec.slideCount <= spec.slidesToShow || spec.infinite === false) {
          targetSlide = ReactDOM.findDOMNode(spec.trackRef).childNodes[spec.slideIndex];
      } else {
          targetSlideIndex = (spec.slideIndex + spec.slidesToShow);
          targetSlide = ReactDOM.findDOMNode(spec.trackRef).childNodes[targetSlideIndex];
      }
      targetLeft = targetSlide ? targetSlide.offsetLeft * -1 : 0;
      if (spec.centerMode === true) {
          if(spec.infinite === false) {
              targetSlide = ReactDOM.findDOMNode(spec.trackRef).children[spec.slideIndex];
          } else {
              targetSlide = ReactDOM.findDOMNode(spec.trackRef).children[(spec.slideIndex + spec.slidesToShow + 1)];
          }

          if (targetSlide) {
            targetLeft = targetSlide.offsetLeft * -1 + (spec.listWidth - targetSlide.offsetWidth) / 2;
          }
      }
  }

  return round(targetLeft);
};