text:
package demo

import (
	"bytes"
	"context"
	"database/sql"
	"fmt"
	"github.com/jackc/pgx/v4"
	"github.com/pkg/errors"
	"github.com/rickb777/date"
	"github.com/rickb777/sqlapi"
	"github.com/rickb777/sqlapi/constraint"
	"github.com/rickb777/sqlapi/driver"
	"github.com/rickb777/sqlapi/require"
	"github.com/rickb777/sqlapi/support"
	"github.com/rickb777/where"
	"github.com/rickb777/where/dialect"
	"github.com/rickb777/where/quote"
	"io"
	"strings"
)

// DatesTabler lists table methods provided by DatesTable.
type DatesTabler interface {
	sqlapi.Table

	// Constraints returns the table's constraints.
	Constraints() constraint.Constraints

	// WithConstraint returns a modified DatesTabler with added data consistency constraints.
	WithConstraint(cc ...constraint.Constraint) DatesTabler

	// WithPrefix returns a modified DatesTabler with a given table name prefix.
	WithPrefix(pfx string) DatesTabler

	// WithContext returns a modified DatesTabler with a given context.
	WithContext(ctx context.Context) DatesTabler

	// CreateTable creates the table.
	CreateTable(ifNotExists bool) (int64, error)

	// DropTable drops the table, destroying all its data.
	DropTable(ifExists bool) (int64, error)

	// Truncate drops every record from the table, if possible.
	Truncate(force bool) (err error)
}

//-------------------------------------------------------------------------------------------------

// DatesQueryer lists query methods provided by DatesTable.
type DatesQueryer interface {
	sqlapi.Table

	// Using returns a modified DatesQueryer using the Execer supplied,
	// which will typically be a transaction (i.e. SqlTx).
	Using(tx sqlapi.Execer) DatesQueryer

	// Transact runs the function provided within a transaction. The transction is committed
	// unless an error occurs.
	Transact(txOptions *pgx.TxOptions, fn func(DatesQueryer) error) error

	// Exec executes a query without returning any rows.
	Exec(req require.Requirement, query string, args ...interface{}) (int64, error)

	// Query is the low-level request method for this table using an SQL query that must return all the columns
	// necessary for Dates values.
	Query(req require.Requirement, query string, args ...interface{}) ([]*Dates, error)

	// QueryOneNullString is a low-level access method for one string, returning the first match.
	QueryOneNullString(req require.Requirement, query string, args ...interface{}) (result sql.NullString, err error)

	// QueryOneNullInt64 is a low-level access method for one int64, returning the first match.
	QueryOneNullInt64(req require.Requirement, query string, args ...interface{}) (result sql.NullInt64, err error)

	// QueryOneNullFloat64 is a low-level access method for one float64, returning the first match.
	QueryOneNullFloat64(req require.Requirement, query string, args ...interface{}) (result sql.NullFloat64, err error)

	// GetDatesById gets the record with a given primary key value.
	GetDatesById(req require.Requirement, id uint64) (*Dates, error)

	// GetManyDatesById gets records from the table according to a list of primary keys.
	GetManyDatesById(req require.Requirement, qc where.QueryConstraint, id ...uint64) (list []*Dates, err error)

	// Fetch fetches a list of Dates based on a supplied query. This is mostly used for join queries that map its
	// result columns to the fields of Dates. Other queries might be better handled by GetXxx or Select methods.
	Fetch(req require.Requirement, query string, args ...interface{}) ([]*Dates, error)

	// SelectOneWhere allows a single Dates to be obtained from the table that matches a 'where' clause.
	SelectOneWhere(req require.Requirement, where, orderBy string, args ...interface{}) (*Dates, error)

	// SelectOne allows a single Dates to be obtained from the table that matches a 'where' clause.
	SelectOne(req require.Requirement, wh where.Expression, qc where.QueryConstraint) (*Dates, error)

	// SelectWhere allows ManyDates to be obtained from the table that match a 'where' clause.
	SelectWhere(req require.Requirement, where, orderBy string, args ...interface{}) ([]*Dates, error)

	// Select allows ManyDates to be obtained from the table that match a 'where' clause.
	Select(req require.Requirement, wh where.Expression, qc where.QueryConstraint) ([]*Dates, error)

	// CountWhere counts ManyDates in the table that match a 'where' clause.
	CountWhere(where string, args ...interface{}) (count int64, err error)

	// Count counts the ManyDates in the table that match a 'where' clause.
	Count(wh where.Expression) (count int64, err error)

	// SliceID gets the id column for all rows that match the 'where' condition.
	SliceID(req require.Requirement, wh where.Expression, qc where.QueryConstraint) ([]uint64, error)

	// SliceInteger gets the integer column for all rows that match the 'where' condition.
	SliceInteger(req require.Requirement, wh where.Expression, qc where.QueryConstraint) ([]date.Date, error)

	// SliceString gets the string column for all rows that match the 'where' condition.
	SliceString(req require.Requirement, wh where.Expression, qc where.QueryConstraint) ([]date.DateString, error)

	// Insert adds new records for the ManyDates, setting the primary key field for each one.
	Insert(req require.Requirement, vv ...*Dates) error

	// UpdateByID updates one or more columns, given a id value.
	UpdateByID(req require.Requirement, id uint64, fields ...sql.NamedArg) (int64, error)

	// UpdateByInteger updates one or more columns, given a integer value.
	UpdateByInteger(req require.Requirement, integer date.Date, fields ...sql.NamedArg) (int64, error)

	// UpdateByString updates one or more columns, given a string value.
	UpdateByString(req require.Requirement, string date.DateString, fields ...sql.NamedArg) (int64, error)

	// UpdateFields updates one or more columns, given a 'where' clause.
	UpdateFields(req require.Requirement, wh where.Expression, fields ...sql.NamedArg) (int64, error)

	// Update updates records, matching them by primary key.
	Update(req require.Requirement, vv ...*Dates) (int64, error)

	// Upsert inserts or updates a record, matching it using the expression supplied.
	// This expression is used to search for an existing record based on some specified
	// key column(s). It must match either zero or one existing record. If it matches
	// none, a new record is inserted; otherwise the matching record is updated. An
	// error results if these conditions are not met.
	Upsert(v *Dates, wh where.Expression) error

	// DeleteByID deletes rows from the table, given some id values.
	// The list of ids can be arbitrarily long.
	DeleteByID(req require.Requirement, id ...uint64) (int64, error)

	// DeleteByInteger deletes rows from the table, given some integer values.
	// The list of ids can be arbitrarily long.
	DeleteByInteger(req require.Requirement, integer ...date.Date) (int64, error)

	// DeleteByString deletes rows from the table, given some string values.
	// The list of ids can be arbitrarily long.
	DeleteByString(req require.Requirement, string ...date.DateString) (int64, error)

	// Delete deletes one or more rows from the table, given a 'where' clause.
	// Use a nil value for the 'wh' argument if it is not needed (very risky!).
	Delete(req require.Requirement, wh where.Expression) (int64, error)
}

//-------------------------------------------------------------------------------------------------

// DatesTable holds a given table name with the database reference, providing access methods below.
// The Prefix field is often blank but can be used to hold a table name prefix (e.g. ending in '_'). Or it can
// specify the name of the schema, in which case it should have a trailing '.'.
type DatesTable struct {
	sqlapi.CoreTable
	constraints constraint.Constraints
	ctx         context.Context
	pk          string
}

// Type conformance checks
var _ sqlapi.TableCreator = &DatesTable{}

// NewDatesTable returns a new table instance.
// If a blank table name is supplied, the default name "manydates" will be used instead.
// The request context is initialised with the background.
func NewDatesTable(name string, d sqlapi.SqlDB) DatesTable {
	if name == "" {
		name = "manydates"
	}
	var constraints constraint.Constraints
	return DatesTable{
		CoreTable: sqlapi.CoreTable{
			Nm: sqlapi.TableName{Prefix: "", Name: name},
			Ex: d,
		},
		constraints: constraints,
		ctx:         context.Background(),
		pk:          "id",
	}
}

// CopyTableAsDatesTable copies a table instance, retaining the name etc but
// providing methods appropriate for 'Dates'.It doesn't copy the constraints of the original table.
//
// It serves to provide methods appropriate for 'Dates'. This is most useful when this is used to represent a
// join result. In such cases, there won't be any need for DDL methods, nor Exec, Insert, Update or Delete.
func CopyTableAsDatesTable(origin sqlapi.Table) DatesTable {
	return DatesTable{
		CoreTable: sqlapi.CoreTable{
			Nm: origin.Name(),
			Ex: origin.Execer(),
		},
		constraints: nil,
		ctx:         origin.Ctx(),
		pk:          "id",
	}
}

// SetPkColumn sets the name of the primary key column. It defaults to "id".
// The result is a modified copy of the table; the original is unchanged.
//func (tbl DatesTable) SetPkColumn(pk string) DatesTabler {
//	tbl.pk = pk
//	return tbl
//}

// WithPrefix sets the table name prefix for subsequent queries.
// The result is a modified copy of the table; the original is unchanged.
func (tbl DatesTable) WithPrefix(pfx string) DatesTabler {
	tbl.Nm.Prefix = pfx
	return tbl
}

// WithContext sets the context for subsequent queries via this table.
// The result is a modified copy of the table; the original is unchanged.
func (tbl DatesTable) WithContext(ctx context.Context) DatesTabler {
	tbl.ctx = ctx
	return tbl
}

// WithConstraint returns a modified DatesTabler with added data consistency constraints.
func (tbl DatesTable) WithConstraint(cc ...constraint.Constraint) DatesTabler {
	tbl.constraints = append(tbl.constraints, cc...)
	return tbl
}

// Constraints returns the table's constraints.
func (tbl DatesTable) Constraints() constraint.Constraints {
	return tbl.constraints
}

// Ctx gets the current request context.
func (tbl DatesTable) Ctx() context.Context {
	return tbl.ctx
}

// PkColumn gets the column name used as a primary key.
func (tbl DatesTable) PkColumn() string {
	return tbl.pk
}

// Using returns a modified DatesTabler using the the Execer supplied,
// which will typically be a transaction (i.e. SqlTx). This is needed when making multiple
// queries across several tables within a single transaction.
//
// The result is a modified copy of the table; the original is unchanged.
func (tbl DatesTable) Using(tx sqlapi.Execer) DatesQueryer {
	tbl.Ex = tx
	return tbl
}

// Transact runs the function provided within a transaction. If the function completes without error,
// the transaction is committed. If there is an error or a panic, the transaction is rolled back.
//
// The options can be nil, in which case the default behaviour is that of the underlying connection.
//
// Nested transactions (i.e. within 'fn') are permitted: they execute within the outermost transaction.
// Therefore they do not commit until the outermost transaction commits.
func (tbl DatesTable) Transact(txOptions *pgx.TxOptions, fn func(DatesQueryer) error) error {
	var err error
	if tbl.IsTx() {
		err = fn(tbl) // nested transactions are inlined
	} else {
		err = tbl.DB().Transact(tbl.ctx, txOptions, func(tx sqlapi.SqlTx) error {
			return fn(tbl.Using(tx))
		})
	}
	return tbl.Logger().LogIfError(tbl.Ctx(), err)
}

func (tbl DatesTable) quotedName() string {
	return tbl.Dialect().Quoter().Quote(tbl.Nm.String())
}

func (tbl DatesTable) quotedNameW(w driver.StringWriter) {
	tbl.Dialect().Quoter().QuoteW(w, tbl.Nm.String())
}

//-------------------------------------------------------------------------------------------------

// NumDatesTableColumns is the total number of columns in DatesTable.
const NumDatesTableColumns = 3

// NumDatesTableDataColumns is the number of columns in DatesTable not including the auto-increment key.
const NumDatesTableDataColumns = 2

// DatesTableColumnNames is the list of columns in DatesTable.
const DatesTableColumnNames = "id,integer,string"

// DatesTableDataColumnNames is the list of data columns in DatesTable.
const DatesTableDataColumnNames = "integer,string"

var listOfDatesTableColumnNames = strings.Split(DatesTableColumnNames, ",")

//-------------------------------------------------------------------------------------------------

var sqlDatesTableCreateColumnsSqlite = []string{
	"integer not null primary key autoincrement",
	"bigint not null",
	"text not null",
}

var sqlDatesTableCreateColumnsMysql = []string{
	"bigint unsigned not null primary key auto_increment",
	"bigint not null",
	"text not null",
}

var sqlDatesTableCreateColumnsPostgres = []string{
	"bigserial not null primary key",
	"bigint not null",
	"text not null",
}

//-------------------------------------------------------------------------------------------------

// CreateTable creates the table.
func (tbl DatesTable) CreateTable(ifNotExists bool) (int64, error) {
	return support.Exec(tbl, nil, createDatesTableSql(tbl, ifNotExists))
}

func createDatesTableSql(tbl DatesTabler, ifNotExists bool) string {
	buf := &bytes.Buffer{}
	buf.WriteString("CREATE TABLE ")
	if ifNotExists {
		buf.WriteString("IF NOT EXISTS ")
	}
	q := tbl.Dialect().Quoter()
	q.QuoteW(buf, tbl.Name().String())
	buf.WriteString(" (\n ")

	var columns []string
	switch tbl.Dialect().Index() {
	case dialect.Sqlite:
		columns = sqlDatesTableCreateColumnsSqlite
	case dialect.Mysql:
		columns = sqlDatesTableCreateColumnsMysql
	case dialect.Postgres:
		columns = sqlDatesTableCreateColumnsPostgres
	}

	comma := ""
	for i, n := range listOfDatesTableColumnNames {
		buf.WriteString(comma)
		q.QuoteW(buf, n)
		buf.WriteString(" ")
		buf.WriteString(columns[i])
		comma = ",\n "
	}

	for i, c := range tbl.(DatesTable).Constraints() {
		buf.WriteString(",\n ")
		buf.WriteString(c.ConstraintSql(tbl.Dialect().Quoter(), tbl.Name(), i+1))
	}

	buf.WriteString("\n)")
	buf.WriteString(tbl.Dialect().CreateTableSettings())
	return buf.String()
}

func ternaryDatesTable(flag bool, a, b string) string {
	if flag {
		return a
	}
	return b
}

// DropTable drops the table, destroying all its data.
func (tbl DatesTable) DropTable(ifExists bool) (int64, error) {
	return support.Exec(tbl, nil, dropDatesTableSql(tbl, ifExists))
}

func dropDatesTableSql(tbl DatesTabler, ifExists bool) string {
	ie := ternaryDatesTable(ifExists, "IF EXISTS ", "")
	quotedName := tbl.Dialect().Quoter().Quote(tbl.Name().String())
	query := fmt.Sprintf("DROP TABLE %s%s", ie, quotedName)
	return query
}

//-------------------------------------------------------------------------------------------------

// Truncate drops every record from the table, if possible. It might fail if constraints exist that
// prevent some or all rows from being deleted; use the force option to override this.
//
// When 'force' is set true, be aware of the following consequences.
// When using Mysql, foreign keys in other tables can be left dangling.
// When using Postgres, a cascade happens, so all 'adjacent' tables (i.e. linked by foreign keys)
// are also truncated.
func (tbl DatesTable) Truncate(force bool) (err error) {
	for _, query := range tbl.Dialect().TruncateDDL(tbl.Name().String(), force) {
		_, err = support.Exec(tbl, nil, query)
		if err != nil {
			return err
		}
	}
	return nil
}

//-------------------------------------------------------------------------------------------------

// Exec executes a query without returning any rows.
// It returns the number of rows affected (if the database driver supports this).
//
// The args are for any placeholder parameters in the query.
func (tbl DatesTable) Exec(req require.Requirement, query string, args ...interface{}) (int64, error) {
	return support.Exec(tbl, req, query, args...)
}

//-------------------------------------------------------------------------------------------------

// Query is the low-level request method for this table. The SQL query must return all the columns necessary for
// Dates values. Placeholders should be vanilla '?' marks, which will be replaced if necessary according to
// the chosen dialect.
//
// The query is logged using whatever logger is configured. If an error arises, this too is logged.
//
// If you need a context other than the background, use WithContext before calling Query.
//
// The args are for any placeholder parameters in the query.
//
// The support API provides a core 'support.Query' function, on which this method depends. If appropriate,
// use that function directly; wrap the result in *sqlapi.Rows if you need to access its data as a map.
func (tbl DatesTable) Query(req require.Requirement, query string, args ...interface{}) ([]*Dates, error) {
	return doDatesTableQueryAndScan(tbl, req, false, query, args)
}

func doDatesTableQueryAndScan(tbl DatesTabler, req require.Requirement, firstOnly bool, query string, args ...interface{}) ([]*Dates, error) {
	rows, err := support.Query(tbl, query, args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	vv, n, err := ScanManyDates(query, rows, firstOnly)
	return vv, tbl.Logger().LogIfError(tbl.Ctx(), require.ChainErrorIfQueryNotSatisfiedBy(err, req, n))
}

//-------------------------------------------------------------------------------------------------

// QueryOneNullString is a low-level access method for one string. This can be used for function queries and
// such like. If the query selected many rows, only the first is returned; the rest are discarded.
// If not found, the result will be invalid.
//
// Note that this applies ReplaceTableName to the query string.
//
// The args are for any placeholder parameters in the query.
func (tbl DatesTable) QueryOneNullString(req require.Requirement, query string, args ...interface{}) (result sql.NullString, err error) {
	err = support.QueryOneNullThing(tbl, req, &result, query, args...)
	return result, err
}

// QueryOneNullInt64 is a low-level access method for one int64. This can be used for 'COUNT(1)' queries and
// such like. If the query selected many rows, only the first is returned; the rest are discarded.
// If not found, the result will be invalid.
//
// Note that this applies ReplaceTableName to the query string.
//
// The args are for any placeholder parameters in the query.
func (tbl DatesTable) QueryOneNullInt64(req require.Requirement, query string, args ...interface{}) (result sql.NullInt64, err error) {
	err = support.QueryOneNullThing(tbl, req, &result, query, args...)
	return result, err
}

// QueryOneNullFloat64 is a low-level access method for one float64. This can be used for 'AVG(...)' queries and
// such like. If the query selected many rows, only the first is returned; the rest are discarded.
// If not found, the result will be invalid.
//
// Note that this applies ReplaceTableName to the query string.
//
// The args are for any placeholder parameters in the query.
func (tbl DatesTable) QueryOneNullFloat64(req require.Requirement, query string, args ...interface{}) (result sql.NullFloat64, err error) {
	err = support.QueryOneNullThing(tbl, req, &result, query, args...)
	return result, err
}

// ScanManyDates reads rows from the database and returns a slice of corresponding values.
// It also returns a number indicating how many rows were read; this will be larger than the length of the
// slice if reading stopped after the first row.
func ScanManyDates(query string, rows sqlapi.SqlRows, firstOnly bool) (vv []*Dates, n int64, err error) {
	for rows.Next() {
		n++

		var v0 uint64
		var v1 date.Date
		var v2 date.DateString

		err = rows.Scan(
			&v0,
			&v1,
			&v2,
		)
		if err != nil {
			return vv, n, errors.Wrap(err, query)
		}

		v := &Dates{}
		v.Id = v0
		v.Integer = v1
		v.String = v2

		var iv interface{} = v
		if hook, ok := iv.(sqlapi.CanPostGet); ok {
			err = hook.PostGet()
			if err != nil {
				return vv, n, errors.Wrap(err, query)
			}
		}

		vv = append(vv, v)

		if firstOnly {
			if rows.Next() {
				n++
			}
			return vv, n, errors.Wrap(rows.Err(), query)
		}
	}

	return vv, n, errors.Wrap(rows.Err(), query)
}

//--------------------------------------------------------------------------------

func allDatesColumnNamesQuoted(q quote.Quoter) string {
	return strings.Join(q.QuoteN(listOfDatesTableColumnNames), ",")
}

//--------------------------------------------------------------------------------

// GetDatesById gets the record with a given primary key value.
// If not found, *Dates will be nil.
func (tbl DatesTable) GetDatesById(req require.Requirement, id uint64) (*Dates, error) {
	return tbl.SelectOne(req, where.Eq("id", id), nil)
}

// GetManyDatesById gets records from the table according to a list of primary keys.
// Although the list of ids can be arbitrarily long, there are practical limits;
// note that Oracle DB has a limit of 1000.
//
// It places a requirement, which may be nil, on the size of the expected results: in particular, require.All
// controls whether an error is generated not all the ids produce a result.
func (tbl DatesTable) GetManyDatesById(req require.Requirement, qc where.QueryConstraint, id ...uint64) (list []*Dates, err error) {
	if req == require.All {
		req = require.Exactly(len(id))
	}
	return tbl.Select(req, where.InSlice("id", id), qc)
}

func doDatesTableQueryAndScanOne(tbl DatesTabler, req require.Requirement, query string, args ...interface{}) (*Dates, error) {
	list, err := doDatesTableQueryAndScan(tbl, req, true, query, args...)
	if err != nil || len(list) == 0 {
		return nil, err
	}
	return list[0], nil
}

// Fetch fetches a list of Dates based on a supplied query. This is mostly used for join queries that map its
// result columns to the fields of Dates. Other queries might be better handled by GetXxx or Select methods.
func (tbl DatesTable) Fetch(req require.Requirement, query string, args ...interface{}) ([]*Dates, error) {
	return doDatesTableQueryAndScan(tbl, req, false, query, args...)
}

//-------------------------------------------------------------------------------------------------

// SelectOneWhere allows a single Dates to be obtained from the table that matches a 'where' clause
// and some limit. Any order, limit or offset clauses can be supplied in 'orderBy'.
// Use blank strings for the 'where' and/or 'orderBy' arguments if they are not needed.
// If not found, *Example will be nil.
//
// It places a requirement, which may be nil, on the size of the expected results: for example require.One
// controls whether an error is generated when no result is found.
//
// The args are for any placeholder parameters in the query.
func (tbl DatesTable) SelectOneWhere(req require.Requirement, where, orderBy string, args ...interface{}) (*Dates, error) {
	quotedName := tbl.Dialect().Quoter().Quote(tbl.Name().String())
	query := fmt.Sprintf("SELECT %s FROM %s %s %s LIMIT 1",
		allDatesColumnNamesQuoted(tbl.Dialect().Quoter()), quotedName, where, orderBy)
	v, err := doDatesTableQueryAndScanOne(tbl, req, query, args...)
	return v, err
}

// SelectOne allows a single Dates to be obtained from the table that matches a 'where' clause.
// Any order, limit or offset clauses can be supplied in query constraint 'qc'.
// Use nil values for the 'wh' and/or 'qc' arguments if they are not needed.
// If not found, *Example will be nil.
//
// It places a requirement, which may be nil, on the size of the expected results: for example require.One
// controls whether an error is generated when no result is found.
func (tbl DatesTable) SelectOne(req require.Requirement, wh where.Expression, qc where.QueryConstraint) (*Dates, error) {
	d := tbl.Dialect()
	whs, args := where.Where(wh, d.Quoter())
	orderBy := where.Build(qc, d.Index())
	return tbl.SelectOneWhere(req, whs, orderBy, args...)
}

// SelectWhere allows ManyDates to be obtained from the table that match a 'where' clause.
// Any order, limit or offset clauses can be supplied in 'orderBy'.
// Use blank strings for the 'where' and/or 'orderBy' arguments if they are not needed.
//
// It places a requirement, which may be nil, on the size of the expected results: for example require.AtLeastOne
// controls whether an error is generated when no result is found.
//
// The args are for any placeholder parameters in the query.
func (tbl DatesTable) SelectWhere(req require.Requirement, where, orderBy string, args ...interface{}) ([]*Dates, error) {
	quotedName := tbl.Dialect().Quoter().Quote(tbl.Name().String())
	query := fmt.Sprintf("SELECT %s FROM %s %s %s",
		allDatesColumnNamesQuoted(tbl.Dialect().Quoter()), quotedName, where, orderBy)
	vv, err := doDatesTableQueryAndScan(tbl, req, false, query, args...)
	return vv, err
}

// Select allows ManyDates to be obtained from the table that match a 'where' clause.
// Any order, limit or offset clauses can be supplied in query constraint 'qc'.
// Use nil values for the 'wh' and/or 'qc' arguments if they are not needed.
//
// It places a requirement, which may be nil, on the size of the expected results: for example require.AtLeastOne
// controls whether an error is generated when no result is found.
func (tbl DatesTable) Select(req require.Requirement, wh where.Expression, qc where.QueryConstraint) ([]*Dates, error) {
	d := tbl.Dialect()
	whs, args := where.Where(wh, d.Quoter())
	orderBy := where.Build(qc, d.Index())
	return tbl.SelectWhere(req, whs, orderBy, args...)
}

//-------------------------------------------------------------------------------------------------

// CountWhere counts ManyDates in the table that match a 'where' clause.
// Use a blank string for the 'where' argument if it is not needed.
//
// The args are for any placeholder parameters in the query.
func (tbl DatesTable) CountWhere(where string, args ...interface{}) (count int64, err error) {
	quotedName := tbl.Dialect().Quoter().Quote(tbl.Name().String())
	query := fmt.Sprintf("SELECT COUNT(1) FROM %s %s", quotedName, where)
	rows, err := support.Query(tbl, query, args...)
	if err != nil {
		return 0, err
	}
	defer rows.Close()
	if rows.Next() {
		err = rows.Scan(&count)
	}
	return count, tbl.Logger().LogIfError(tbl.Ctx(), err)
}

// Count counts the ManyDates in the table that match a 'where' clause.
// Use a nil value for the 'wh' argument if it is not needed.
func (tbl DatesTable) Count(wh where.Expression) (count int64, err error) {
	whs, args := where.Where(wh, tbl.Dialect().Quoter())
	return tbl.CountWhere(whs, args...)
}

//--------------------------------------------------------------------------------

// SliceID gets the id column for all rows that match the 'where' condition.
// Any order, limit or offset clauses can be supplied in query constraint 'qc'.
// Use nil values for the 'wh' and/or 'qc' arguments if they are not needed.
func (tbl DatesTable) SliceID(req require.Requirement, wh where.Expression, qc where.QueryConstraint) ([]uint64, error) {
	return support.SliceUint64List(tbl, req, tbl.pk, wh, qc)
}

// SliceInteger gets the integer column for all rows that match the 'where' condition.
// Any order, limit or offset clauses can be supplied in query constraint 'qc'.
// Use nil values for the 'wh' and/or 'qc' arguments if they are not needed.
func (tbl DatesTable) SliceInteger(req require.Requirement, wh where.Expression, qc where.QueryConstraint) ([]date.Date, error) {
	return sliceDatesTableDateList(tbl, req, "integer", wh, qc)
}

// SliceString gets the string column for all rows that match the 'where' condition.
// Any order, limit or offset clauses can be supplied in query constraint 'qc'.
// Use nil values for the 'wh' and/or 'qc' arguments if they are not needed.
func (tbl DatesTable) SliceString(req require.Requirement, wh where.Expression, qc where.QueryConstraint) ([]date.DateString, error) {
	return sliceDatesTableDateStringList(tbl, req, "string", wh, qc)
}

func sliceDatesTableDateList(tbl DatesTabler, req require.Requirement, sqlname string, wh where.Expression, qc where.QueryConstraint) ([]date.Date, error) {
	d := tbl.Dialect()
	whs, args := where.Where(wh, d.Quoter())
	orderBy := where.Build(qc, d.Index())
	quotedName := tbl.Dialect().Quoter().Quote(tbl.Name().String())
	query := fmt.Sprintf("SELECT %s FROM %s %s %s", d.Quoter().Quote(sqlname), quotedName, whs, orderBy)
	rows, err := support.Query(tbl, query, args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	list := make([]date.Date, 0, 10)

	for rows.Next() {
		var v date.Date
		err = rows.Scan(&v)
		if err == sql.ErrNoRows {
			return list, tbl.Logger().LogIfError(tbl.Ctx(), require.ErrorIfQueryNotSatisfiedBy(req, int64(len(list))))
		} else {
			list = append(list, v)
		}
	}
	return list, tbl.Logger().LogIfError(tbl.Ctx(), require.ChainErrorIfQueryNotSatisfiedBy(rows.Err(), req, int64(len(list))))
}

func sliceDatesTableDateStringList(tbl DatesTabler, req require.Requirement, sqlname string, wh where.Expression, qc where.QueryConstraint) ([]date.DateString, error) {
	d := tbl.Dialect()
	whs, args := where.Where(wh, d.Quoter())
	orderBy := where.Build(qc, d.Index())
	quotedName := tbl.Dialect().Quoter().Quote(tbl.Name().String())
	query := fmt.Sprintf("SELECT %s FROM %s %s %s", d.Quoter().Quote(sqlname), quotedName, whs, orderBy)
	rows, err := support.Query(tbl, query, args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	list := make([]date.DateString, 0, 10)

	for rows.Next() {
		var v date.DateString
		err = rows.Scan(&v)
		if err == sql.ErrNoRows {
			return list, tbl.Logger().LogIfError(tbl.Ctx(), require.ErrorIfQueryNotSatisfiedBy(req, int64(len(list))))
		} else {
			list = append(list, v)
		}
	}
	return list, tbl.Logger().LogIfError(tbl.Ctx(), require.ChainErrorIfQueryNotSatisfiedBy(rows.Err(), req, int64(len(list))))
}

func constructDatesTableInsert(tbl DatesTable, w io.StringWriter, v *Dates, withPk bool) (s []interface{}, err error) {
	q := tbl.Dialect().Quoter()
	s = make([]interface{}, 0, 3)

	comma := ""
	w.WriteString(" (")

	if withPk {
		q.QuoteW(w, "id")
		comma = ","
		s = append(s, v.Id)
	}

	w.WriteString(comma)
	q.QuoteW(w, "integer")
	s = append(s, v.Integer)
	comma = ","

	w.WriteString(comma)
	q.QuoteW(w, "string")
	s = append(s, v.String)

	w.WriteString(")")
	return s, nil
}

func constructDatesTableUpdate(tbl DatesTable, w io.StringWriter, v *Dates) (s []interface{}, err error) {
	q := tbl.Dialect().Quoter()
	j := 1
	s = make([]interface{}, 0, 2)

	comma := ""

	w.WriteString(comma)
	q.QuoteW(w, "integer")
	w.WriteString("=?")
	s = append(s, v.Integer)
	j++
	comma = ", "

	w.WriteString(comma)
	q.QuoteW(w, "string")
	w.WriteString("=?")
	s = append(s, v.String)
	j++
	return s, nil
}

//--------------------------------------------------------------------------------

// Insert adds new records for the ManyDates.// The ManyDates have their primary key fields set to the new record identifiers.
// The Dates.PreInsert() method will be called, if it exists.
func (tbl DatesTable) Insert(req require.Requirement, vv ...*Dates) error {
	if req == require.All {
		req = require.Exactly(len(vv))
	}

	var count int64
	returning := ""
	insertHasReturningPhrase := tbl.Dialect().InsertHasReturningPhrase()
	if insertHasReturningPhrase {
		returning = fmt.Sprintf(" RETURNING %q", tbl.pk)
	}

	for _, v := range vv {
		var iv interface{} = v
		if hook, ok := iv.(sqlapi.CanPreInsert); ok {
			err := hook.PreInsert()
			if err != nil {
				return tbl.Logger().LogError(tbl.Ctx(), err)
			}
		}

		b := driver.Adapt(&bytes.Buffer{})
		b.WriteString("INSERT INTO ")
		tbl.quotedNameW(b)

		fields, err := constructDatesTableInsert(tbl, b, v, false)
		if err != nil {
			return tbl.Logger().LogError(tbl.Ctx(), err)
		}

		b.WriteString(" VALUES (")
		b.WriteString(tbl.Dialect().Placeholders(len(fields)))
		b.WriteString(")")
		b.WriteString(returning)

		query := b.String()
		tbl.Logger().LogQuery(tbl.Ctx(), query, fields...)

		var n int64 = 1
		if insertHasReturningPhrase {
			row := tbl.Execer().QueryRow(tbl.ctx, query, fields...)
			var i64 int64
			err = row.Scan(&i64)
			v.Id = uint64(i64)

		} else {
			i64, e2 := tbl.Execer().Insert(tbl.ctx, tbl.pk, query, fields...)
			if e2 != nil {
				return tbl.Logger().LogError(tbl.Ctx(), e2)
			}
			v.Id = uint64(i64)
		}

		if err != nil {
			return tbl.Logger().LogError(tbl.Ctx(), err)
		}
		count += n
	}

	return tbl.Logger().LogIfError(tbl.Ctx(), require.ErrorIfExecNotSatisfiedBy(req, count))
}

// UpdateByID updates one or more columns, given a id value.
func (tbl DatesTable) UpdateByID(req require.Requirement, id uint64, fields ...sql.NamedArg) (int64, error) {
	return tbl.UpdateFields(req, where.Eq("id", id), fields...)
}

// UpdateByInteger updates one or more columns, given a integer value.
func (tbl DatesTable) UpdateByInteger(req require.Requirement, integer date.Date, fields ...sql.NamedArg) (int64, error) {
	return tbl.UpdateFields(req, where.Eq("integer", integer), fields...)
}

// UpdateByString updates one or more columns, given a string value.
func (tbl DatesTable) UpdateByString(req require.Requirement, string date.DateString, fields ...sql.NamedArg) (int64, error) {
	return tbl.UpdateFields(req, where.Eq("string", string), fields...)
}

// UpdateFields updates one or more columns, given a 'where' clause.
// Use a nil value for the 'wh' argument if it is not needed (but note that this is risky!).
func (tbl DatesTable) UpdateFields(req require.Requirement, wh where.Expression, fields ...sql.NamedArg) (int64, error) {
	return support.UpdateFields(tbl, req, wh, fields...)
}

//--------------------------------------------------------------------------------

// Update updates records, matching them by primary key. It returns the number of rows affected.
// The Dates.PreUpdate(Execer) method will be called, if it exists.
func (tbl DatesTable) Update(req require.Requirement, vv ...*Dates) (int64, error) {
	if req == require.All {
		req = require.Exactly(len(vv))
	}

	var count int64
	d := tbl.Dialect()
	q := d.Quoter()

	for _, v := range vv {
		var iv interface{} = v
		if hook, ok := iv.(sqlapi.CanPreUpdate); ok {
			err := hook.PreUpdate()
			if err != nil {
				return count, tbl.Logger().LogError(tbl.Ctx(), err)
			}
		}

		b := driver.Adapt(&bytes.Buffer{})
		b.WriteString("UPDATE ")
		tbl.quotedNameW(b)
		b.WriteString(" SET ")

		args, err := constructDatesTableUpdate(tbl, b, v)
		if err != nil {
			return count, err
		}
		args = append(args, v.Id)

		b.WriteString(" WHERE ")
		q.QuoteW(b, tbl.pk)
		b.WriteString("=?")

		query := b.String()
		n, err := tbl.Exec(nil, query, args...)
		if err != nil {
			return count, err
		}
		count += n
	}

	return count, tbl.Logger().LogIfError(tbl.Ctx(), require.ErrorIfExecNotSatisfiedBy(req, count))
}

//--------------------------------------------------------------------------------

// Upsert inserts or updates a record, matching it using the expression supplied.
// This expression is used to search for an existing record based on some specified
// key column(s). It must match either zero or one existing record. If it matches
// none, a new record is inserted; otherwise the matching record is updated. An
// error results if these conditions are not met.
func (tbl DatesTable) Upsert(v *Dates, wh where.Expression) error {
	col := tbl.Dialect().Quoter().Quote(tbl.pk)
	qName := tbl.quotedName()
	whs, args := where.Where(wh, tbl.Dialect().Quoter())

	query := fmt.Sprintf("SELECT %s FROM %s %s", col, qName, whs)
	rows, err := support.Query(tbl, query, args...)
	if err != nil {
		return err
	}
	defer rows.Close()

	if !rows.Next() {
		return tbl.Insert(require.One, v)
	}

	var id uint64
	err = rows.Scan(&id)
	if err != nil {
		return tbl.Logger().LogIfError(tbl.Ctx(), err)
	}

	if rows.Next() {
		return require.ErrWrongSize(2, "expected to find no more than 1 but got at least 2 using %q", wh)
	}

	v.Id = id
	_, err = tbl.Update(require.One, v)
	return err
}

//-------------------------------------------------------------------------------------------------

// DeleteByID deletes rows from the table, given some id values.
// The list of ids can be arbitrarily long.
func (tbl DatesTable) DeleteByID(req require.Requirement, id ...uint64) (int64, error) {
	ii := support.Uint64AsInterfaceSlice(id)
	return support.DeleteByColumn(tbl, req, "id", ii...)
}

// DeleteByInteger deletes rows from the table, given some integer values.
// The list of ids can be arbitrarily long.
func (tbl DatesTable) DeleteByInteger(req require.Requirement, integer ...date.Date) (int64, error) {
	ii := make([]interface{}, len(integer))
	for i, v := range integer {
		ii[i] = v
	}
	return support.DeleteByColumn(tbl, req, "integer", ii...)
}

// DeleteByString deletes rows from the table, given some string values.
// The list of ids can be arbitrarily long.
func (tbl DatesTable) DeleteByString(req require.Requirement, string ...date.DateString) (int64, error) {
	ii := make([]interface{}, len(string))
	for i, v := range string {
		ii[i] = v
	}
	return support.DeleteByColumn(tbl, req, "string", ii...)
}

// Delete deletes one or more rows from the table, given a 'where' clause.
// Use a nil value for the 'wh' argument if it is not needed (very risky!).
func (tbl DatesTable) Delete(req require.Requirement, wh where.Expression) (int64, error) {
	query, args := deleteRowsDatesTableSql(tbl, wh)
	return tbl.Exec(req, query, args...)
}

func deleteRowsDatesTableSql(tbl DatesTabler, wh where.Expression) (string, []interface{}) {
	whs, args := where.Where(wh, tbl.Dialect().Quoter())
	quotedName := tbl.Dialect().Quoter().Quote(tbl.Name().String())
	query := fmt.Sprintf("DELETE FROM %s %s", quotedName, whs)
	return query, args
}

//-------------------------------------------------------------------------------------------------


text:
#ifndef _K_PMM_H_
#define _K_PMM_H_

#include <stdbool.h>

#define PAGE_USED 0
#define PAGE_FREE 1

extern const int PAGE_SIZE;

/**
  * Setup the physical memory manager.
  */
bool pmm_init();

/**
  * Allocate a single physical memory page.
  * @param  pages  int  Number of pages
  * @return Start Address
  */
void* pmm_alloc(int pages);

/**
  * Deallocate physical memory page.
  * @param  address  void* Start Address
  * @param  pages    int   Number of pages
  */
void pmm_free(void* address, int pages);

#endif // _K_PMM_H_

redpajama_set_name: RedPajamaGithub


text:
TEST(WinUtils, IsReparsePoint) {
  using sandbox::IsReparsePoint;

  // Create a temp file because we need write access to it.
  wchar_t temp_directory[MAX_PATH];
  wchar_t my_folder[MAX_PATH];
  ASSERT_NE(::GetTempPath(MAX_PATH, temp_directory), 0u);
  ASSERT_NE(::GetTempFileName(temp_directory, L"test", 0, my_folder), 0u);

  // Delete the file and create a directory instead.
  ASSERT_TRUE(::DeleteFile(my_folder));
  ASSERT_TRUE(::CreateDirectory(my_folder, NULL));

  EXPECT_EQ(static_cast<DWORD>(ERROR_NOT_A_REPARSE_POINT),
            IsReparsePoint(my_folder));

  base::string16 not_found = base::string16(my_folder) + L"\\foo\\bar";
  EXPECT_EQ(static_cast<DWORD>(ERROR_NOT_A_REPARSE_POINT),
            IsReparsePoint(not_found));

  base::string16 new_file = base::string16(my_folder) + L"\\foo";
  EXPECT_EQ(static_cast<DWORD>(ERROR_NOT_A_REPARSE_POINT),
            IsReparsePoint(new_file));

  // Replace the directory with a reparse point to %temp%.
  HANDLE dir = ::CreateFile(my_folder, FILE_ALL_ACCESS,
                            FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
                            OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
  EXPECT_NE(INVALID_HANDLE_VALUE, dir);

  base::string16 temp_dir_nt = base::string16(L"\\??\\") + temp_directory;
  EXPECT_TRUE(SetReparsePoint(dir, temp_dir_nt.c_str()));

  EXPECT_EQ(static_cast<DWORD>(ERROR_SUCCESS), IsReparsePoint(new_file));

  EXPECT_TRUE(DeleteReparsePoint(dir));
  EXPECT_TRUE(::CloseHandle(dir));
  EXPECT_TRUE(::RemoveDirectory(my_folder));
}

TEST(WinUtils, SameObject) {
  using sandbox::SameObject;

  // Create a temp file because we need write access to it.
  wchar_t temp_directory[MAX_PATH];
  wchar_t my_folder[MAX_PATH];
  ASSERT_NE(::GetTempPath(MAX_PATH, temp_directory), 0u);
  ASSERT_NE(::GetTempFileName(temp_directory, L"test", 0, my_folder), 0u);

  // Delete the file and create a directory instead.
  ASSERT_TRUE(::DeleteFile(my_folder));
  ASSERT_TRUE(::CreateDirectory(my_folder, NULL));

  base::string16 folder(my_folder);
  base::string16 file_name = folder + L"\\foo.txt";
  const ULONG kSharing = FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE;
  base::win::ScopedHandle file(CreateFile(
      file_name.c_str(), GENERIC_WRITE, kSharing, NULL, CREATE_ALWAYS,
      FILE_FLAG_DELETE_ON_CLOSE, NULL));

  EXPECT_TRUE(file.IsValid());
  base::string16 file_name_nt1 = base::string16(L"\\??\\") + file_name;
  base::string16 file_name_nt2 =
      base::string16(L"\\??\\") + folder + L"\\FOO.txT";
  EXPECT_TRUE(SameObject(file.Get(), file_name_nt1.c_str()));
  EXPECT_TRUE(SameObject(file.Get(), file_name_nt2.c_str()));

  file.Close();
  EXPECT_TRUE(::RemoveDirectory(my_folder));
}

TEST(WinUtils, IsPipe) {
  using sandbox::IsPipe;

  base::string16 pipe_name = L"\\??\\pipe\\mypipe";
  EXPECT_TRUE(IsPipe(pipe_name));

  pipe_name = L"\\??\\PiPe\\mypipe";
  EXPECT_TRUE(IsPipe(pipe_name));

  pipe_name = L"\\??\\pipe";
  EXPECT_FALSE(IsPipe(pipe_name));

  pipe_name = L"\\??\\_pipe_\\mypipe";
  EXPECT_FALSE(IsPipe(pipe_name));

  pipe_name = L"\\??\\ABCD\\mypipe";
  EXPECT_FALSE(IsPipe(pipe_name));

  // Written as two strings to prevent trigraph '?' '?' '/'.
  pipe_name = L"/?" L"?/pipe/mypipe";
  EXPECT_FALSE(IsPipe(pipe_name));

  pipe_name = L"\\XX\\pipe\\mypipe";
  EXPECT_FALSE(IsPipe(pipe_name));

  pipe_name = L"\\Device\\NamedPipe\\mypipe";
  EXPECT_FALSE(IsPipe(pipe_name));
}

TEST(WinUtils, NtStatusToWin32Error) {
  using sandbox::GetLastErrorFromNtStatus;
  EXPECT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
            GetLastErrorFromNtStatus(STATUS_SUCCESS));
  EXPECT_EQ(static_cast<DWORD>(ERROR_NOT_SUPPORTED),
            GetLastErrorFromNtStatus(STATUS_NOT_SUPPORTED));
  EXPECT_EQ(static_cast<DWORD>(ERROR_ALREADY_EXISTS),
            GetLastErrorFromNtStatus(STATUS_OBJECT_NAME_COLLISION));
  EXPECT_EQ(static_cast<DWORD>(ERROR_ACCESS_DENIED),
            GetLastErrorFromNtStatus(STATUS_ACCESS_DENIED));
}


text:
class WXDLLEXPORT wxStaticBox : public wxStaticBoxBase
{
public:
    wxStaticBox() { }

    wxStaticBox(wxWindow *parent, wxWindowID id,
                const wxString& label,
                const wxPoint& pos = wxDefaultPosition,
                const wxSize& size = wxDefaultSize,
                long style = 0,
                const wxString& name = wxStaticBoxNameStr)
    {
        Create(parent, id, label, pos, size, style, name);
    }

    bool Create(wxWindow *parent, wxWindowID id,
                const wxString& label,
                const wxPoint& pos = wxDefaultPosition,
                const wxSize& size = wxDefaultSize,
                long style = 0,
                const wxString& name = wxStaticBoxNameStr);

    /// Implementation only
    virtual void GetBordersForSizer(int *borderTop, int *borderOther) const;

    virtual WXDWORD MSWGetStyle(long style, WXDWORD *exstyle) const;

protected:
    virtual wxSize DoGetBestSize() const;

    // choose the default border for this window
    virtual wxBorder GetDefaultBorder() const;

#ifndef __WXWINCE__
public:
    virtual WXLRESULT MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam);

protected:
    // return the region with all the windows inside this static box excluded
    virtual WXHRGN MSWGetRegionWithoutChildren();

    // remove the parts which are painted by static box itself from the given
    // region which is embedded in a rectangle (0, 0)-(w, h)
    virtual void MSWGetRegionWithoutSelf(WXHRGN hrgn, int w, int h);

    // paint the given rectangle with our background brush/colour
    virtual void PaintBackground(wxDC& dc, const struct tagRECT& rc);
    // paint the foreground of the static box
    virtual void PaintForeground(wxDC& dc, const struct tagRECT& rc);

    void OnPaint(wxPaintEvent& event);
#endif // !__WXWINCE__

    DECLARE_DYNAMIC_CLASS_NO_COPY(wxStaticBox)
};

#endif // _WX_MSW_STATBOX_H_


text:
import React,  { Component } from 'react';
import { connect } from 'react-redux';

class Select extends Component {
    constructor (props){
        super(props);

        this.state = {
            selection: null
        };

        this.handelChange = this.handelChange.bind(this);
    }

    handelChange = (evt) => {
        const teamID = evt.target.value;

        this.props.onChange(teamID);
    }

    render() {
        const { basketballTeams } = this.props;

        const options = basketballTeams.map(team => {
            return (
                <option value={team.teamid} key={team.teamid}>{team.team_name}</option>
            )
        });

        return (

                    <form>

                                Select School
                                <select className="custom-select mr-sm-2" id="inlineFormCustomSelect" onChange={this.handelChange}>
                                    {options}
                                </select>

                    </form>

        )
    }
};

const mapStateToProps = (state) => {
    return {
        basketballTeams: state.basketballTeams
    }
}

export default connect(mapStateToProps)(Select);


text:
package com.github.mjeanroy.junit.servers.samples.utils.tomcat;

import org.apache.juli.logging.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * An implementation of Java Util Logging for Tomcat, delegating all call to
 * a slf4j logger.
 *
 * <br>
 *
 * Note that this class will automatically be loaded by tomcat using the Service Provider
 * Interface.
 */
public class TomcatLogger implements Log {

	/**
	 * The internal SLF4J Logger.
	 */
	private final Logger logger;

	// this constructor is important, otherwise the ServiceLoader cannot start
	public TomcatLogger() {
		logger = LoggerFactory.getLogger(TomcatLogger.class);
	}

	// this constructor is needed by the LogFactory implementation
	public TomcatLogger(String name) {
		logger = LoggerFactory.getLogger(name);
	}

	@Override
	public boolean isDebugEnabled() {
		return logger.isDebugEnabled();
	}

	@Override
	public boolean isErrorEnabled() {
		return logger.isErrorEnabled();
	}

	@Override
	public boolean isFatalEnabled() {
		return logger.isErrorEnabled();
	}

	@Override
	public boolean isInfoEnabled() {
		return logger.isInfoEnabled();
	}

	@Override
	public boolean isTraceEnabled() {
		return logger.isTraceEnabled();
	}

	@Override
	public boolean isWarnEnabled() {
		return logger.isWarnEnabled();
	}

	@Override
	public void trace(Object message) {
		logger.trace(Objects.toString(message));
	}

	@Override
	public void trace(Object message, Throwable t) {
		logger.trace(Objects.toString(message), t);
	}

	@Override
	public void debug(Object message) {
		logger.debug(Objects.toString(message));
	}

	@Override
	public void debug(Object message, Throwable t) {
		logger.debug(Objects.toString(message), t);
	}

	@Override
	public void info(Object message) {
		logger.info(Objects.toString(message));
	}

	@Override
	public void info(Object message, Throwable t) {
		logger.info(Objects.toString(message), t);
	}

	@Override
	public void warn(Object message) {
		logger.warn(Objects.toString(message));
	}

	@Override
	public void warn(Object message, Throwable t) {
		logger.warn(Objects.toString(message), t);
	}

	@Override
	public void error(Object message) {
		logger.error(Objects.toString(message));
	}

	@Override
	public void error(Object message, Throwable t) {
		logger.error(Objects.toString(message), t);
	}

	@Override
	public void fatal(Object message) {
		logger.error(Objects.toString(message));
	}

	@Override
	public void fatal(Object message, Throwable t) {
		logger.error(Objects.toString(message), t);
	}
}


text:
<template name="footer">

					Made By Nate Strauser
					 -
					  Fork me on GitHub

					 RSS Jobs Developers
					 -
					 JSON Jobs Developers

				We Work Meteor is an independent entity and has not been authorized, sponsored, or otherwise approved by Meteor Development Group.

</template>


text:
"""
Unit tests for the EvMenu system

This sets up a testing parent for testing EvMenu trees. It is configured by subclassing the
`TestEvMenu` class from this module and setting the class variables to point to the menu that should
be tested and how it should be called.

Without adding any further test methods, the tester will process all nodes of the menu, depth first,
by stepping through all options for every node. Optionally, it can check that all nodes are visited.
It will create a hierarchical list of node names that describes the tree structure. This can then be
compared against a template to make sure the menu structure is sound. Easiest way to use this is to
run the test once to see how the structure looks.

The system also allows for testing the returns of each node as part of the parsing.

To help debug the menu, turn on `debug_output`, which will print the traversal process in detail.

"""

import copy
from anything import Anything
from django.test import TestCase
from evennia.utils.test_resources import EvenniaTest
from evennia.utils import evmenu
from evennia.utils import ansi
from mock import MagicMock

class TestEvMenu(TestCase):
    "Run the EvMenu testing."
    menutree = {}  # can also be the path to the menu tree
    startnode = "start"
    cmdset_mergetype = "Replace"
    cmdset_priority = 1
    auto_quit = True
    auto_look = True
    auto_help = True
    cmd_on_exit = "look"
    persistent = False
    startnode_input = ""
    kwargs = {}

    # if all nodes must be visited for the test to pass. This is not on
    # by default since there may be exec-nodes that are made to not be
    # visited.
    expect_all_nodes = False

    # this is compared against the full tree structure generated
    expected_tree = []
    # this allows for verifying that a given node returns a given text. The
    # text is compared with .startswith, so the entire text need not be matched.
    expected_node_texts = {}
    # just check the number of options from each node
    expected_node_options_count = {}
    # check the actual options
    expected_node_options = {}

    # set this to print the traversal as it happens (debugging)
    debug_output = False

    def _debug_output(self, indent, msg):
        if self.debug_output:
            print(" " * indent + ansi.strip_ansi(msg))

    def _test_menutree(self, menu):
        """
        This is a automatic tester of the menu tree by recursively progressing through the
        structure.
        """

        def _depth_first(menu, tree, visited, indent):

            # we are in a given node here
            nodename = menu.nodename
            options = menu.test_options
            if isinstance(options, dict):
                options = (options,)

            # run validation tests for this node
            compare_text = self.expected_node_texts.get(nodename, None)
            if compare_text is not None:
                compare_text = ansi.strip_ansi(compare_text.strip())
                node_text = menu.test_nodetext
                self.assertIsNotNone(
                    bool(node_text),
                    "node: {}: node-text is None, which was not expected.".format(nodename),
                )
                if isinstance(node_text, tuple):
                    node_text, helptext = node_text
                node_text = ansi.strip_ansi(node_text.strip())
                self.assertTrue(
                    node_text.startswith(compare_text),
                    "\nnode \"{}':\nOutput:\n{}\n\nExpected (startswith):\n{}".format(
                        nodename, node_text, compare_text
                    ),
                )
            compare_options_count = self.expected_node_options_count.get(nodename, None)
            if compare_options_count is not None:
                self.assertEqual(
                    len(options),
                    compare_options_count,
                    "Not the right number of options returned from node {}.".format(nodename),
                )
            compare_options = self.expected_node_options.get(nodename, None)
            if compare_options:
                self.assertEqual(
                    options,
                    compare_options,
                    "Options returned from node {} does not match.".format(nodename),
                )

            self._debug_output(indent, "*{}".format(nodename))
            subtree = []

            if not options:
                # an end node
                if nodename not in visited:
                    visited.append(nodename)
                subtree = nodename
            else:
                for inum, optdict in enumerate(options):

                    key, desc, execute, goto = (
                        optdict.get("key", ""),
                        optdict.get("desc", None),
                        optdict.get("exec", None),
                        optdict.get("goto", None),
                    )

                    # prepare the key to pass to the menu
                    if isinstance(key, (tuple, list)) and len(key) > 1:
                        key = key[0]
                    if key == "_default":
                        key = "test raw input"
                    if not key:
                        key = str(inum + 1)

                    backup_menu = copy.copy(menu)

                    # step the menu
                    menu.parse_input(key)

                    # from here on we are likely in a different node
                    nodename = menu.nodename

                    if menu.close_menu.called:
                        # this was an end node
                        self._debug_output(indent, "    .. menu exited! Back to previous node.")
                        menu = backup_menu
                        menu.close_menu = MagicMock()
                        visited.append(nodename)
                        subtree.append(nodename)
                    elif nodename not in visited:
                        visited.append(nodename)
                        subtree.append(nodename)
                        _depth_first(menu, subtree, visited, indent + 2)
                        # self._debug_output(indent, "    -> arrived at {}".format(nodename))
                    else:
                        subtree.append(nodename)
                        # self._debug_output( indent, "    -> arrived at {} (circular call)".format(nodename))
                    self._debug_output(indent, "-- {} ({}) -> {}".format(key, desc, goto))

            if subtree:
                tree.append(subtree)

        # the start node has already fired at this point
        visited_nodes = [menu.nodename]
        traversal_tree = [menu.nodename]
        _depth_first(menu, traversal_tree, visited_nodes, 1)

        if self.expect_all_nodes:
            self.assertGreaterEqual(len(menu._menutree), len(visited_nodes))
        self.assertEqual(traversal_tree, self.expected_tree)

    def setUp(self):
        self.menu = None
        if self.menutree:
            self.caller = MagicMock()
            self.caller.key = "Test"
            self.caller2 = MagicMock()
            self.caller2.key = "Test"
            self.caller.msg = MagicMock()
            self.caller2.msg = MagicMock()
            self.session = MagicMock()
            self.session.protocol_flags = {}
            self.session2 = MagicMock()
            self.session2.protocol_flags = {}
            self.caller.session = self.session
            self.caller2.session = self.session2

            self.menu = evmenu.EvMenu(
                self.caller,
                self.menutree,
                startnode=self.startnode,
                cmdset_mergetype=self.cmdset_mergetype,
                cmdset_priority=self.cmdset_priority,
                auto_quit=self.auto_quit,
                auto_look=self.auto_look,
                auto_help=self.auto_help,
                cmd_on_exit=self.cmd_on_exit,
                persistent=False,
                startnode_input=self.startnode_input,
                session=self.session,
                **self.kwargs,
            )
            # persistent version
            self.pmenu = evmenu.EvMenu(
                self.caller2,
                self.menutree,
                startnode=self.startnode,
                cmdset_mergetype=self.cmdset_mergetype,
                cmdset_priority=self.cmdset_priority,
                auto_quit=self.auto_quit,
                auto_look=self.auto_look,
                auto_help=self.auto_help,
                cmd_on_exit=self.cmd_on_exit,
                persistent=True,
                startnode_input=self.startnode_input,
                session=self.session2,
                **self.kwargs,
            )

            self.menu.close_menu = MagicMock()
            self.pmenu.close_menu = MagicMock()

    def test_menu_structure(self):
        if self.menu:
            self._test_menutree(self.menu)
            self._test_menutree(self.pmenu)

class TestEvMenuExample(TestEvMenu):

    menutree = "evennia.utils.tests.data.evmenu_example"
    startnode = "test_start_node"
    kwargs = {"testval": "val", "testval2": "val2"}
    debug_output = False

    expected_node_texts = {"test_view_node": "Your name is"}

    expected_tree = [
        "test_start_node",
        [
            "test_set_node",
            ["test_start_node"],
            "test_look_node",
            ["test_start_node"],
            "test_view_node",
            ["test_start_node"],
            "test_dynamic_node",
            [
                "test_dynamic_node",
                "test_dynamic_node",
                "test_dynamic_node",
                "test_dynamic_node",
                "test_start_node",
            ],
            "test_end_node",
            "test_displayinput_node",
            ["test_start_node"],
        ],
    ]

    def test_kwargsave(self):
        self.assertTrue(hasattr(self.menu, "testval"))
        self.assertTrue(hasattr(self.menu, "testval2"))

def _callnode1(caller, raw_string, **kwargs):
    return "node1"

def _callnode2(caller, raw_string, **kwargs):
    return "node2"

class TestMenuTemplateParse(EvenniaTest):
    """Test menu templating helpers"""

    def setUp(self):
        super().setUp()

        self.menu_template = """
        ## node start

        Neque ea alias perferendis molestiae eligendi. Debitis exercitationem
        exercitationem quas blanditiis quisquam officia ut. Fugit aut fugit enim quia
        non. Earum et excepturi animi ex esse accusantium et. Id adipisci eos enim
        ratione.

        ## options

        1: first option -> node1
        2: second option -> node2
        next: node1

        ## node node1

        Node 1

        ## options

        fwd: node2
        call1: callnode1()
        call2: callnode2(foo=bar, bar=22, goo="another test")
        >: start

        ## node node2

        Text of node 2

        ## options

        > foo*: node1
        > [0-9]+?: node2
        > back: start

        """
        self.goto_callables = {"callnode1": _callnode1, "callnode2": _callnode2}

    def test_parse_menu_template(self):
        """EvMenu template testing"""

        menutree = evmenu.parse_menu_template(self.char1, self.menu_template, self.goto_callables)
        self.assertEqual(menutree, {"start": Anything, "node1": Anything, "node2": Anything})

    def test_template2menu(self):
        evmenu.template2menu(self.char1, self.menu_template, self.goto_callables)

    def test_parse_menu_fail(self):
        template = """
        ## NODE

        Text

        ## OPTIONS

        next: callnode2(invalid)
        """
        with self.assertRaises(RuntimeError):
            evmenu.parse_menu_template(self.char1, template, self.goto_callables)


text:
class LuckyComponent {
protected:
   SDL_Rect bounds;
public:
   SDL_Rect* parent_bounds;

   LuckyComponent(int x, int y, int w = 0, int h = 0)
      : bounds{x, y, w, h} { }

   virtual void update() = 0;
   virtual void draw() = 0;
};

class LuckyWindow;

class LuckyPane : public LuckyComponent {
public:
   SDL_Texture* pane_tex;
   LuckyWindow* parent;
   std::vector<LuckyComponent*> components;

   LuckyPane(LuckyWindow* p);

   void addComponent(LuckyComponent* component);

   void update();
   void draw();
};

class LuckyWindow {
private:
   SDL_Rect shadow;
   SDL_Rect frame;
   SDL_Rect handle;

   bool locked = false;
   int grabbedx, grabbedy;

   SDL_Texture* shadow_tex;
   SDL_Texture* frame_tex;

public:
   const char* title;
   SDL_Rect window;

   LuckyPane* pane;

   LuckyWindow(const char* t, int x, int y, int w = 240, int h = 180);

   void updateWindow();
   bool trygrab();

   void update();
   void draw();
};

class LuckyText : public LuckyComponent {
public:
   const char* text;

   LuckyText(const char* t, int x, int y);

   void update();
   void draw();
};

class LuckyButton : public LuckyComponent {
private:
   bool hover, pressed;
   int padding;

   SDL_Texture* btex;
   SDL_Texture* btex_hover;
   SDL_Texture* btex_press;

public:
   const char* text;
   SDL_Rect actual;

   LuckyButton(const char* t, int x, int y);

   void (*onClick)(void*) = NULL;

   void update();
   void draw();
};


text:
<component name="libraryTable">
  <library name="opentelemetry" type="repository">
    <properties maven-id="io.opentelemetry:opentelemetry-sdk:1.17.0" />
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/io/opentelemetry/opentelemetry-sdk/1.17.0/opentelemetry-sdk-1.17.0.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/io/opentelemetry/opentelemetry-api/1.17.0/opentelemetry-api-1.17.0.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/io/opentelemetry/opentelemetry-context/1.17.0/opentelemetry-context-1.17.0.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/io/opentelemetry/opentelemetry-sdk-common/1.17.0/opentelemetry-sdk-common-1.17.0.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/io/opentelemetry/opentelemetry-semconv/1.17.0-alpha/opentelemetry-semconv-1.17.0-alpha.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/io/opentelemetry/opentelemetry-sdk-trace/1.17.0/opentelemetry-sdk-trace-1.17.0.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/io/opentelemetry/opentelemetry-sdk-metrics/1.17.0/opentelemetry-sdk-metrics-1.17.0.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/io/opentelemetry/opentelemetry-sdk-logs/1.17.0-alpha/opentelemetry-sdk-logs-1.17.0-alpha.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/io/opentelemetry/opentelemetry-sdk/1.17.0/opentelemetry-sdk-1.17.0-sources.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/io/opentelemetry/opentelemetry-api/1.17.0/opentelemetry-api-1.17.0-sources.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/io/opentelemetry/opentelemetry-context/1.17.0/opentelemetry-context-1.17.0-sources.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/io/opentelemetry/opentelemetry-sdk-common/1.17.0/opentelemetry-sdk-common-1.17.0-sources.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/io/opentelemetry/opentelemetry-semconv/1.17.0-alpha/opentelemetry-semconv-1.17.0-alpha-sources.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/io/opentelemetry/opentelemetry-sdk-trace/1.17.0/opentelemetry-sdk-trace-1.17.0-sources.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/io/opentelemetry/opentelemetry-sdk-metrics/1.17.0/opentelemetry-sdk-metrics-1.17.0-sources.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/io/opentelemetry/opentelemetry-sdk-logs/1.17.0-alpha/opentelemetry-sdk-logs-1.17.0-alpha-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;

namespace Flubu.VisualStudio.Base.TaskRunner
{
    public static class TextViewUtil
    {
        public static IVsTextView FindTextViewFor(string filePath)
        {
            IVsWindowFrame frame = FindWindowFrame(filePath);
            if (frame != null)
            {
                IVsTextView textView;

                if (GetTextViewFromFrame(frame, out textView))
                {
                    return textView;
                }
            }

            return null;
        }

        private static IEnumerable<IVsWindowFrame> EnumerateDocumentWindowFrames()
        {
            IVsUIShell shell = Package.GetGlobalService(typeof(SVsUIShell)) as IVsUIShell;

            if (shell != null)
            {
                IEnumWindowFrames framesEnum;

                int hr = shell.GetDocumentWindowEnum(out framesEnum);

                if (hr == VSConstants.S_OK && framesEnum != null)
                {
                    IVsWindowFrame[] frames = new IVsWindowFrame[1];
                    uint fetched;

                    while (framesEnum.Next(1, frames, out fetched) == VSConstants.S_OK && fetched == 1)
                    {
                        yield return frames[0];
                    }
                }
            }
        }

        private static IVsWindowFrame FindWindowFrame(string filePath)
        {
            foreach (IVsWindowFrame currentFrame in EnumerateDocumentWindowFrames())
            {
                if (IsFrameForFilePath(currentFrame, filePath))
                {
                    return currentFrame;
                }
            }

            return null;
        }

        private static bool GetPhysicalPathFromFrame(IVsWindowFrame frame, out string frameFilePath)
        {
            object propertyValue;

            int hr = frame.GetProperty((int)__VSFPROPID.VSFPROPID_pszMkDocument, out propertyValue);
            if (hr == VSConstants.S_OK && propertyValue != null)
            {
                frameFilePath = propertyValue.ToString();
                return true;
            }

            frameFilePath = null;
            return false;
        }

        private static bool GetTextViewFromFrame(IVsWindowFrame frame, out IVsTextView textView)
        {
            textView = VsShellUtilities.GetTextView(frame);

            return textView != null;
        }

        private static bool IsFrameForFilePath(IVsWindowFrame frame, string filePath)
        {
            string frameFilePath;

            if (GetPhysicalPathFromFrame(frame, out frameFilePath))
            {
                return String.Equals(filePath, frameFilePath, StringComparison.OrdinalIgnoreCase);
            }

            return false;
        }
    }
}


text:
var places = undefined;
var friends = undefined;
var seekplaces = undefined;

function initList() {
    var pl = document.getElementById("places_list");
    var fl = document.getElementById("friends_list");
    var spl = document.getElementById("seek_place_box");
    seekplaces = new List(spl);
    places = new List(pl);
    friends = new List(fl);
    addevent(places.listener, "listadd", new_place_list);
    addevent(places.listener, "listadd", new_place_map);
    addevent(places.listener, "listdel", old_place_list);
    addevent(places.listener, "listdel", old_place_map);
    addevent(friends.listener, "listadd", new_friend_list);
    addevent(friends.listener, "listdel", old_friend_list);
//    addevent(friends.listener, "listadd", new_friend_place_map);
//    addevent(friends.listener, "listdel", old_place_map);
    addevent(seekplaces.listener, "listadd", new_seek_place_list);
    addevent(seekplaces.listener, "listdel", old_seek_place_list);
}


text:
/* Generated by ./xlat/gen.sh from ./xlat/bpf_map_types.in; do not edit. */

static const struct xlat bpf_map_types[] = {
#if !(defined(BPF_MAP_TYPE_UNSPEC) || (defined(HAVE_DECL_BPF_MAP_TYPE_UNSPEC) && HAVE_DECL_BPF_MAP_TYPE_UNSPEC))
# define BPF_MAP_TYPE_UNSPEC 0
#endif
 XLAT(BPF_MAP_TYPE_UNSPEC),
#if !(defined(BPF_MAP_TYPE_HASH) || (defined(HAVE_DECL_BPF_MAP_TYPE_HASH) && HAVE_DECL_BPF_MAP_TYPE_HASH))
# define BPF_MAP_TYPE_HASH 1
#endif
 XLAT(BPF_MAP_TYPE_HASH),
#if !(defined(BPF_MAP_TYPE_ARRAY) || (defined(HAVE_DECL_BPF_MAP_TYPE_ARRAY) && HAVE_DECL_BPF_MAP_TYPE_ARRAY))
# define BPF_MAP_TYPE_ARRAY 2
#endif
 XLAT(BPF_MAP_TYPE_ARRAY),
#if !(defined(BPF_MAP_TYPE_PROG_ARRAY) || (defined(HAVE_DECL_BPF_MAP_TYPE_PROG_ARRAY) && HAVE_DECL_BPF_MAP_TYPE_PROG_ARRAY))
# define BPF_MAP_TYPE_PROG_ARRAY 3
#endif
 XLAT(BPF_MAP_TYPE_PROG_ARRAY),
 XLAT_END
};


text:
package db

import (
	"database/sql"
	"encoding/json"

	sq "github.com/Masterminds/squirrel"
	"github.com/concourse/concourse/atc"
	"go.opentelemetry.io/otel/propagation"
)

//counterfeiter:generate . ResourceConfigVersion
type ResourceConfigVersion interface {
	ID() int
	Version() Version
	Metadata() ResourceConfigMetadataFields
	CheckOrder() int
	SpanContext() propagation.TextMapCarrier

	Reload() (bool, error)
}

type ResourceConfigVersions []ResourceConfigVersion

type ResourceConfigMetadataField struct {
	Name  string
	Value string
}

type ResourceConfigMetadataFields []ResourceConfigMetadataField

func NewResourceConfigMetadataFields(atcm []atc.MetadataField) ResourceConfigMetadataFields {
	metadata := make([]ResourceConfigMetadataField, len(atcm))
	for i, md := range atcm {
		metadata[i] = ResourceConfigMetadataField{
			Name:  md.Name,
			Value: md.Value,
		}
	}

	return metadata
}

func (rmf ResourceConfigMetadataFields) ToATCMetadata() []atc.MetadataField {
	metadata := make([]atc.MetadataField, len(rmf))
	for i, md := range rmf {
		metadata[i] = atc.MetadataField{
			Name:  md.Name,
			Value: md.Value,
		}
	}

	return metadata
}

type Version map[string]string

type resourceConfigVersion struct {
	id          int
	version     Version
	metadata    ResourceConfigMetadataFields
	checkOrder  int
	spanContext SpanContext

	conn Conn
}

var resourceConfigVersionQuery = psql.Select(`
	v.id,
	v.version,
	v.metadata,
	v.check_order,
	v.span_context
`).
	From("resource_config_versions v")

func (r *resourceConfigVersion) ID() int                                { return r.id }
func (r *resourceConfigVersion) Version() Version                       { return r.version }
func (r *resourceConfigVersion) Metadata() ResourceConfigMetadataFields { return r.metadata }
func (r *resourceConfigVersion) CheckOrder() int                        { return r.checkOrder }
func (r *resourceConfigVersion) SpanContext() propagation.TextMapCarrier {
	return r.spanContext
}

func (r *resourceConfigVersion) Reload() (bool, error) {
	row := resourceConfigVersionQuery.Where(sq.Eq{"v.id": r.id}).
		RunWith(r.conn).
		QueryRow()

	err := scanResourceConfigVersion(r, row)
	if err != nil {
		if err == sql.ErrNoRows {
			return false, nil
		}
		return false, err
	}

	return true, nil
}

func scanResourceConfigVersion(r *resourceConfigVersion, scan scannable) error {
	var version, metadata, spanContext sql.NullString

	err := scan.Scan(&r.id, &version, &metadata, &r.checkOrder, &spanContext)
	if err != nil {
		return err
	}

	if version.Valid {
		err = json.Unmarshal([]byte(version.String), &r.version)
		if err != nil {
			return err
		}
	}

	if metadata.Valid {
		err = json.Unmarshal([]byte(metadata.String), &r.metadata)
		if err != nil {
			return err
		}
	}

	if spanContext.Valid {
		err = json.Unmarshal([]byte(spanContext.String), &r.spanContext)
		if err != nil {
			return err
		}
	}

	return nil
}


text:
package org.kuali.rice.core.api.util;

import com.google.common.io.ByteStreams;
import com.google.common.io.Closeables;
import org.springframework.core.DecoratingClassLoader;
import org.springframework.instrument.classloading.WeavingTransformer;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.lang.instrument.ClassFileTransformer;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * A class loader for which supports instrumentation and load-time weaving of it's classes by "shadowing" the classes
 * of it's enclosing classloader by loading, defining, and transfomring the byte code within the context of this
 * classloader.
 *
 *
Much of this code is based on Spring's {@code ShadowingClassLoader}.

 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
*/
public class ShadowingInstrumentableClassLoader extends DecoratingClassLoader {

    private static final String[] DEFAULT_EXCLUDES = new String[] {
            "java.", "javax.", "sun.", "oracle.", "com.sun.", "com.ibm.", "COM.ibm.", "org.w3c.", "org.xml.",
            "org.dom4j.", "org.eclipse", "org.aspectj.", "net.sf.cglib", "org.springframework.cglib",
            "org.apache.xerces.", "org.apache.commons.logging."
    };

    private final ClassLoader enclosingClassLoader;
    private final WeavingTransformer weavingTransformer;

    private final Map<String, Class<?>> classCache = new HashMap<String, Class<?>>();
    private final Set<String> attempted = new HashSet<String>();

    public ShadowingInstrumentableClassLoader(ClassLoader enclosingClassLoader) {
        this(enclosingClassLoader, null);
    }

    public ShadowingInstrumentableClassLoader(ClassLoader enclosingClassLoader, String[] excludedPackages) {
        if (enclosingClassLoader == null) {
            throw new IllegalArgumentException("Enclosing ClassLoader must not be null");
        }
        this.weavingTransformer = new WeavingTransformer(this);
        this.enclosingClassLoader = enclosingClassLoader;
        for (String defaultExcludedPackage : DEFAULT_EXCLUDES) {
            excludePackage(defaultExcludedPackage);
        }
        if (excludedPackages != null) {
            for (String excludedPackage : excludedPackages) {
                excludePackage(excludedPackage);
            }
        }
    }

    public void addTransformer(ClassFileTransformer transformer) {
        weavingTransformer.addTransformer(transformer);
    }

    @Override
    public synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        Class<?> cls = this.classCache.get(name);
        if (cls != null) {
            return cls;
        }
        if (!attempted.contains(name) && shouldInstrument(name)) {
            return loadAndInstrumentClass(name);
        }
        else {
            return this.enclosingClassLoader.loadClass(name);
        }
    }

    /**
     * Determine whether the given class should be excluded from instrumentation.
     *
     * @param className the name of the class
     *
     * @return whether the specified class should be instrumented
     */
    private boolean shouldInstrument(String className) {
        return !className.equals(getClass().getName()) && !isExcluded(className);
    }

    private Class<?> loadAndInstrumentClass(String name) throws ClassNotFoundException {
        String internalName = StringUtils.replace(name, ".", "/") + ".class";
        attempted.add(name);
        attempted.add(internalName);
        InputStream is = this.enclosingClassLoader.getResourceAsStream(internalName);
        if (is == null) {
            throw new ClassNotFoundException(name);
        }
        byte[] bytes;
        try {
            bytes = ByteStreams.toByteArray(is);
        } catch (IOException e) {
            throw new ClassNotFoundException("Cannot load resource for class [" + name + "]", e);
        } finally {
            Closeables.closeQuietly(is);
        }
        bytes = weavingTransformer.transformIfNecessary(name, bytes);
        Class<?> cls = defineClass(name, bytes, 0, bytes.length);
        // Additional check for defining the package, if not defined yet.
        if (cls.getPackage() == null) {
            int packageSeparator = name.lastIndexOf('.');
            if (packageSeparator != -1) {
                String packageName = name.substring(0, packageSeparator);
                definePackage(packageName, null, null, null, null, null, null, null);
            }
        }
        this.classCache.put(name, cls);
        return cls;
    }

    @Override
    public URL getResource(String name) {
        return this.enclosingClassLoader.getResource(name);
    }

    @Override
    public InputStream getResourceAsStream(String name) {
        return this.enclosingClassLoader.getResourceAsStream(name);
    }

    @Override
    public Enumeration<URL> getResources(String name) throws IOException {
        return this.enclosingClassLoader.getResources(name);
    }

}


text:
require 'common_utils'
# require 'action_mailer_mixins'
# require 'action_view_mixins'
# require 'active_record_mixins'
# require 'array_mixins'
# require 'cache_mixins'
# require 'columnized'
# require 'crypto'
# require 'custom_validations'
# require 'hash_mixins'
# require 'key_generator'
# require 'migration_helpers'
# require 'object_mixins'
# require 'validation_mixins'


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <base href="/">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">

    <link rel="stylesheet" href="app/app.css">

      <link rel="stylesheet" href="app/animate.css">

    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Raleway" />


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8" />
<meta name="generator" content="AsciiDoc 8.6.8" />
<title>Git Protocol Capabilities</title>

Git Protocol Capabilities

Servers SHOULD support all capabilities defined in this document.

On the very first line of the initial server response of either
receive-pack and upload-pack the first reference is followed by
a NUL byte and then a list of space delimited server capabilities.
These allow the server to declare what it can and cannot support
to the client.

Client will then send a space separated list of capabilities it wants
to be in effect. The client MUST NOT ask for capabilities the server
did not say it supports.

Server MUST diagnose and abort if capabilities it does not understand
was sent.  Server MUST NOT ignore capabilities that client requested
and server advertised.  As a consequence of these rules, server MUST
NOT advertise capabilities it does not understand.

The report-status and delete-refs capabilities are sent and
recognized by the receive-pack (push to server) process.

The ofs-delta capability is sent and recognized by both upload-pack
and receive-pack protocols.

All other capabilities are only recognized by the upload-pack (fetch
from server) process.

multi_ack

The multi_ack capability allows the server to return "ACK obj-id
continue" as soon as it finds a commit that it can use as a common
base, between the client’s wants and the client’s have set.

By sending this early, the server can potentially head off the client
from walking any further down that particular branch of the client’s
repository history.  The client may still need to walk down other
branches, sending have lines for those, until the server has a
complete cut across the DAG, or the client has said "done".

Without multi_ack, a client sends have lines in --date-order until
the server has found a common base.  That means the client will send
have lines that are already known by the server to be common, because
they overlap in time with another branch that the server hasn’t found
a common base on yet.

For example suppose the client has commits in caps that the server
doesn’t and the server has commits in lower case that the client
doesn’t, as in the following diagram:

   +---- u ---------------------- x
  /              +----- y
 /              /
a -- b -- c -- d -- E -- F
   \
    +--- Q -- R -- S

If the client wants x,y and starts out by saying have F,S, the server
doesn’t know what F,S is.  Eventually the client says "have d" and
the server sends "ACK d continue" to let the client know to stop
walking down that line (so don’t send c-b-a), but it’s not done yet,
it needs a base for x. The client keeps going with S-R-Q, until a
gets reached, at which point the server has a clear base and it all
ends.

Without multi_ack the client would have sent that c-b-a chain anyway,
interleaved with S-R-Q.

thin-pack

This capability means that the server can send a thin pack, a pack
which does not contain base objects; if those base objects are available
on client side. Client requests thin-pack capability when it
understands how to "thicken" it by adding required delta bases making
it self-contained.

Client MUST NOT request thin-pack capability if it cannot turn a thin
pack into a self-contained pack.

side-band, side-band-64k

This capability means that server can send, and client understand multiplexed
progress reports and error info interleaved with the packfile itself.

These two options are mutually exclusive. A modern client always
favors side-band-64k.

Either mode indicates that the packfile data will be streamed broken
up into packets of up to either 1000 bytes in the case of side_band,
or 65520 bytes in the case of side_band_64k. Each packet is made up
of a leading 4-byte pkt-line length of how much data is in the packet,
followed by a 1-byte stream code, followed by the actual data.

The stream code can be one of:

1 - pack data
2 - progress messages
3 - fatal error message just before stream aborts

The "side-band-64k" capability came about as a way for newer clients
that can handle much larger packets to request packets that are
actually crammed nearly full, while maintaining backward compatibility
for the older clients.

Further, with side-band and its up to 1000-byte messages, it’s actually
999 bytes of payload and 1 byte for the stream code. With side-band-64k,
same deal, you have up to 65519 bytes of data and 1 byte for the stream
code.

The client MUST send only maximum of one of "side-band" and "side-
band-64k".  Server MUST diagnose it as an error if client requests
both.

ofs-delta

Server can send, and client understand PACKv2 with delta referring to
its base by position in pack rather than by an obj-id.  That is, they can
send/read OBJ_OFS_DELTA (aka type 6) in a packfile.

shallow

This capability adds "deepen", "shallow" and "unshallow" commands to
the  fetch-pack/upload-pack protocol so clients can request shallow
clones.

no-progress

The client was started with "git clone -q" or something, and doesn’t
want that side band 2.  Basically the client just says "I do not
wish to receive stream 2 on sideband, so do not send it to me, and if
you did, I will drop it on the floor anyway".  However, the sideband
channel 3 is still used for error responses.

include-tag

The include-tag capability is about sending annotated tags if we are
sending objects they point to.  If we pack an object to the client, and
a tag object points exactly at that object, we pack the tag object too.
In general this allows a client to get all new annotated tags when it
fetches a branch, in a single network connection.

Clients MAY always send include-tag, hardcoding it into a request when
the server advertises this capability. The decision for a client to
request include-tag only has to do with the client’s desires for tag
data, whether or not a server had advertised objects in the
refs/tags/* namespace.

Servers MUST pack the tags if their referrant is packed and the client
has requested include-tags.

Clients MUST be prepared for the case where a server has ignored
include-tag and has not actually sent tags in the pack.  In such
cases the client SHOULD issue a subsequent fetch to acquire the tags
that include-tag would have otherwise given the client.

The server SHOULD send include-tag, if it supports it, regardless
of whether or not there are tags available.

report-status

The upload-pack process can receive a report-status capability,
which tells it that the client wants a report of what happened after
a packfile upload and reference update.  If the pushing client requests
this capability, after unpacking and updating references the server
will respond with whether the packfile unpacked successfully and if
each reference was updated successfully.  If any of those were not
successful, it will send back an error message.  See pack-protocol.txt
for example messages.

delete-refs

If the server sends back the delete-refs capability, it means that
it is capable of accepting a zero-id value as the target
value of a reference update.  It is not sent back by the client, it
simply informs the client that it can be sent zero-id values
to delete references.

Last updated 2011-11-15 13:45:02 PST


text:
package com.demo.aspect;

import java.lang.annotation.*;

/**
 * 自定义注解 拦截Controller
 * @author dong.wang
 *
 */

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AddLog {

	/** 要执行的方法描述 **/
	public String value() default "";

}


text:
using Vertica.Utilities.Comparisons;

namespace Vertica.Utilities.Tests.Comparisons.Support
{
	internal class Property2ChainableComparer : ChainableComparer<ComparisonSubject>
	{
		public Property2ChainableComparer() { }
		public Property2ChainableComparer(Direction sortDirection) : base(sortDirection) { }

		protected override int DoCompare(ComparisonSubject x, ComparisonSubject y)
		{
			return x.Property2.CompareTo(y.Property2);
		}
	}
}


text:
package javan.util.function;

/**
 * Represents a supplier of {@code double}-valued results.  This is the
 * {@code double}-producing primitive specialization of {@link Supplier}.
 *
 *
There is no requirement that a distinct result be returned each
 * time the supplier is invoked.
 *
 *
This is a functional interface
 * whose functional method is {@link #getAsDouble()}.
 *
 * @see Supplier
 * @since 1.8
 */
@FunctionalInterface
public interface DoubleSupplier {

    /**
     * Gets a result.
     *
     * @return a result
     */
    double getAsDouble();
}


text:
package net.maritimecloud.identityregistry.command.user;

import javax.annotation.Resource;
import net.maritimecloud.identityregistry.command.api.ChangeUserPassword;
import net.maritimecloud.identityregistry.command.api.ResetPasswordKeyGenerated;
import net.maritimecloud.identityregistry.command.api.UserPasswordChanged;
import net.maritimecloud.portal.application.ApplicationServiceRegistry;
import net.maritimecloud.common.eventsourcing.axon.NoReplayedEvents;
import net.maritimecloud.portal.infrastructure.mail.MailService;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.axonframework.saga.annotation.AbstractAnnotatedSaga;
import org.axonframework.saga.annotation.EndSaga;
import org.axonframework.saga.annotation.SagaEventHandler;
import org.axonframework.saga.annotation.StartSaga;

/**
 *
 * @author Christoffer Børrild
 */
@NoReplayedEvents
public class ResetPasswordSaga extends AbstractAnnotatedSaga {

    @Resource
    private transient CommandGateway commandGateway;

    private MailService mailService() {
        return ApplicationServiceRegistry.mailService();
    }

    public CommandGateway getCommandGateway() {
        return commandGateway;
    }

    public void setCommandGateway(CommandGateway commandGateway) {
        this.commandGateway = commandGateway;
    }

    @StartSaga
    @SagaEventHandler(associationProperty = "userId")
    public void handle(ResetPasswordKeyGenerated event) {

        System.out.println("User " + event.getUsername() + " has requested to reset password using " + event.getEmailAddress() + ".");

        // compose and send out welcome and confirm email
        System.out.println("Sending out reset password instruction email with the reset password key: " + event.getResetPasswordKey());

        mailService().sendResetPasswordMessage(event.getEmailAddress(), event.getUsername(), event.getResetPasswordKey());

        // HACK: FIXME: TODO:
        // auto-confirm users that fulfil some criteria
        autoResetTestUsersPassword_HACK(event.getUserId(), event.getEmailAddress(), event.getResetPasswordKey());
    }

    private String autoResetTestUsersPassword_HACK(UserId userId, String emailAddress, String resetPasswordKey) {
        // HACK: FIXME: TODO:
        // auto generate ResetPasswordCommand in odrer to auto-reset users password in test and demo without reading mails
        if (emailAddress.endsWith("@auto.demo.dma.dk")) {
            System.out.println("HACK for auto.demo.dma.dk dmoain: auto-reset password to 'reset' for user " + userId);
            commandGateway.send(new ChangeUserPassword(userId, resetPasswordKey, "reset"));
        }
        return resetPasswordKey;
    }

    @EndSaga
    @SagaEventHandler(associationProperty = "userId")
    public void handle(UserPasswordChanged event) {
        System.out.println("User " + event.getUsername() + " password has been changed.");
        //System.out.println("Sending out a 'Users password was reset' notification email to: " + event.getUsername());
    }

    // FIXME TODO: add en expire saga trigger to end unanswered saga instances!!!
    //@EndSaga
    //...
}