text:
package org.apache.cassandra.auth.jmx;

import java.lang.reflect.Field;
import java.nio.file.Paths;
import java.rmi.server.RMISocketFactory;
import java.util.HashMap;
import java.util.Map;
import javax.management.JMX;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.*;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;

import com.google.common.collect.ImmutableSet;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import org.apache.cassandra.auth.*;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.cql3.CQLTester;
import org.apache.cassandra.db.ColumnFamilyStoreMBean;
import org.apache.cassandra.utils.JMXServerUtils;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

public class JMXAuthTest extends CQLTester
{
    private static JMXConnectorServer jmxServer;
    private static MBeanServerConnection connection;
    private RoleResource role;
    private String tableName;
    private JMXResource tableMBean;

    @FunctionalInterface
    private interface MBeanAction
    {
        void execute();
    }

    @BeforeClass
    public static void setupClass() throws Exception
    {
        setupAuthorizer();
        setupJMXServer();
    }

    private static void setupAuthorizer()
    {
        try
        {
            IAuthorizer authorizer = new StubAuthorizer();
            Field authorizerField = DatabaseDescriptor.class.getDeclaredField("authorizer");
            authorizerField.setAccessible(true);
            authorizerField.set(null, authorizer);
            DatabaseDescriptor.setPermissionsValidity(0);
        }
        catch (IllegalAccessException | NoSuchFieldException e)
        {
            throw new RuntimeException(e);
        }
    }

    private static void setupJMXServer() throws Exception
    {
        String config = Paths.get(ClassLoader.getSystemResource("auth/cassandra-test-jaas.conf").toURI()).toString();
        System.setProperty("com.sun.management.jmxremote.authenticate", "true");
        System.setProperty("java.security.auth.login.config", config);
        System.setProperty("cassandra.jmx.remote.login.config", "TestLogin");
        System.setProperty("cassandra.jmx.authorizer", NoSuperUserAuthorizationProxy.class.getName());
        jmxServer = JMXServerUtils.createJMXServer(9999, "localhost", true);
        jmxServer.start();

        JMXServiceURL jmxUrl = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi");
        Map<String, Object> env = new HashMap<>();
        env.put("com.sun.jndi.rmi.factory.socket", RMISocketFactory.getDefaultSocketFactory());
        JMXConnector jmxc = JMXConnectorFactory.connect(jmxUrl, env);
        connection = jmxc.getMBeanServerConnection();
    }

    @Before
    public void setup() throws Throwable
    {
        role = RoleResource.role("test_role");
        clearAllPermissions();
        tableName = createTable("CREATE TABLE %s (k int, v int, PRIMARY KEY (k))");
        tableMBean = JMXResource.mbean(String.format("org.apache.cassandra.db:type=Tables,keyspace=%s,table=%s",
                                                     KEYSPACE, tableName));
    }

    @Test
    public void readAttribute() throws Throwable
    {
        ColumnFamilyStoreMBean proxy = JMX.newMBeanProxy(connection,
                                                         ObjectName.getInstance(tableMBean.getObjectName()),
                                                         ColumnFamilyStoreMBean.class);

        // grant SELECT on a single specific Table mbean
        assertPermissionOnResource(Permission.SELECT, tableMBean, proxy::getTableName);

        // grant SELECT on all Table mbeans in named keyspace
        clearAllPermissions();
        JMXResource allTablesInKeyspace = JMXResource.mbean(String.format("org.apache.cassandra.db:type=Tables,keyspace=%s,*",
                                                                          KEYSPACE));
        assertPermissionOnResource(Permission.SELECT, allTablesInKeyspace, proxy::getTableName);

        // grant SELECT on all Table mbeans
        clearAllPermissions();
        JMXResource allTables = JMXResource.mbean("org.apache.cassandra.db:type=Tables,*");
        assertPermissionOnResource(Permission.SELECT, allTables, proxy::getTableName);

        // grant SELECT ON ALL MBEANS
        clearAllPermissions();
        assertPermissionOnResource(Permission.SELECT, JMXResource.root(), proxy::getTableName);
    }

    @Test
    public void writeAttribute() throws Throwable
    {
        ColumnFamilyStoreMBean proxy = JMX.newMBeanProxy(connection,
                                                         ObjectName.getInstance(tableMBean.getObjectName()),
                                                         ColumnFamilyStoreMBean.class);
        MBeanAction action = () -> proxy.setMinimumCompactionThreshold(4);

        // grant MODIFY on a single specific Table mbean
        assertPermissionOnResource(Permission.MODIFY, tableMBean, action);

        // grant MODIFY on all Table mbeans in named keyspace
        clearAllPermissions();
        JMXResource allTablesInKeyspace = JMXResource.mbean(String.format("org.apache.cassandra.db:type=Tables,keyspace=%s,*",
                                                                          KEYSPACE));
        assertPermissionOnResource(Permission.MODIFY, allTablesInKeyspace, action);

        // grant MODIFY on all Table mbeans
        clearAllPermissions();
        JMXResource allTables = JMXResource.mbean("org.apache.cassandra.db:type=Tables,*");
        assertPermissionOnResource(Permission.MODIFY, allTables, action);

        // grant MODIFY ON ALL MBEANS
        clearAllPermissions();
        assertPermissionOnResource(Permission.MODIFY, JMXResource.root(), action);
    }

    @Test
    public void executeMethod() throws Throwable
    {
        ColumnFamilyStoreMBean proxy = JMX.newMBeanProxy(connection,
                                                         ObjectName.getInstance(tableMBean.getObjectName()),
                                                         ColumnFamilyStoreMBean.class);

        // grant EXECUTE on a single specific Table mbean
        assertPermissionOnResource(Permission.EXECUTE, tableMBean, proxy::estimateKeys);

        // grant EXECUTE on all Table mbeans in named keyspace
        clearAllPermissions();
        JMXResource allTablesInKeyspace = JMXResource.mbean(String.format("org.apache.cassandra.db:type=Tables,keyspace=%s,*",
                                                                          KEYSPACE));
        assertPermissionOnResource(Permission.EXECUTE, allTablesInKeyspace, proxy::estimateKeys);

        // grant EXECUTE on all Table mbeans
        clearAllPermissions();
        JMXResource allTables = JMXResource.mbean("org.apache.cassandra.db:type=Tables,*");
        assertPermissionOnResource(Permission.EXECUTE, allTables, proxy::estimateKeys);

        // grant EXECUTE ON ALL MBEANS
        clearAllPermissions();
        assertPermissionOnResource(Permission.EXECUTE, JMXResource.root(), proxy::estimateKeys);
    }

    private void assertPermissionOnResource(Permission permission,
                                            JMXResource resource,
                                            MBeanAction action)
    {
        assertUnauthorized(action);
        grantPermission(permission, resource, role);
        assertAuthorized(action);
    }

    private void grantPermission(Permission permission, JMXResource resource, RoleResource role)
    {
        DatabaseDescriptor.getAuthorizer().grant(AuthenticatedUser.SYSTEM_USER,
                                                 ImmutableSet.of(permission),
                                                 resource,
                                                 role);
    }

    private void assertAuthorized(MBeanAction action)
    {
        action.execute();
    }

    private void assertUnauthorized(MBeanAction action)
    {
        try
        {
            action.execute();
            fail("Expected an UnauthorizedException, but none was thrown");
        }
        catch (SecurityException e)
        {
            assertEquals("Access Denied", e.getLocalizedMessage());
        }
    }

    private void clearAllPermissions()
    {
        ((StubAuthorizer) DatabaseDescriptor.getAuthorizer()).clear();
    }

    public static class StubLoginModule implements LoginModule
    {
        private CassandraPrincipal principal;
        private Subject subject;

        public StubLoginModule(){}

        public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options)
        {
            this.subject = subject;
            principal = new CassandraPrincipal((String)options.get("role_name"));
        }

        public boolean login() throws LoginException
        {
            return true;
        }

        public boolean commit() throws LoginException
        {
            if (!subject.getPrincipals().contains(principal))
                subject.getPrincipals().add(principal);
            return true;
        }

        public boolean abort() throws LoginException
        {
            return true;
        }

        public boolean logout() throws LoginException
        {
            return true;
        }
    }

    // always answers false to isSuperUser and true to isAuthSetup complete - saves us having to initialize
    // a real IRoleManager and StorageService for the test
    public static class NoSuperUserAuthorizationProxy extends AuthorizationProxy
    {
        public NoSuperUserAuthorizationProxy()
        {
            super();
            this.isSuperuser = (role) -> false;
            this.isAuthSetupComplete = () -> true;
        }
    }
}


text:
<?php if(isset($alert_message) && strlen(trim($alert_message)) > 0): ?>
    <?php
    $type = array(
        'Error' => 'danger',
        'Warning' => 'warning',
        'Success' => 'success'
    );
    ?>
    <div class="alert alert-<?php echo $type[$alert_type]?>" role="alert">

        Error:

        <?php echo $alert_message?>

<?php endif;?>

redpajama_set_name: RedPajamaGithub


text:
package genmai

import (
	"database/sql"
	"errors"
	"fmt"
	"io"
	"reflect"
	"runtime"
	"sort"
	"strconv"
	"strings"
	"sync"

	"github.com/naoina/go-stringutil"
)

var ErrTxDone = errors.New("genmai: transaction hasn't been started or already committed or rolled back")

// DB represents a database object.
type DB struct {
	db      *sql.DB
	dialect Dialect
	tx      *sql.Tx
	m       sync.Mutex
	logger  logger
}

// New returns a new DB.
// If any error occurs, it returns nil and error.
func New(dialect Dialect, dsn string) (*DB, error) {
	db, err := sql.Open(dialect.Name(), dsn)
	if err != nil {
		return nil, err
	}
	return &DB{db: db, dialect: dialect, logger: defaultLogger}, nil
}

// Select fetch data into the output from the database.
// output argument must be pointer to a slice of struct. If not a pointer or not a slice of struct, It returns error.
// The table name of the database will be determined from name of struct. e.g. If *[]ATableName passed to output argument, table name will be "a_table_name".
// If args are not given, fetch the all data like "SELECT * FROM table" SQL.
func (db *DB) Select(output interface{}, args ...interface{}) (err error) {
	defer func() {
		if e := recover(); e != nil {
			buf := make([]byte, 4096)
			n := runtime.Stack(buf, false)
			err = fmt.Errorf("%v\n%v", e, string(buf[:n]))
		}
	}()
	rv := reflect.ValueOf(output)
	if rv.Kind() != reflect.Ptr {
		return fmt.Errorf("Select: first argument must be a pointer")
	}
	for rv.Kind() == reflect.Ptr {
		rv = rv.Elem()
	}
	var tableName string
	for _, arg := range args {
		if f, ok := arg.(*From); ok {
			if tableName != "" {
				return fmt.Errorf("Select: From statement specified more than once")
			}
			tableName = f.TableName
		}
	}
	var selectFunc selectFunc
	ptrN := 0
	switch rv.Kind() {
	case reflect.Slice:
		t := rv.Type().Elem()
		for ; t.Kind() == reflect.Ptr; ptrN++ {
			t = t.Elem()
		}
		if t.Kind() != reflect.Struct {
			return fmt.Errorf("Select: argument of slice must be slice of struct, but %v", rv.Type())
		}
		if tableName == "" {
			tableName = db.tableName(t)
		}
		selectFunc = db.selectToSlice
	case reflect.Invalid:
		return fmt.Errorf("Select: nil pointer dereference")
	default:
		if tableName == "" {
			return fmt.Errorf("Select: From statement must be given if any Function is given")
		}
		selectFunc = db.selectToValue
	}
	col, from, conditions, err := db.classify(tableName, args)
	if err != nil {
		return err
	}
	queries := []string{`SELECT`, col, `FROM`, db.dialect.Quote(from)}
	var values []interface{}
	for _, cond := range conditions {
		q, a := cond.build(0, false)
		queries = append(queries, q...)
		values = append(values, a...)
	}
	query := strings.Join(queries, " ")
	stmt, err := db.prepare(query, values...)
	if err != nil {
		return err
	}
	defer stmt.Close()
	rows, err := stmt.Query(values...)
	if err != nil {
		return err
	}
	defer rows.Close()
	value, err := selectFunc(rows, rv.Type())
	if err != nil {
		return err
	}
	rv.Set(value)
	return nil
}

// From returns a "FROM" statement.
// A table name will be determined from name of struct of arg.
// If arg argument is not struct type, it panics.
func (db *DB) From(arg interface{}) *From {
	t := reflect.Indirect(reflect.ValueOf(arg)).Type()
	if t.Kind() != reflect.Struct {
		panic(fmt.Errorf("From: argument must be struct (or that pointer) type, got %v", t))
	}
	return &From{TableName: db.tableName(t)}
}

// Where returns a new Condition of "WHERE" clause.
func (db *DB) Where(cond interface{}, args ...interface{}) *Condition {
	return newCondition(db).Where(cond, args...)
}

// OrderBy returns a new Condition of "ORDER BY" clause.
func (db *DB) OrderBy(table interface{}, column interface{}, order ...interface{}) *Condition {
	return newCondition(db).OrderBy(table, column, order...)
}

// Limit returns a new Condition of "LIMIT" clause.
func (db *DB) Limit(lim int) *Condition {
	return newCondition(db).Limit(lim)
}

// Offset returns a new Condition of "OFFSET" clause.
func (db *DB) Offset(offset int) *Condition {
	return newCondition(db).Offset(offset)
}

// Distinct returns a representation object of "DISTINCT" statement.
func (db *DB) Distinct(columns ...string) *Distinct {
	return &Distinct{columns: columns}
}

// Join returns a new JoinCondition of "JOIN" clause.
func (db *DB) Join(table interface{}) *JoinCondition {
	return (&JoinCondition{db: db}).Join(table)
}

func (db *DB) LeftJoin(table interface{}) *JoinCondition {
	return (&JoinCondition{db: db}).LeftJoin(table)
}

// Count returns "COUNT" function.
func (db *DB) Count(column ...interface{}) *Function {
	switch len(column) {
	case 0, 1:
		// do nothing.
	default:
		panic(fmt.Errorf("Count: a number of argument must be 0 or 1, got %v", len(column)))
	}
	return &Function{
		Name: "COUNT",
		Args: column,
	}
}

const (
	dbTag        = "db"
	dbColumnTag  = "column"
	dbDefaultTag = "default"
	dbSizeTag    = "size"
	skipTag      = "-"
)

// CreateTable creates the table into database.
// If table isn't direct/indirect struct, it returns error.
func (db *DB) CreateTable(table interface{}) error {
	return db.createTable(table, false)
}

// CreateTableIfNotExists creates the table into database if table isn't exists.
// If table isn't direct/indirect struct, it returns error.
func (db *DB) CreateTableIfNotExists(table interface{}) error {
	return db.createTable(table, true)
}

func (db *DB) createTable(table interface{}, ifNotExists bool) error {
	_, t, tableName, err := db.tableValueOf("CreateTable", table)
	if err != nil {
		return err
	}
	fields, err := db.collectTableFields(t)
	if err != nil {
		return err
	}
	var query string
	if ifNotExists {
		query = "CREATE TABLE IF NOT EXISTS %s (%s)"
	} else {
		query = "CREATE TABLE %s (%s)"
	}
	query = fmt.Sprintf(query, db.dialect.Quote(tableName), strings.Join(fields, ", "))
	stmt, err := db.prepare(query)
	if err != nil {
		return err
	}
	defer stmt.Close()
	if _, err := stmt.Exec(); err != nil {
		return err
	}
	return nil
}

// DropTable removes the table from database.
// If table isn't direct/indirect struct, it returns error.
func (db *DB) DropTable(table interface{}) error {
	_, _, tableName, err := db.tableValueOf("DropTable", table)
	if err != nil {
		return err
	}
	query := fmt.Sprintf("DROP TABLE %s", db.dialect.Quote(tableName))
	stmt, err := db.prepare(query)
	if err != nil {
		return err
	}
	defer stmt.Close()
	if _, err = stmt.Exec(); err != nil {
		return err
	}
	return nil
}

// CreateIndex creates the index into database.
// If table isn't direct/indirect struct, it returns error.
func (db *DB) CreateIndex(table interface{}, name string, names ...string) error {
	return db.createIndex(table, false, name, names...)
}

// CreateUniqueIndex creates the unique index into database.
// If table isn't direct/indirect struct, it returns error.
func (db *DB) CreateUniqueIndex(table interface{}, name string, names ...string) error {
	return db.createIndex(table, true, name, names...)
}

func (db *DB) createIndex(table interface{}, unique bool, name string, names ...string) error {
	_, _, tableName, err := db.tableValueOf("CreateIndex", table)
	if err != nil {
		return err
	}
	names = append([]string{name}, names...)
	indexes := make([]string, len(names))
	for i, name := range names {
		indexes[i] = db.dialect.Quote(name)
	}
	indexName := strings.Join(append([]string{"index", tableName}, names...), "_")
	var query string
	if unique {
		query = "CREATE UNIQUE INDEX %s ON %s (%s)"
	} else {
		query = "CREATE INDEX %s ON %s (%s)"
	}
	query = fmt.Sprintf(query,
		db.dialect.Quote(indexName),
		db.dialect.Quote(tableName),
		strings.Join(indexes, ", "))
	stmt, err := db.prepare(query)
	if err != nil {
		return err
	}
	defer stmt.Close()
	if _, err := stmt.Exec(); err != nil {
		return err
	}
	return nil
}

// Update updates the one record.
// The obj must be struct, and must have field that specified "pk" struct tag.
// Update will try to update record which searched by value of primary key in obj.
// Update returns the number of rows affected by an update.
func (db *DB) Update(obj interface{}) (affected int64, err error) {
	rv, rtype, tableName, err := db.tableValueOf("Update", obj)
	if err != nil {
		return -1, err
	}
	if hook, ok := obj.(BeforeUpdater); ok {
		if err := hook.BeforeUpdate(); err != nil {
			return -1, err
		}
	}
	fieldIndexes := db.collectFieldIndexes(rtype, nil)
	pkIdx := db.findPKIndex(rtype, nil)
	if len(pkIdx) < 1 {
		return -1, fmt.Errorf(`Update: fields of struct doesn't have primary key: "pk" struct tag must be specified for update`)
	}
	sets := make([]string, len(fieldIndexes))
	var args []interface{}
	for i, index := range fieldIndexes {
		col := db.columnFromTag(rtype.FieldByIndex(index))
		sets[i] = fmt.Sprintf("%s = %s", db.dialect.Quote(col), db.dialect.PlaceHolder(i))
		args = append(args, rv.FieldByIndex(index).Interface())
	}
	query := fmt.Sprintf("UPDATE %s SET %s WHERE %s = %s",
		db.dialect.Quote(tableName),
		strings.Join(sets, ", "),
		db.dialect.Quote(db.columnFromTag(rtype.FieldByIndex(pkIdx))),
		db.dialect.PlaceHolder(len(fieldIndexes)))
	args = append(args, rv.FieldByIndex(pkIdx).Interface())
	stmt, err := db.prepare(query, args...)
	if err != nil {
		return -1, err
	}
	defer stmt.Close()
	result, err := stmt.Exec(args...)
	if err != nil {
		return -1, err
	}
	affected, _ = result.RowsAffected()
	if hook, ok := obj.(AfterUpdater); ok {
		if err := hook.AfterUpdate(); err != nil {
			return affected, err
		}
	}
	return affected, nil
}

// Insert inserts one or more records to the database table.
// The obj must be pointer to struct or slice of struct. If a struct have a
// field which specified "pk" struct tag on type of autoincrementable, it
// won't be used to as an insert value.
// Insert sets the last inserted id to the primary key of the instance of the given obj if obj is single.
// Insert returns the number of rows affected by insert.
func (db *DB) Insert(obj interface{}) (affected int64, err error) {
	objs, rtype, tableName, err := db.tableObjs("Insert", obj)
	if err != nil {
		return -1, err
	}
	if len(objs) < 1 {
		return 0, nil
	}
	for _, obj := range objs {
		if hook, ok := obj.(BeforeInserter); ok {
			if err := hook.BeforeInsert(); err != nil {
				return -1, err
			}
		}
	}
	fieldIndexes := db.collectFieldIndexes(rtype, nil)
	cols := make([]string, len(fieldIndexes))
	for i, index := range fieldIndexes {
		cols[i] = db.dialect.Quote(db.columnFromTag(rtype.FieldByIndex(index)))
	}
	var args []interface{}
	for _, obj := range objs {
		rv := reflect.Indirect(reflect.ValueOf(obj))
		for _, index := range fieldIndexes {
			args = append(args, rv.FieldByIndex(index).Interface())
		}
	}
	numHolders := 0
	values := make([]string, len(objs))
	holders := make([]string, len(cols))
	for i := 0; i < len(values); i++ {
		for j := 0; j < len(holders); j++ {
			holders[j] = db.dialect.PlaceHolder(numHolders)
			numHolders++
		}
		values[i] = fmt.Sprintf("(%s)", strings.Join(holders, ", "))
	}
	query := fmt.Sprintf("INSERT INTO %s (%s) VALUES %s",
		db.dialect.Quote(tableName),
		strings.Join(cols, ", "),
		strings.Join(values, ", "),
	)
	stmt, err := db.prepare(query, args...)
	if err != nil {
		return -1, err
	}
	defer stmt.Close()
	result, err := stmt.Exec(args...)
	if err != nil {
		return -1, err
	}
	affected, _ = result.RowsAffected()
	if len(objs) == 1 {
		if pkIdx := db.findPKIndex(rtype, nil); len(pkIdx) > 0 {
			field := rtype.FieldByIndex(pkIdx)
			if db.isAutoIncrementable(&field) {
				id, err := db.LastInsertId()
				if err != nil {
					return affected, err
				}
				rv := reflect.Indirect(reflect.ValueOf(objs[0])).FieldByIndex(pkIdx)
				for rv.Kind() == reflect.Ptr {
					rv = rv.Elem()
				}
				rv.Set(reflect.ValueOf(id).Convert(rv.Type()))
			}
		}
	}
	for _, obj := range objs {
		if hook, ok := obj.(AfterInserter); ok {
			if err := hook.AfterInsert(); err != nil {
				return affected, err
			}
		}
	}
	return affected, nil
}

// Delete deletes the records from database table.
// The obj must be pointer to struct or slice of struct, and must have field that specified "pk" struct tag.
// Delete will try to delete record which searched by value of primary key in obj.
// Delete returns teh number of rows affected by a delete.
func (db *DB) Delete(obj interface{}) (affected int64, err error) {
	objs, rtype, tableName, err := db.tableObjs("Delete", obj)
	if err != nil {
		return -1, err
	}
	if len(objs) < 1 {
		return 0, nil
	}
	for _, obj := range objs {
		if hook, ok := obj.(BeforeDeleter); ok {
			if err := hook.BeforeDelete(); err != nil {
				return -1, err
			}
		}
	}
	pkIdx := db.findPKIndex(rtype, nil)
	if len(pkIdx) < 1 {
		return -1, fmt.Errorf(`Delete: fields of struct doesn't have primary key: "pk" struct tag must be specified for delete`)
	}
	var args []interface{}
	for _, obj := range objs {
		rv := reflect.Indirect(reflect.ValueOf(obj))
		args = append(args, rv.FieldByIndex(pkIdx).Interface())
	}
	holders := make([]string, len(args))
	for i := 0; i < len(holders); i++ {
		holders[i] = db.dialect.PlaceHolder(i)
	}
	query := fmt.Sprintf("DELETE FROM %s WHERE %s IN (%s)",
		db.dialect.Quote(tableName),
		db.dialect.Quote(db.columnFromTag(rtype.FieldByIndex(pkIdx))),
		strings.Join(holders, ", "))
	stmt, err := db.prepare(query, args...)
	if err != nil {
		return -1, err
	}
	defer stmt.Close()
	result, err := stmt.Exec(args...)
	if err != nil {
		return -1, err
	}
	affected, _ = result.RowsAffected()
	for _, obj := range objs {
		if hook, ok := obj.(AfterDeleter); ok {
			if err := hook.AfterDelete(); err != nil {
				return affected, err
			}
		}
	}
	return affected, nil
}

// Begin starts a transaction.
func (db *DB) Begin() error {
	tx, err := db.db.Begin()
	if err != nil {
		return err
	}
	db.m.Lock()
	defer db.m.Unlock()
	db.tx = tx
	return nil
}

// Commit commits the transaction.
// If Begin still not called, or Commit or Rollback already called, Commit returns ErrTxDone.
func (db *DB) Commit() error {
	db.m.Lock()
	defer db.m.Unlock()
	if db.tx == nil {
		return ErrTxDone
	}
	err := db.tx.Commit()
	db.tx = nil
	return err
}

// Rollback rollbacks the transaction.
// If Begin still not called, or Commit or Rollback already called, Rollback returns ErrTxDone.
func (db *DB) Rollback() error {
	db.m.Lock()
	defer db.m.Unlock()
	if db.tx == nil {
		return ErrTxDone
	}
	err := db.tx.Rollback()
	db.tx = nil
	return err
}

func (db *DB) LastInsertId() (int64, error) {
	stmt, err := db.prepare(db.dialect.LastInsertId())
	if err != nil {
		return 0, err
	}
	defer stmt.Close()
	var id int64
	return id, stmt.QueryRow().Scan(&id)
}

// Raw returns a value that is wrapped with Raw.
func (db *DB) Raw(v interface{}) Raw {
	return Raw(&v)
}

// Close closes the database.
func (db *DB) Close() error {
	return db.db.Close()
}

// Quote returns a quoted s.
// It is for a column name, not a value.
func (db *DB) Quote(s string) string {
	return db.dialect.Quote(s)
}

// DB returns a *sql.DB that is associated to DB.
func (db *DB) DB() *sql.DB {
	return db.db
}

// SetLogOutput sets output destination for logging.
// If w is nil, it unsets output of logging.
func (db *DB) SetLogOutput(w io.Writer) {
	if w == nil {
		db.logger = defaultLogger
	} else {
		db.logger = &templateLogger{w: w, t: defaultLoggerTemplate}
	}
}

// SetLogFormat sets format for logging.
//
// Format syntax uses Go's template. And you can use the following data object in that template.
//
//     - .time        time.Time object in current time.
//     - .duration    Processing time of SQL. It will format to "%.2fms".
//     - .query       string of SQL query. If it using placeholder,
//                    placeholder parameters will append to the end of query.
//
// The default format is:
//
//     [{{.time.Format "2006-01-02 15:04:05"}}] [{{.duration}}] {{.query}}
func (db *DB) SetLogFormat(format string) error {
	return db.logger.SetFormat(format)
}

// selectToSlice returns a slice value fetched from rows.
func (db *DB) selectToSlice(rows *sql.Rows, t reflect.Type) (reflect.Value, error) {
	columns, err := rows.Columns()
	if err != nil {
		return reflect.Value{}, err
	}
	t = t.Elem()
	ptrN := 0
	for ; t.Kind() == reflect.Ptr; ptrN++ {
		t = t.Elem()
	}
	fieldIndexes := make([][]int, len(columns))
	for i, column := range columns {
		index := db.fieldIndexByName(t, column, nil)
		if len(index) < 1 {
			return reflect.Value{}, fmt.Errorf("`%v` field isn't defined in %v or embedded struct", stringutil.ToUpperCamelCase(column), t)
		}
		fieldIndexes[i] = index
	}
	dest := make([]interface{}, len(columns))
	var result []reflect.Value
	for rows.Next() {
		v := reflect.New(t).Elem()
		for i, index := range fieldIndexes {
			field := v.FieldByIndex(index)
			dest[i] = field.Addr().Interface()
		}
		if err := rows.Scan(dest...); err != nil {
			return reflect.Value{}, err
		}
		result = append(result, v)
	}
	if err := rows.Err(); err != nil {
		return reflect.Value{}, err
	}
	for i := 0; i < ptrN; i++ {
		t = reflect.PtrTo(t)
	}
	slice := reflect.MakeSlice(reflect.SliceOf(t), len(result), len(result))
	for i, v := range result {
		for j := 0; j < ptrN; j++ {
			v = v.Addr()
		}
		slice.Index(i).Set(v)
	}
	return slice, nil
}

// selectToValue returns a single value fetched from rows.
func (db *DB) selectToValue(rows *sql.Rows, t reflect.Type) (reflect.Value, error) {
	ptrN := 0
	for ; t.Kind() == reflect.Ptr; ptrN++ {
		t = t.Elem()
	}
	dest := reflect.New(t).Elem()
	if rows.Next() {
		if err := rows.Scan(dest.Addr().Interface()); err != nil {
			return reflect.Value{}, err
		}
	}
	for i := 0; i < ptrN; i++ {
		dest = dest.Addr()
	}
	return dest, nil
}

// fieldIndexByName returns the nested field corresponding to the index sequence.
func (db *DB) fieldIndexByName(t reflect.Type, name string, index []int) []int {
	for i := 0; i < t.NumField(); i++ {
		field := t.Field(i)
		if candidate := db.columnFromTag(field); candidate == name {
			return append(index, i)
		}
		if field.Anonymous {
			if idx := db.fieldIndexByName(field.Type, name, append(index, i)); len(idx) > 0 {
				return append(index, idx...)
			}
		}
	}
	return nil
}

func (db *DB) classify(tableName string, args []interface{}) (column, from string, conditions []*Condition, err error) {
	if len(args) == 0 {
		return ColumnName(db.dialect, tableName, "*"), tableName, nil, nil
	}
	offset := 1
	switch t := args[0].(type) {
	case string:
		if t != "" {
			column = ColumnName(db.dialect, tableName, t)
		}
	case []string:
		column = db.columns(tableName, ToInterfaceSlice(t))
	case *Distinct:
		column = fmt.Sprintf("DISTINCT %s", db.columns(tableName, ToInterfaceSlice(t.columns)))
	case *Function:
		var col string
		if len(t.Args) == 0 {
			col = "*"
		} else {
			col = db.columns(tableName, t.Args)
		}
		column = fmt.Sprintf("%s(%s)", t.Name, col)
	default:
		offset--
	}
	for i := offset; i < len(args); i++ {
		switch t := args[i].(type) {
		case *Condition:
			t.tableName = tableName
			conditions = append(conditions, t)
		case string, []string:
			return "", "", nil, fmt.Errorf("argument of %T type must be before the *Condition arguments", t)
		case *From:
			// ignore.
		case *Function:
			return "", "", nil, fmt.Errorf("%s function must be specified to the first argument", t.Name)
		default:
			return "", "", nil, fmt.Errorf("unsupported argument type: %T", t)
		}
	}
	if column == "" {
		column = ColumnName(db.dialect, tableName, "*")
	}
	return column, tableName, conditions, nil
}

// columns returns the comma-separated column name with quoted.
func (db *DB) columns(tableName string, columns []interface{}) string {
	if len(columns) == 0 {
		return ColumnName(db.dialect, tableName, "*")
	}
	names := make([]string, len(columns))
	for i, col := range columns {
		switch c := col.(type) {
		case Raw:
			names[i] = fmt.Sprint(*c)
		case string:
			names[i] = ColumnName(db.dialect, tableName, c)
		case *Distinct:
			names[i] = fmt.Sprintf("DISTINCT %s", db.columns(tableName, ToInterfaceSlice(c.columns)))
		default:
			panic(fmt.Errorf("column name must be string, Raw or *Distinct, got %T", c))
		}
	}
	return strings.Join(names, ", ")
}

func (db *DB) collectTableFields(t reflect.Type) (fields []string, err error) {
	for i := 0; i < t.NumField(); i++ {
		field := t.Field(i)
		if IsUnexportedField(field) {
			continue
		}
		if db.hasSkipTag(&field) {
			continue
		}
		if field.Anonymous {
			fs, err := db.collectTableFields(field.Type)
			if err != nil {
				return nil, err
			}
			fields = append(fields, fs...)
			continue
		}
		var options []string
		autoIncrement := false
		for _, tag := range db.tagsFromField(&field) {
			switch tag {
			case "pk":
				options = append(options, "PRIMARY KEY")
				if db.isAutoIncrementable(&field) {
					options = append(options, db.dialect.AutoIncrement())
					autoIncrement = true
				}
			case "unique":
				options = append(options, "UNIQUE")
			default:
				return nil, fmt.Errorf(`CreateTable: unsupported field tag: "%v"`, tag)
			}
		}
		size, err := db.sizeFromTag(&field)
		if err != nil {
			return nil, err
		}
		typName, allowNull := db.dialect.SQLType(reflect.Zero(field.Type).Interface(), autoIncrement, size)
		if !allowNull {
			options = append(options, "NOT NULL")
		}
		line := append([]string{db.dialect.Quote(db.columnFromTag(field)), typName}, options...)
		def, err := db.defaultFromTag(&field)
		if err != nil {
			return nil, err
		}
		if def != "" {
			line = append(line, def)
		}
		fields = append(fields, strings.Join(line, " "))
	}
	return fields, nil
}

// tagsFromField returns a slice of option strings.
func (db *DB) tagsFromField(field *reflect.StructField) (options []string) {
	if db.hasSkipTag(field) {
		return nil
	}
	for _, tag := range strings.Split(field.Tag.Get(dbTag), ",") {
		if t := strings.ToLower(strings.TrimSpace(tag)); t != "" {
			options = append(options, t)
		}
	}
	return options
}

// hasSkipTag returns whether the struct field has the "-" tag.
func (db *DB) hasSkipTag(field *reflect.StructField) bool {
	if field.Tag.Get(dbTag) == skipTag {
		return true
	}
	return false
}

// hasPKTag returns whether the struct field has the "pk" tag.
func (db *DB) hasPKTag(field *reflect.StructField) bool {
	for _, tag := range db.tagsFromField(field) {
		if tag == "pk" {
			return true
		}
	}
	return false
}

// isAutoIncrementable returns whether the struct field is integer.
func (db *DB) isAutoIncrementable(field *reflect.StructField) bool {
	switch field.Type.Kind() {
	case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64,
		reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return true
	}
	return false
}

// collectFieldIndexes returns the indexes of field which doesn't have skip tag and pk tag.
func (db *DB) collectFieldIndexes(typ reflect.Type, index []int) (indexes [][]int) {
	for i := 0; i < typ.NumField(); i++ {
		field := typ.Field(i)
		if IsUnexportedField(field) {
			continue
		}
		if !(db.hasSkipTag(&field) || (db.hasPKTag(&field) && db.isAutoIncrementable(&field))) {
			tmp := make([]int, len(index)+1)
			copy(tmp, index)
			tmp[len(tmp)-1] = i
			if field.Anonymous {
				indexes = append(indexes, db.collectFieldIndexes(field.Type, tmp)...)
			} else {
				indexes = append(indexes, tmp)
			}
		}
	}
	return indexes
}

// findPKIndex returns the nested field corresponding to the index sequence of field of primary key.
func (db *DB) findPKIndex(typ reflect.Type, index []int) []int {
	for i := 0; i < typ.NumField(); i++ {
		field := typ.Field(i)
		if IsUnexportedField(field) {
			continue
		}
		if field.Anonymous {
			if idx := db.findPKIndex(field.Type, append(index, i)); idx != nil {
				return append(index, idx...)
			}
			continue
		}
		if db.hasPKTag(&field) {
			return append(index, i)
		}
	}
	return nil
}

// sizeFromTag returns a size from tag.
// If "size" tag specified to struct field, it will converted to uint64 and returns it.
// If it doesn't specify, it returns 0.
// If value of "size" tag cannot convert to uint64, it returns 0 and error.
func (db *DB) sizeFromTag(field *reflect.StructField) (size uint64, err error) {
	if s := field.Tag.Get(dbSizeTag); s != "" {
		size, err = strconv.ParseUint(s, 10, 64)
	}
	return size, err
}

func (db *DB) tableName(t reflect.Type) string {
	if table, ok := reflect.New(t).Interface().(TableNamer); ok {
		return table.TableName()
	}
	return stringutil.ToSnakeCase(t.Name())
}

// columnFromTag returns the column name.
// If "column" tag specified to struct field, returns it.
// Otherwise, it returns snake-cased field name as column name.
func (db *DB) columnFromTag(field reflect.StructField) string {
	col := field.Tag.Get(dbColumnTag)
	if col == "" {
		return stringutil.ToSnakeCase(field.Name)
	}
	return col
}

// defaultFromTag returns a "DEFAULT ..." keyword.
// If "default" tag specified to struct field, it use as the default value.
// If it doesn't specify, it returns empty string.
func (db *DB) defaultFromTag(field *reflect.StructField) (string, error) {
	def := field.Tag.Get(dbDefaultTag)
	if def == "" {
		return "", nil
	}
	switch field.Type.Kind() {
	case reflect.Bool:
		b, err := strconv.ParseBool(def)
		if err != nil {
			return "", err
		}
		return fmt.Sprintf("DEFAULT %v", db.dialect.FormatBool(b)), nil
	}
	return fmt.Sprintf("DEFAULT %v", def), nil
}

func (db *DB) tableObjs(name string, obj interface{}) (objs []interface{}, rtype reflect.Type, tableName string, err error) {
	switch v := reflect.Indirect(reflect.ValueOf(obj)); v.Kind() {
	case reflect.Slice:
		if v.Len() < 1 {
			return objs, nil, "", nil
		}
		for i := 0; i < v.Len(); i++ {
			sv := v.Index(i)
			for sv.Kind() == reflect.Ptr {
				sv = sv.Elem()
			}
			if sv.Kind() == reflect.Interface {
				svk := reflect.Indirect(reflect.ValueOf(sv)).Kind()
				if svk != reflect.Struct {
					goto Error
				}
				objs = append(objs, sv.Interface())
			} else {
				if sv.Kind() != reflect.Struct {
					goto Error
				}
				objs = append(objs, sv.Addr().Interface())
			}
		}
	case reflect.Struct:
		if !v.CanAddr() {
			goto Error
		}
		objs = append(objs, v.Addr().Interface())
	}
	_, rtype, tableName, err = db.tableValueOf(name, objs[0])
	return objs, rtype, tableName, err
Error:
	return nil, nil, "", fmt.Errorf("%s: argument must be pointer to struct or slice of struct, got %T", name, obj)
}

func (db *DB) tableValueOf(name string, table interface{}) (rv reflect.Value, rt reflect.Type, tableName string, err error) {
	rv = reflect.Indirect(reflect.ValueOf(table))
	rt = rv.Type()
	if rt.Kind() != reflect.Struct {
		return rv, rt, "", fmt.Errorf("%s: a table must be struct type, got %v", name, rt)
	}
	tableName = db.tableName(rt)
	if tableName == "" {
		return rv, rt, "", fmt.Errorf("%s: a table isn't named", name)
	}
	return rv, rt, tableName, nil
}

func (db *DB) prepare(query string, args ...interface{}) (*sql.Stmt, error) {
	defer db.logger.Print(now(), query, args...)
	db.m.Lock()
	defer db.m.Unlock()
	if db.tx == nil {
		return db.db.Prepare(query)
	} else {
		return db.tx.Prepare(query)
	}
}

type selectFunc func(*sql.Rows, reflect.Type) (reflect.Value, error)

// TableNamer is an interface that is used to use a different table name.
type TableNamer interface {
	// TableName returns the table name on DB.
	TableName() string
}

// BeforeUpdater is an interface that hook for before Update.
type BeforeUpdater interface {
	// BeforeUpdate called before an update by DB.Update.
	// If it returns error, the update will be cancelled.
	BeforeUpdate() error
}

// AfterUpdater is an interface that hook for after Update.
type AfterUpdater interface {
	// AfterUpdate called after an update by DB.Update.
	AfterUpdate() error
}

// BeforeInserter is an interface that hook for before Insert.
type BeforeInserter interface {
	// BeforeInsert called before an insert by DB.Insert.
	// If it returns error, the insert will be cancelled.
	BeforeInsert() error
}

// AfterInserter is an interface that hook for after Insert.
type AfterInserter interface {
	// AfterInsert called after an insert by DB.Insert.
	AfterInsert() error
}

// BeforeDeleter is an interface that hook for before Delete.
type BeforeDeleter interface {
	// BeforeDelete called before a delete by DB.Delete.
	// If it returns error, the delete will be cancelled.
	BeforeDelete() error
}

// AfterDeleter is an interface that hook for after Delete.
type AfterDeleter interface {
	// AfterDelete called after a delete by DB.Delete.
	AfterDelete() error
}

// Raw represents a raw value.
// Raw value won't quoted.
type Raw *interface{}

// From represents a "FROM" statement.
type From struct {
	TableName string
}

// Distinct represents a "DISTINCT" statement.
type Distinct struct {
	columns []string
}

// Function represents a function of SQL.
type Function struct {
	// A function name.
	Name string

	// function arguments (optional).
	Args []interface{}
}

// Order represents a keyword for the "ORDER" clause of SQL.
type Order string

const (
	ASC  Order = "ASC"
	DESC Order = "DESC"
)

func (o Order) String() string {
	return string(o)
}

// Clause represents a clause of SQL.
type Clause uint

const (
	Where Clause = iota
	And
	Or
	OrderBy
	Limit
	Offset
	In
	Like
	Between
	Join
	LeftJoin
	IsNull
	IsNotNull
)

func (c Clause) String() string {
	if int(c) >= len(clauseStrings) {
		panic(fmt.Errorf("Clause %v is not defined", uint(c)))
	}
	return clauseStrings[c]
}

var clauseStrings = []string{
	Where:     "WHERE",
	And:       "AND",
	Or:        "OR",
	OrderBy:   "ORDER BY",
	Limit:     "LIMIT",
	Offset:    "OFFSET",
	In:        "IN",
	Like:      "LIKE",
	Between:   "BETWEEN",
	Join:      "JOIN",
	LeftJoin:  "LEFT JOIN",
	IsNull:    "IS NULL",
	IsNotNull: "IS NOT NULL",
}

// column represents a column name in query.
type column struct {
	table string // table name (optional).
	name  string // column name.
}

// expr represents a expression in query.
type expr struct {
	op     string      // operator.
	column *column     // column name.
	value  interface{} // value.
}

// orderBy represents a "ORDER BY" query.
type orderBy struct {
	column column // column name.
	order  Order  // direction.
}

// between represents a "BETWEEN" query.
type between struct {
	from interface{}
	to   interface{}
}

// Condition represents a condition for query.
type Condition struct {
	db        *DB
	parts     parts  // parts of the query.
	tableName string // table name (optional).
}

// newCondition returns a new Condition with Dialect.
func newCondition(db *DB) *Condition {
	return &Condition{db: db}
}

// Where adds "WHERE" clause to the Condition and returns it for method chain.
func (c *Condition) Where(cond interface{}, args ...interface{}) *Condition {
	return c.appendQueryByCondOrExpr("Where", 0, Where, cond, args...)
}

// And adds "AND" operator to the Condition and returns it for method chain.
func (c *Condition) And(cond interface{}, args ...interface{}) *Condition {
	return c.appendQueryByCondOrExpr("And", 100, And, cond, args...)
}

// Or adds "OR" operator to the Condition and returns it for method chain.
func (c *Condition) Or(cond interface{}, args ...interface{}) *Condition {
	return c.appendQueryByCondOrExpr("Or", 100, Or, cond, args...)
}

// In adds "IN" clause to the Condition and returns it for method chain.
func (c *Condition) In(args ...interface{}) *Condition {
	return c.appendQuery(100, In, args)
}

// Like adds "LIKE" clause to the Condition and returns it for method chain.
func (c *Condition) Like(arg string) *Condition {
	return c.appendQuery(100, Like, arg)
}

// Between adds "BETWEEN ... AND ..." clause to the Condition and returns it for method chain.
func (c *Condition) Between(from, to interface{}) *Condition {
	return c.appendQuery(100, Between, &between{from, to})
}

// IsNull adds "IS NULL" clause to the Condition and returns it for method chain.
func (c *Condition) IsNull() *Condition {
	return c.appendQuery(100, IsNull, nil)
}

// IsNotNull adds "IS NOT NULL" clause to the Condition and returns it for method chain.
func (c *Condition) IsNotNull() *Condition {
	return c.appendQuery(100, IsNotNull, nil)
}

// OrderBy adds "ORDER BY" clause to the Condition and returns it for method chain.
func (c *Condition) OrderBy(table, col interface{}, order ...interface{}) *Condition {
	order = append([]interface{}{table, col}, order...)
	orderbys := make([]orderBy, 0, 1)
	for len(order) > 0 {
		o, rest := order[0], order[1:]
		if _, ok := o.(string); ok {
			if len(rest) < 1 {
				panic(fmt.Errorf("OrderBy: few arguments"))
			}
			// OrderBy("column", genmai.DESC)
			orderbys = append(orderbys, c.orderBy(nil, o, rest[0]))
			order = rest[1:]
			continue
		}
		if len(rest) < 2 {
			panic(fmt.Errorf("OrderBy: few arguments"))
		}
		// OrderBy(tbl{}, "column", genmai.DESC)
		orderbys = append(orderbys, c.orderBy(o, rest[0], rest[1]))
		order = rest[2:]
	}
	return c.appendQuery(300, OrderBy, orderbys)
}

// Limit adds "LIMIT" clause to the Condition and returns it for method chain.
func (c *Condition) Limit(lim int) *Condition {
	return c.appendQuery(500, Limit, lim)
}

// Offset adds "OFFSET" clause to the Condition and returns it for method chain.
func (c *Condition) Offset(offset int) *Condition {
	return c.appendQuery(700, Offset, offset)
}

func (c *Condition) appendQuery(priority int, clause Clause, expr interface{}, args ...interface{}) *Condition {
	c.parts = append(c.parts, part{
		clause:   clause,
		expr:     expr,
		priority: priority,
	})
	return c
}

func (c *Condition) appendQueryByCondOrExpr(name string, order int, clause Clause, cond interface{}, args ...interface{}) *Condition {
	switch t := cond.(type) {
	case string, *Condition:
		args = append([]interface{}{t}, args...)
	default:
		v := reflect.Indirect(reflect.ValueOf(t))
		if v.Kind() != reflect.Struct {
			panic(fmt.Errorf("%s: first argument must be string or struct, got %T", name, t))
		}
		args = append([]interface{}{c.db.tableName(v.Type())}, args...)
	}
	switch len(args) {
	case 1: // Where(Where("id", "=", 1))
		switch t := args[0].(type) {
		case *Condition:
			cond = t
		case string:
			cond = &column{name: t}
		default:
			panic(fmt.Errorf("%s: first argument must be string or *Condition if args not given, got %T", name, t))
		}
	case 2: // Where(&Table{}, "id")
		cond = &column{
			table: fmt.Sprint(args[0]),
			name:  fmt.Sprint(args[1]),
		}
	case 3: // Where("id", "=", 1)
		cond = &expr{
			op: fmt.Sprint(args[1]),
			column: &column{
				name: fmt.Sprint(args[0]),
			},
			value: args[2],
		}
	case 4: // Where(&Table{}, "id", "=", 1)
		cond = &expr{
			op: fmt.Sprint(args[2]),
			column: &column{
				table: fmt.Sprint(args[0]),
				name:  fmt.Sprint(args[1]),
			},
			value: args[3],
		}
	default:
		panic(fmt.Errorf("%s: arguments expect between 1 and 4, got %v", name, len(args)))
	}
	return c.appendQuery(order, clause, cond)
}

func (c *Condition) orderBy(table, col, order interface{}) orderBy {
	o := orderBy{
		column: column{
			name: fmt.Sprint(col),
		},
		order: Order(fmt.Sprint(order)),
	}
	if table != nil {
		rt := reflect.TypeOf(table)
		for rt.Kind() == reflect.Ptr {
			rt = rt.Elem()
		}
		o.column.table = c.db.tableName(rt)
	}
	return o
}

func (c *Condition) build(numHolders int, inner bool) (queries []string, args []interface{}) {
	sort.Sort(c.parts)
	for _, p := range c.parts {
		if !(inner && p.clause == Where) {
			queries = append(queries, p.clause.String())
		}
		switch e := p.expr.(type) {
		case *expr:
			col := ColumnName(c.db.dialect, e.column.table, e.column.name)
			queries = append(queries, col, e.op, c.db.dialect.PlaceHolder(numHolders))
			args = append(args, e.value)
			numHolders++
		case []orderBy:
			o := e[0]
			queries = append(queries, ColumnName(c.db.dialect, o.column.table, o.column.name), o.order.String())
			if len(e) > 1 {
				for _, o := range e[1:] {
					queries = append(queries, ",", ColumnName(c.db.dialect, o.column.table, o.column.name), o.order.String())
				}
			}
		case *column:
			col := ColumnName(c.db.dialect, e.table, e.name)
			queries = append(queries, col)
		case []interface{}:
			e = flatten(e)
			holders := make([]string, len(e))
			for i := 0; i < len(e); i++ {
				holders[i] = c.db.dialect.PlaceHolder(numHolders)
				numHolders++
			}
			queries = append(queries, "(", strings.Join(holders, ", "), ")")
			args = append(args, e...)
		case *between:
			queries = append(queries, c.db.dialect.PlaceHolder(numHolders), "AND", c.db.dialect.PlaceHolder(numHolders+1))
			args = append(args, e.from, e.to)
			numHolders += 2
		case *Condition:
			q, a := e.build(numHolders, true)
			queries = append(append(append(queries, "("), q...), ")")
			args = append(args, a...)
		case *JoinCondition:
			var leftTableName string
			if e.leftTableName == "" {
				leftTableName = c.tableName
			} else {
				leftTableName = e.leftTableName
			}
			queries = append(queries,
				c.db.dialect.Quote(e.tableName), "ON",
				ColumnName(c.db.dialect, leftTableName, e.left), e.op, ColumnName(c.db.dialect, e.tableName, e.right))
		case nil:
			// ignore.
		default:
			queries = append(queries, c.db.dialect.PlaceHolder(numHolders))
			args = append(args, e)
			numHolders++
		}
	}
	return queries, args
}

// JoinCondition represents a condition of "JOIN" query.
type JoinCondition struct {
	db            *DB
	leftTableName string // A table name of 'to be joined'.
	tableName     string // A table name of 'to join'.
	op            string // A operator of expression in "ON" clause.
	left          string // A left column name of operator.
	right         string // A right column name of operator.
	clause        Clause // A type of join clause ("JOIN" or "LEFT JOIN")
}

// Join adds table name to the JoinCondition of "JOIN".
// If table isn't direct/indirect struct type, it panics.
func (jc *JoinCondition) Join(table interface{}) *JoinCondition {
	return jc.join(Join, table)
}

// LeftJoin adds table name to the JoinCondition of "LEFT JOIN".
// If table isn't direct/indirect struct type, it panics.
func (jc *JoinCondition) LeftJoin(table interface{}) *JoinCondition {
	return jc.join(LeftJoin, table)
}

// On adds "[LEFT] JOIN ... ON" clause to the Condition and returns it for method chain.
func (jc *JoinCondition) On(larg interface{}, args ...string) *Condition {
	var lcolumn string
	switch rv := reflect.ValueOf(larg); rv.Kind() {
	case reflect.String:
		lcolumn = rv.String()
	default:
		for rv.Kind() == reflect.Ptr {
			rv = rv.Elem()
		}
		if rv.Kind() != reflect.Struct {
			panic(fmt.Errorf("On: first argument must be string or struct, got %v", rv.Type()))
		}
		jc.leftTableName = jc.db.tableName(rv.Type())
		lcolumn, args = args[0], args[1:]
	}
	switch len(args) {
	case 0:
		jc.left, jc.op, jc.right = lcolumn, "=", lcolumn
	case 2:
		jc.left, jc.op, jc.right = lcolumn, args[0], args[1]
	default:
		panic(fmt.Errorf("On: arguments expect 1 or 3, got %v", len(args)+1))
	}
	c := newCondition(jc.db)
	c.parts = append(c.parts, part{
		clause:   jc.clause,
		expr:     jc,
		priority: -100,
	})
	return c
}

func (jc *JoinCondition) join(joinClause Clause, table interface{}) *JoinCondition {
	t := reflect.Indirect(reflect.ValueOf(table)).Type()
	if t.Kind() != reflect.Struct {
		panic(fmt.Errorf("%v: a table must be struct type, got %v", joinClause, t))
	}
	jc.tableName = jc.db.tableName(t)
	jc.clause = joinClause
	return jc
}

// part represents a part of query.
type part struct {
	clause Clause
	expr   interface{}

	// a order for sort. A lower value is a high-priority.
	priority int
}

// parts is for sort.Interface.
type parts []part

func (ps parts) Len() int {
	return len(ps)
}

func (ps parts) Less(i, j int) bool {
	return ps[i].priority < ps[j].priority
}

func (ps parts) Swap(i, j int) {
	ps[i], ps[j] = ps[j], ps[i]
}


text:
package test;

import java.util.Date;

public class Product {
    private Long id;

    private String productName;

    private String productDescripton;

    private String productDim;

    private Integer productView;

    private Integer productRank;

    private Integer productStatus;

    private Integer productCount;

    private String productUrl;

    private Integer productUrlClick;

    private String productPriceMark;

    private String productUnit;

    private Long productTypeId;

    private Long shopId;

    private Long productPrice;

    private String currenciesType;

    private String productEnName;

    private String productEnDescription;

    private String productEnDim;

    private Long userId;

    private Date createTime;

    private Long productSubtypeId;

    private String productTag;

    private String readFlag;

    private String delFlag;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName == null ? null : productName.trim();
    }

    public String getProductDescripton() {
        return productDescripton;
    }

    public void setProductDescripton(String productDescripton) {
        this.productDescripton = productDescripton == null ? null : productDescripton.trim();
    }

    public String getProductDim() {
        return productDim;
    }

    public void setProductDim(String productDim) {
        this.productDim = productDim == null ? null : productDim.trim();
    }

    public Integer getProductView() {
        return productView;
    }

    public void setProductView(Integer productView) {
        this.productView = productView;
    }

    public Integer getProductRank() {
        return productRank;
    }

    public void setProductRank(Integer productRank) {
        this.productRank = productRank;
    }

    public Integer getProductStatus() {
        return productStatus;
    }

    public void setProductStatus(Integer productStatus) {
        this.productStatus = productStatus;
    }

    public Integer getProductCount() {
        return productCount;
    }

    public void setProductCount(Integer productCount) {
        this.productCount = productCount;
    }

    public String getProductUrl() {
        return productUrl;
    }

    public void setProductUrl(String productUrl) {
        this.productUrl = productUrl == null ? null : productUrl.trim();
    }

    public Integer getProductUrlClick() {
        return productUrlClick;
    }

    public void setProductUrlClick(Integer productUrlClick) {
        this.productUrlClick = productUrlClick;
    }

    public String getProductPriceMark() {
        return productPriceMark;
    }

    public void setProductPriceMark(String productPriceMark) {
        this.productPriceMark = productPriceMark == null ? null : productPriceMark.trim();
    }

    public String getProductUnit() {
        return productUnit;
    }

    public void setProductUnit(String productUnit) {
        this.productUnit = productUnit == null ? null : productUnit.trim();
    }

    public Long getProductTypeId() {
        return productTypeId;
    }

    public void setProductTypeId(Long productTypeId) {
        this.productTypeId = productTypeId;
    }

    public Long getShopId() {
        return shopId;
    }

    public void setShopId(Long shopId) {
        this.shopId = shopId;
    }

    public Long getProductPrice() {
        return productPrice;
    }

    public void setProductPrice(Long productPrice) {
        this.productPrice = productPrice;
    }

    public String getCurrenciesType() {
        return currenciesType;
    }

    public void setCurrenciesType(String currenciesType) {
        this.currenciesType = currenciesType == null ? null : currenciesType.trim();
    }

    public String getProductEnName() {
        return productEnName;
    }

    public void setProductEnName(String productEnName) {
        this.productEnName = productEnName == null ? null : productEnName.trim();
    }

    public String getProductEnDescription() {
        return productEnDescription;
    }

    public void setProductEnDescription(String productEnDescription) {
        this.productEnDescription = productEnDescription == null ? null : productEnDescription.trim();
    }

    public String getProductEnDim() {
        return productEnDim;
    }

    public void setProductEnDim(String productEnDim) {
        this.productEnDim = productEnDim == null ? null : productEnDim.trim();
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Long getProductSubtypeId() {
        return productSubtypeId;
    }

    public void setProductSubtypeId(Long productSubtypeId) {
        this.productSubtypeId = productSubtypeId;
    }

    public String getProductTag() {
        return productTag;
    }

    public void setProductTag(String productTag) {
        this.productTag = productTag == null ? null : productTag.trim();
    }

    public String getReadFlag() {
        return readFlag;
    }

    public void setReadFlag(String readFlag) {
        this.readFlag = readFlag == null ? null : readFlag.trim();
    }

    public String getDelFlag() {
        return delFlag;
    }

    public void setDelFlag(String delFlag) {
        this.delFlag = delFlag == null ? null : delFlag.trim();
    }
}


text:
<readable><title>1259936608_e3f0064f23</title><content>
A little girl with arms outstretched plays with others at a sprinkler park .
Children play in a water fountain .
Children playing in public waterspouts .
The two young girls , one wearing a skirt and the other wearing shorts , are playing in a bubbling fountain .
Two kids playing in a fountain at a water park .
</content></readable>


text:
// Copyright (c) Umbraco.
// See LICENSE for more details.

using System;
using System.Collections.Generic;
using System.Globalization;
using Umbraco.Cms.Core.Semver;

namespace Umbraco.Extensions
{
    public static class VersionExtensions
    {
        public static Version GetVersion(this SemVersion semVersion, int maxParts = 4)
        {
            int build = 0;
            int.TryParse(semVersion.Build, NumberStyles.Integer, CultureInfo.InvariantCulture, out build);

            if (maxParts >= 4)
            {
                return new Version(semVersion.Major, semVersion.Minor, semVersion.Patch, build);
            }
            if (maxParts == 3)
            {
                return new Version(semVersion.Major, semVersion.Minor, semVersion.Patch);
            }

            return new Version(semVersion.Major, semVersion.Minor);
        }

        public static Version SubtractRevision(this Version version)
        {
            var parts = new List<int>(new[] {version.Major, version.Minor, version.Build, version.Revision});

            //remove all prefixed zero parts
            while (parts[0] <= 0)
            {
                parts.RemoveAt(0);
                if (parts.Count == 0) break;
            }

            for (int index = 0; index < parts.Count; index++)
            {
                var part = parts[index];
                if (part <= 0)
                {
                    parts.RemoveAt(index);
                    index++;
                }
                else
                {
                    //break when there isn't a zero part
                    break;
                }
            }

            if (parts.Count == 0) throw new InvalidOperationException("Cannot subtract a revision from a zero version");

            var lastNonZero = parts.FindLastIndex(i => i > 0);

            //subtract 1 from the last non-zero
            parts[lastNonZero] = parts[lastNonZero] - 1;

            //the last non zero is actually the revision so we can just return
            if (lastNonZero == (parts.Count -1))
            {
                return FromList(parts);
            }

            //the last non zero isn't the revision so the remaining zero's need to be replaced with int.max
            for (var i = lastNonZero + 1; i < parts.Count; i++)
            {
                parts[i] = int.MaxValue;
            }

            return FromList(parts);
        }

        private static Version FromList(IList<int> parts)
        {
            while (parts.Count < 4)
            {
                parts.Insert(0, 0);
            }
            return new Version(parts[0], parts[1], parts[2], parts[3]);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Utilities;

namespace PowerShellTools.Repl {
#if INTERACTIVE_WINDOW
    using IReplWindow = IInteractiveWindow;
#elif POWERSHELL
    using IReplWindow = IPowerShellReplWindow;
#endif

    /// <summary>
    /// Provides access to creating or finding existing REPL windows.
    /// </summary>
#if INTERACTIVE_WINDOW
    public interface IInteractiveWindowProvider {
#elif POWERSHELL
    public interface IPowerShellReplWindowProvider
    {
#else
    public interface IReplWindowProvider {
#endif
        /// <summary>
        /// Creates a REPL window and returns a ToolWindowPane which implements IReplWindow.  An IReplEvaluatorProvider must exist
        /// to respond and create the specified REPL ID.
        ///
        /// The returned object is also a ToolWindowPane and can be cast for access to control the docking with VS.
        /// </summary>
        IReplWindow CreateReplWindow(IContentType/*!*/ contentType, string/*!*/ title, Guid languageServiceGuid, string replId);

        /// <summary>
        /// Finds the REPL w/ the specified ID or returns null if the window hasn't been created.  An IReplEvaluatorProvider must exist
        /// to respond and create the specified REPL ID.
        ///
        /// The returned object is also a ToolWindowPane and can be cast for access to control the docking with VS.
        /// </summary>
        IReplWindow FindReplWindow(string replId);

        /// <summary>
        /// Returns this list of repl windows currently loaded.
        /// </summary>
        /// <returns></returns>
        IEnumerable<IReplWindow> GetReplWindows();
    }
}


text:
Working with Forms
==================

> Note: This section is under development.

The primary way of using forms in Yii is through [[yii\widgets\ActiveForm]]. This approach should be preferred when
the form is based upon  a model. Additionally, there are some useful methods in [[yii\helpers\Html]] that are typically
used for adding buttons and help text to any form.

When creating model-based forms, the first step is to define the model itself. The model can be either based upon the
Active Record class, or the more generic Model class. For this login example, a generic model will be used:

```php
use yii\base\Model;

class LoginForm extends Model
{
    public $username;
    public $password;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['username', 'password'], 'required'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     */
    public function validatePassword()
    {
        $user = User::findByUsername($this->username);
        if (!$user || !$user->validatePassword($this->password)) {
            $this->addError('password', 'Incorrect username or password.');
        }
    }

    /**
     * Logs in a user using the provided username and password.
     * @return boolean whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            $user = User::findByUsername($this->username);
            return true;
        } else {
            return false;
        }
    }
}
```

The controller will pass an instance of that model to the view, wherein the [[yii\widgets\ActiveForm|ActiveForm]] widget is used:

```php
use yii\helpers\Html;
use yii\widgets\ActiveForm;

<?php $form = ActiveForm::begin([
    'id' => 'login-form',
    'options' => ['class' => 'form-horizontal'],
]) ?>
    <?= $form->field($model, 'username') ?>
    <?= $form->field($model, 'password')->passwordInput() ?>

    <div class="form-group">
        <div class="col-lg-offset-1 col-lg-11">
            <?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
        </div>
    </div>
<?php ActiveForm::end() ?>
```

In the above code, [[yii\widgets\ActiveForm::begin()|ActiveForm::begin()]] not only creates a form instance, but also marks the beginning of the form.
All of the content placed between [[yii\widgets\ActiveForm::begin()|ActiveForm::begin()]] and
[[yii\widgets\ActiveForm::end()|ActiveForm::end()]] will be wrapped within the `<form>` tag.
As with any widget, you can specify some options as to how the widget should be configured by passing an array to
the `begin` method. In this case, an extra CSS class and identifying ID are passed to be used in the opening `<form>` tag.

In order to create a form element in the form, along with the element's label, and any application JavaScript validation,
the [[yii\widgets\ActiveForm::field()|ActiveForm::field()]] method of the Active Form widget is called.
When the invocation of this method is echoed directly, the result is a regular (text) input.
To customize the output, you can chain additional methods to this call:

```php
<?= $form->field($model, 'password')->passwordInput() ?>

// or

<?= $form->field($model, 'username')->textInput()->hint('Please enter your name')->label('Name') ?>
```

This will create all the `<label>`, `<input>` and other tags according to the template defined by the form field.
To add these tags yourself you can use the `Html` helper class.

If you want to use one of HTML5 fields you may specify input type directly like the following:

```php
<?= $form->field($model, 'email')->input('email') ?>
```

Specifying the attribute of the model can be done in more sophisticated ways. For example when an attribute may
take an array value when uploading multiple files or selecting multiple items you may specify it by appending `[]`
to the attribute name:

```php
// allow multiple files to be uploaded:
echo $form->field($model, 'uploadFile[]')->fileInput(['multiple'=>'multiple']);

// allow multiple items to be checked:
echo $form->field($model, 'items[]')->checkboxList(['a' => 'Item A', 'b' => 'Item B', 'c' => 'Item C']);
```

> **Tip**: in order to style required fields with asterisk you can use the following CSS:
>
```css
div.required label:after {
    content: " *";
    color: red;
}
```

Handling multiple models with a single form
-------------------------------------------

Sometimes you need to handle multiple models of the same kind in a single form. For example, multiple settings where
each setting is stored as name-value and is represented by `Setting` model. The
following shows how to implement it with Yii.

Let's start with controller action:

```php
namespace app\controllers;

use Yii;
use yii\base\Model;
use yii\web\Controller;
use app\models\Setting;

class SettingsController extends Controller
{
    // ...

    public function actionUpdate()
    {
        $settings = Setting::find()->indexBy('id')->all();

        if (Model::loadMultiple($settings, Yii::$app->request->post()) && Model::validateMultiple($settings)) {
            foreach ($settings as $setting) {
                $setting->save(false);
            }

            return $this->redirect('index');
        }

        return $this->render('update', ['settings' => $settings]);
    }
}
```

In the code above we're using `indexBy` when retrieving models from database to make array indexed by model ids. These
will be later used to identify form fields. `loadMultiple` fills multiple modelds with the form data coming from POST
and `validateMultiple` validates all models at once. In order to skip validation when saving we're passing `false` as
a parameter to `save`.

Now the form that's in `update` view:

```php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;

$form = ActiveForm::begin();

foreach ($settings as $index => $setting) {
    echo Html::encode($setting->name) . ': ' . $form->field($setting, "[$index]value");
}

ActiveForm::end();
```

Here for each setting we are rendering name and an input with a value. It is important to add a proper index
to input name since that is how `loadMultiple` determines which model to fill with which values.


text:
package builder.api_json

import core.{Importer, ServiceFetcher, TypesProvider, TypesProviderEnum, TypesProviderModel, TypesProviderUnion, VersionMigration}
import lib.{Methods, Primitives, ServiceConfiguration, Text, UrlKey}
import io.apibuilder.spec.v0.models._
import lib.Methods.{MethodsNotAcceptingBodies, supportsBody}
import play.api.libs.json._

import scala.util.{Failure, Success, Try}

case class ServiceBuilder(
  migration: VersionMigration
) {

  def apply(
    config: ServiceConfiguration,
    apiJson: String,
    fetcher: ServiceFetcher
  ): Service = {
    val jsValue = Json.parse(apiJson)
    apply(config, InternalServiceForm(jsValue, fetcher))
  }

  def apply(
    config: ServiceConfiguration,
    internal: InternalServiceForm
  ): Service = {

    val name = internal.name.getOrElse(sys.error("Missing name"))
    val key = internal.key.getOrElse { UrlKey.generate(name) }
    val namespace = internal.namespace.getOrElse { config.applicationNamespace(key) }

    val resolver = TypeResolver(
      defaultNamespace = Some(namespace),
      RecursiveTypesProvider(internal)
    )

    val imports = internal.imports.map { ImportBuilder(internal.fetcher, _) }.sortWith(_.uri.toLowerCase < _.uri.toLowerCase)
    val headers = internal.headers.map { HeaderBuilder(resolver, _) }
    val enums = internal.enums.map { EnumBuilder(_) }.sortWith(_.name.toLowerCase < _.name.toLowerCase)
    val interfaces = internal.interfaces.map { InterfaceBuilder(_) }.sortWith(_.name.toLowerCase < _.name.toLowerCase)
    val unions = internal.unions.map { UnionBuilder(_) }.sortWith(_.name.toLowerCase < _.name.toLowerCase)
    val models = internal.models.map { ModelBuilder(_) }.sortWith(_.name.toLowerCase < _.name.toLowerCase)
    val resources = internal.resources.map { ResourceBuilder(resolver, _) }.sortWith(_.`type`.toLowerCase < _.`type`.toLowerCase)
    val attributes = internal.attributes.map { AttributeBuilder(_) }
    val annotations = internal.annotations.map{ AnnotationsBuilder(_) }

    val info = internal.info match {
      case None => Info(
        contact = None,
        license = None
      )
      case Some(i) => InfoBuilder(i)
    }

    Service(
      apidoc = internal.apidoc.flatMap(_.version) match {
        case Some(v) => Apidoc(version = v)
        case None => Apidoc(version = io.apibuilder.spec.v0.Constants.Version)
      },
      info = info,
      name = name,
      namespace = namespace,
      organization = Organization(key = config.orgKey),
      application = Application(key = key),
      version = config.version,
      imports = imports,
      description = internal.description,
      baseUrl = internal.baseUrl,
      enums = enums,
      interfaces = interfaces,
      unions = unions,
      models = models,
      headers = headers,
      resources = resources,
      attributes = attributes,
      annotations = annotations ++ imports.flatMap(_.annotations).distinct
    )
  }

  object ResourceBuilder {

    private[api_json] case class Resolution(
      enum: Option[TypesProviderEnum] = None,
      model: Option[TypesProviderModel] = None,
      union: Option[TypesProviderUnion] = None
    ) {
      private[this] val all = Seq(enum, model, union).flatten
      assert(all.size <= 1, s"Cannot have more than 1 resolved item: $all")

      def isEmpty: Boolean = all.isEmpty
    }

    // @scala.annotation.tailrec
    def resolve(
      resolver: TypesProvider,
      name: String
    ): Resolution = {
      resolver.enums.find(o => o.name == name || o.fullName == name) match {
        case Some(enum) => {
          Resolution(enum = Some(enum))
        }
        case None => {
          resolver.models.find(o => o.name == name || o.fullName == name) match {
            case Some(model) => {
              Resolution(model = Some(model))
            }
            case None => {
              resolver.unions.find(o => o.name == name || o.fullName == name) match {
                case Some(union) => {
                  Resolution(union = Some(union))
                }
                case None => {
                  Resolution()
                }
              }
            }
          }
        }
      }
    }

    def apply(
      resolver: TypeResolver,
      internal: InternalResourceForm
    ): Resource = {
      val resolution = resolve(resolver.provider, internal.datatype.name)

      resolution.enum match {
        case Some(enum) => {
          val resourcePath = internal.path.getOrElse("/" + enum.plural)
          Resource(
            `type` = internal.datatype.label,
            plural = enum.plural,
            path = Some(resourcePath),
            description = internal.description,
            deprecation = internal.deprecation.map(DeprecationBuilder(_)),
            operations = internal.operations.map(op => OperationBuilder(op, resourcePath, resolver)),
            attributes = internal.attributes.map { AttributeBuilder(_) }
          )
        }

        case None => {
          resolution.model match {
            case Some(model) => {
              val resourcePath = internal.path.getOrElse("/" + model.plural)
              Resource(
                `type` = internal.datatype.label,
                plural = model.plural,
                path = Some(resourcePath),
                description = internal.description,
                deprecation = internal.deprecation.map(DeprecationBuilder(_)),
                operations = internal.operations.map(op => OperationBuilder(op, resourcePath, resolver, model = Some(model))),
                attributes = internal.attributes.map { AttributeBuilder(_) }
              )
            }

            case None => {
              resolution.union match {
                case Some(union) => {
                  val resourcePath = internal.path.getOrElse("/" + union.plural)
                  Resource(
                    `type` = internal.datatype.label,
                    plural = union.plural,
                    path = Some(resourcePath),
                    description = internal.description,
                    deprecation = internal.deprecation.map(DeprecationBuilder(_)),
                    operations = internal.operations.map(op => OperationBuilder(op, resourcePath, resolver, union = Some(union))),
                    attributes = internal.attributes.map { AttributeBuilder(_) }
                  )
                }
                case None => {
                  val resourcePath = internal.path.getOrElse("")
                  Resource(
                    `type` = internal.datatype.label,
                    plural = Text.pluralize(internal.datatype.name),
                    path = Some(resourcePath),
                    description = internal.description,
                    deprecation = internal.deprecation.map(DeprecationBuilder(_)),
                    operations = internal.operations.map(op => OperationBuilder(op, resourcePath, resolver)),
                    attributes = internal.attributes.map { AttributeBuilder(_) }
                  )
                }
              }
            }
          }
        }
      }
    }

  }

  object OperationBuilder {

    /**
      * Historically apibuilder placed parameters by default for GET and DELETE in
      * the query parameters. Maintain this convention to avoid breaking APIs
      */
    private[this] def defaultParameterLocation(verb: String): ParameterLocation = {
      if (supportsBody(verb)) {
        verb.toUpperCase().trim match {
          case "DELETE" => ParameterLocation.Query
          case _ => ParameterLocation.Form
        }
      } else {
        ParameterLocation.Query
      }
    }

    def apply(
      internal: InternalOperationForm,
      resourcePath: String,
      resolver: TypeResolver,
      model: Option[TypesProviderModel] = None,
      union: Option[TypesProviderUnion] = None
    ): Operation = {
      val method = internal.method.getOrElse("")
      val defaultLocation = if (internal.body.isDefined) {
        ParameterLocation.Query
      } else {
        internal.method match {
          case None => ParameterLocation.Form
          case Some(m) => defaultParameterLocation(m)
        }
      }

      val pathParameters = internal.namedPathParameters.map { name =>
        internal.parameters.find(_.name.contains(name)) match {
          case None => {
            val datatypeLabel: String = model.flatMap(_.fields.find(_.name == name)) match {
              case Some(field) => field.`type`
              case None => {
                union.flatMap(commonField(resolver.provider, _, name)).getOrElse {
                  Primitives.String.toString
                }
              }
            }
            ParameterBuilder.fromPath(name, datatypeLabel)
          }
          case Some(declared) => {
            // Path parameter was declared in the parameters
            // section. Use the explicit information provided in the
            // specification
            ParameterBuilder(declared, ParameterLocation.Path)
          }
        }
      }

      val internalParams = internal.parameters.filter(p => !pathParameters.exists(_.name == p.name.get)).map { p =>
        ParameterBuilder(p, defaultLocation)
      }

      val fullPath = Seq(
        resourcePath,
        internal.path.getOrElse("")
      ).filter(!_.isEmpty).mkString("") match {
        case "" => "/"
        case p => p
      }

      Operation(
        method = Method(method),
        path = fullPath,
        description = internal.description,
        deprecation = internal.deprecation.map(DeprecationBuilder(_)),
        body = internal.body.map { BodyBuilder(_) },
        parameters = pathParameters ++ internalParams,
        responses = internal.responses.map { ResponseBuilder(resolver, _) },
        attributes = internal.attributes.map { AttributeBuilder(_) }
      )
    }

    /**
      * If all types agree on the datatype for the field with the specified Name,
      * returns the field. Otherwise, returns None
      */
    private def commonField(resolver: TypesProvider, union: TypesProviderUnion, fieldName: String): Option[String] = {
      val fieldTypes: Seq[String] = union.types.map { u =>
        Primitives(u.`type`) match {
          case Some(p) => p.toString
          case None => {
            resolver.models.find { m => m.name == u.`type` || m.fullName == u.`type` } match {
              case None => {
                Primitives.String.toString
              }
              case Some(m) => {
                m.fields.find(_.name == fieldName) match {
                  case None => {
                    Primitives.String.toString
                  }
                  case Some(f) => {
                    f.`type`
                  }
                }
              }
            }
          }
        }
      }

      fieldTypes.distinct.toList match {
        case single :: Nil => Some(single)
        case _ => None
      }
    }

  }

  object BodyBuilder {

    def apply(ib: InternalBodyForm): Body = {
      ib.datatype match {
        case Left(errs) => sys.error("Body missing type: " + errs.mkString(", "))
        case Right(datatype) => Body(
          `type` = datatype.label,
          description = ib.description,
          deprecation = ib.deprecation.map(DeprecationBuilder(_)),
          attributes = ib.attributes.map { AttributeBuilder(_) }
        )
      }
    }

  }

  object DeprecationBuilder {

    def apply(internal: InternalDeprecationForm): Deprecation = {
      Deprecation(description = internal.description)
    }

  }

  object EnumBuilder {

    def apply(ie: InternalEnumForm): Enum = {
      Enum(
        name = ie.name,
        plural = ie.plural,
        description = ie.description,
        deprecation = ie.deprecation.map(DeprecationBuilder(_)),
        values = ie.values.map { iv =>
          EnumValue(
            name = iv.name.get,
            value = iv.value,
            description = iv.description,
            deprecation = iv.deprecation.map(DeprecationBuilder(_))
          )
        },
        attributes = ie.attributes.map { AttributeBuilder(_) }
      )
    }

  }

  object UnionBuilder {

    def apply(internal: InternalUnionForm): Union = {
      Union(
        name = internal.name,
        plural = internal.plural,
        discriminator = internal.discriminator,
        description = internal.description,
        deprecation = internal.deprecation.map(DeprecationBuilder(_)),
        interfaces = internal.interfaces,
        types = internal.types.map { it =>
          val typ = rightOrError(it.datatype)
          UnionType(
            `type` = typ.label,
            description = it.description,
            deprecation = it.deprecation.map(DeprecationBuilder(_)),
            default = it.default,
            discriminatorValue = Some(
              it.discriminatorValue.getOrElse(typ.name)
            )
          )
        },
        attributes = internal.attributes.map { AttributeBuilder(_) }
      )
    }

  }

  object HeaderBuilder {

    def apply(resolver: TypeResolver, ih: InternalHeaderForm): Header = {
      Header(
        name = ih.name.get,
        `type` = rightOrError(ih.datatype).label,
        required = ih.required,
        description = ih.description,
        deprecation = ih.deprecation.map(DeprecationBuilder(_)),
        default = ih.default,
        attributes = ih.attributes.map(AttributeBuilder(_)),
      )
    }

  }

  object InfoBuilder {

    def apply(internal: InternalInfoForm): Info = {
      Info(
        contact = internal.contact.flatMap { c =>
          if (c.name.isEmpty && c.email.isEmpty && c.url.isEmpty) {
            None
          } else {
            Some(
              Contact(
                name = c.name,
                url = c.url,
                email = c.email
              )
            )
          }
        },
        license = internal.license.map { l =>
          License(
            name = l.name.getOrElse {
              sys.error("License is missing name")
            },
            url = l.url
          )
        }
      )
    }
  }

  object ImportBuilder {

    def apply(fetcher: ServiceFetcher, internal: InternalImportForm): Import = {
      Importer(fetcher, internal.uri.get).fetched match {
        case Left(errors) => {
          sys.error("Errors in import: " + errors)
        }
        case Right(service) => {
          Import(
            uri = internal.uri.get,
            organization = service.organization,
            application = service.application,
            namespace = service.namespace,
            version = service.version,
            enums = service.enums.map(_.name),
            unions = service.unions.map(_.name),
            interfaces = service.interfaces.map(_.name),
            models = service.models.map(_.name),
            annotations = service.annotations
          )
        }
      }
    }

  }

  object InterfaceBuilder {

    def apply(im: InternalInterfaceForm): Interface = {
      Interface(
        name = im.name,
        plural = im.plural,
        description = im.description,
        deprecation = im.deprecation.map(DeprecationBuilder(_)),
        fields = im.fields.map { FieldBuilder(_) },
        attributes = im.attributes.map { AttributeBuilder(_) }
      )
    }

  }

  object ModelBuilder {

    def apply(im: InternalModelForm): Model = {
      Model(
        name = im.name,
        plural = im.plural,
        description = im.description,
        deprecation = im.deprecation.map(DeprecationBuilder(_)),
        fields = im.fields.map { FieldBuilder(_) },
        interfaces = im.interfaces,
        attributes = im.attributes.map { AttributeBuilder(_) }
      )
    }

  }

  object ResponseBuilder {

    def apply(resolver: TypeResolver, internal: InternalResponseForm): Response = {
      Response(
        code = Try(internal.code.toInt) match {
          case Success(code) => ResponseCodeInt(code)
          case Failure(_) => ResponseCodeOption(internal.code)
        },
        `type` = rightOrError(internal.datatype).label,
        headers = internal.headers.map { HeaderBuilder(resolver, _) }.toList match {
          case Nil => None
          case headers => Some(headers)
        },
        description = internal.description,
        deprecation = internal.deprecation.map(DeprecationBuilder(_)),
        attributes = Some(internal.attributes.map { AttributeBuilder(_) })
      )
    }

  }

  object ParameterBuilder {

    def fromPath(name: String, datatypeLabel: String): Parameter = {
      Parameter(
        name = name,
        `type` = datatypeLabel,
        location = ParameterLocation.Path,
        required = true
      )
    }

    def apply(internal: InternalParameterForm, defaultLocation: ParameterLocation): Parameter = {
      Parameter(
        name = internal.name.get,
        `type` = rightOrError(internal.datatype).label,
        location = internal.location.map(ParameterLocation(_)).getOrElse(defaultLocation),
        description = internal.description,
        deprecation = internal.deprecation.map(DeprecationBuilder(_)),
        required = if (migration.makeFieldsWithDefaultsRequired()) {
          internal.default match {
            case None => internal.required
            case Some(_) => true
          }
        } else {
          internal.required
        },
        default = internal.default,
        minimum = internal.minimum,
        maximum = internal.maximum,
        example = internal.example
      )
    }

  }

  object FieldBuilder {
    def apply(
      internal: InternalFieldForm
    ): Field = {
      Field(
        name = internal.name.get,
        `type` = rightOrError(internal.datatype).label,
        description = internal.description,
        deprecation = internal.deprecation.map(DeprecationBuilder(_)),
        default = internal.default,
        required = if (migration.makeFieldsWithDefaultsRequired()) {
          internal.default match {
            case None => internal.required
            case Some(_) => true
          }
        } else {
          internal.required
        },
        minimum = internal.minimum,
        maximum = internal.maximum,
        example = internal.example,
        attributes = internal.attributes.map { AttributeBuilder(_) },
        annotations = internal.annotations
      )
    }

  }

  object AttributeBuilder {
    def apply(
      internal: InternalAttributeForm
    ): Attribute = {
      Attribute(
        name = internal.name.get,
        value = internal.value.get,
        description = internal.description,
        deprecation = internal.deprecation.map(DeprecationBuilder(_))
      )
    }
  }

  object AnnotationsBuilder {
    def apply(
      internal: InternalAnnotationForm
    ): Annotation = {
      Annotation(
        name = internal.name,
        description = internal.description,
        deprecation = internal.deprecation.map(DeprecationBuilder(_))
      )
    }
  }

  private[this] def rightOrError[T](value: Either[Seq[String], T]): T = {
    value match {
      case Left(errors) => sys.error("Unexpected errors: " + errors.mkString(", "))
      case Right(v) => v
    }
  }
}


text:
  Implementation of the Dasein Cloud API for vSphere

  The Dasein Cloud API is released under the terms of the Artistic License 2.0.


text:
import { NgModule } from '@angular/core';
import { RouterModule, Routes, PreloadAllModules } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { ResetPasswordComponent } from './reset-password/reset-password.component';
import { RegisterComponent } from './register/register.component';
import { ConfirmComponent } from './confirm/confirm.component';
import { ConfirmEmailComponent } from './confirm-email/confirm-email.component';
import { NewPasswordComponent } from './new-password/new-password.component';

const routes: Routes = [
	{ path: 'login', component: LoginComponent },
	{ path: 'register', component: RegisterComponent },
	{ path: 'reset-password', component: ResetPasswordComponent },
	{ path: 'confirm/:token', component: ConfirmComponent },
	{ path: 'confirmEmail/:token', component: ConfirmEmailComponent },
	{ path: 'new-password/:token', component: NewPasswordComponent }
];

@NgModule({
	imports: [
		RouterModule.forChild(routes)
	],
	exports: [
		RouterModule
	]
})
export class UserRoutingModule {}


text:
<?xml version='1.0' encoding='UTF-8'?>
<user>
  <fullName>admin</fullName>
  <properties>
    <hudson.model.PaneStatusProperties>
      <collapsed/>
    </hudson.model.PaneStatusProperties>
    <jenkins.security.ApiTokenProperty>
      <apiToken>P4JYP5Vp7uLieaf5hhJqcl8luFotPeqQ4idMWB2KD/SIArhUAidNak2QaYz2JT9/</apiToken>
    </jenkins.security.ApiTokenProperty>
    <com.cloudbees.plugins.credentials.UserCredentialsProvider_-UserCredentialsProperty plugin="credentials@1.18">
      <domainCredentialsMap class="hudson.util.CopyOnWriteMap$Hash"/>
    </com.cloudbees.plugins.credentials.UserCredentialsProvider_-UserCredentialsProperty>
    <hudson.model.MyViewsProperty>
      <views>
        <hudson.model.AllView>
          <owner class="hudson.model.MyViewsProperty" reference="../../.."/>
          <name>All</name>
          <filterExecutors>false</filterExecutors>
          <filterQueue>false</filterQueue>
          <properties class="hudson.model.View$PropertyList"/>
        </hudson.model.AllView>
      </views>
    </hudson.model.MyViewsProperty>
    <hudson.search.UserSearchProperty>
      <insensitiveSearch>false</insensitiveSearch>
    </hudson.search.UserSearchProperty>
    <hudson.security.HudsonPrivateSecurityRealm_-Details>
      <passwordHash>#jbcrypt:$2a$10$s7vvZed8UoD55Zpx72LkyuBKWWwOduRIhoLCuAkhrYItflogaUeuS</passwordHash>
    </hudson.security.HudsonPrivateSecurityRealm_-Details>
    <hudson.tasks.Mailer_-UserProperty plugin="mailer@1.11">
      <emailAddress>admin@localhost</emailAddress>
    </hudson.tasks.Mailer_-UserProperty>
  </properties>
</user>


text:
package com.sksamuel.elastic4s

import zio.json._

import scala.annotation.implicitNotFound

package object ziojson {
  @implicitNotFound("No JsonEncoder for type ${T} found. Bring an implicit JsonEncoder[T] instance in scope")
  implicit def zioJsonIndexable[T](implicit encoder: JsonEncoder[T]): Indexable[T] = _.toJson

  @implicitNotFound("No JsonDecoder for type ${T} found. Bring an implicit JsonDecoder[T] instance in scope")
  implicit def zioJsonHitReader[T](implicit decoder: JsonDecoder[T]): HitReader[T] =
    _.sourceAsString.fromJson[T].left.map(new Throwable(_)).toTry

  @implicitNotFound("No JsonDecoder for type ${T} found. Bring an implicit JsonDecoder[T] instance in scope")
  implicit def zioJsonAggReader[T](implicit decoder: JsonDecoder[T]): AggReader[T] =
    _.fromJson[T].left.map(new Throwable(_)).toTry

  @implicitNotFound("No JsonEncoder for type ${T} found. Bring an implicit JsonEncoder[T] instance in scope")
  implicit def zioJsonParamSerializer[T](implicit encoder: JsonEncoder[T]): ParamSerializer[T] = _.toJson
}


text:
/**
 *     This code was auto-generated by a Codezu.
 *
 *     Changes to this file may cause incorrect behavior and will be lost if
 *     the code is regenerated.
 */
package com.mozu.api.contracts.core.thirdparty;

import java.util.List;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.joda.time.DateTime;
import com.mozu.api.contracts.core.thirdparty.InitializablePropertyValue;

/**
 *	Property value that can be initialized for a capability that uses shipping countries.
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class InitializableShippingCountryPropertyValue implements Serializable
{
	// Default Serial Version UID
	private static final long serialVersionUID = 1L;

	/**
	 * If true, the property value is initialized.
	 */
	protected Boolean initialized;

	public Boolean getInitialized() {
		return this.initialized;
	}

	public void setInitialized(Boolean initialized) {
		this.initialized = initialized;
	}

	/**
	 * Value of the initializable third-party capability property.
	 */
	protected String value;

	public String getValue() {
		return this.value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	/**
	 * Child value in a hierarchy of shipping country properties.
	 */
	protected List<InitializablePropertyValue> child;
	public List<InitializablePropertyValue> getChild() {
		return this.child;
	}
	public void setChild(List<InitializablePropertyValue> child) {
		this.child = child;
	}

}


text:
package org.apache.sqoop.testutil;

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

import static org.apache.commons.lang3.StringUtils.isEmpty;

public class ArgumentArrayBuilder {

  private static final String PROPERTY_PREFIX = "-D";

  private static final String OPTION_PREFIX = "--";

  private static final String TOOL_ARG_SEPARATOR = "--";

  private Map<String, Argument> properties;

  private Map<String, Argument> options;

  private Map<String, Argument> toolOptions;

  private boolean withCommonHadoopFlags;

  public ArgumentArrayBuilder() {
    properties = new HashMap<>();
    options = new HashMap<>();
    toolOptions = new HashMap<>();
  }

  public ArgumentArrayBuilder withProperty(String name, String value) {
    properties.put(name, new Argument(name, value));
    return this;
  }

  public ArgumentArrayBuilder withProperty(String name) {
    properties.put(name, new Argument(name));
    return this;
  }

  public ArgumentArrayBuilder withOption(String name, String value) {
    options.put(name, new Argument(name, value));
    return this;
  }

  public ArgumentArrayBuilder withOption(String name) {
    options.put(name, new Argument(name));
    return this;
  }

  public ArgumentArrayBuilder withToolOption(String name, String value) {
    toolOptions.put(name, new Argument(name, value));
    return this;
  }

  public ArgumentArrayBuilder withToolOption(String name) {
    toolOptions.put(name, new Argument(name));
    return this;
  }

  public ArgumentArrayBuilder with(ArgumentArrayBuilder otherBuilder) {
    properties.putAll(otherBuilder.properties);
    options.putAll(otherBuilder.options);
    toolOptions.putAll(otherBuilder.toolOptions);
    return this;
  }

  public ArgumentArrayBuilder withCommonHadoopFlags(boolean b) {
    withCommonHadoopFlags = b;
    return this;
  }

  public ArgumentArrayBuilder withCommonHadoopFlags() {
    withCommonHadoopFlags = true;
    return this;
  }

  /**
   * Transforms the given options, properties and toolOptions to the command line format Sqoop expects,
   * by adding dashes (--) and the capital D letter when it's necessary (in front of properties)
   * @return String array that can be used to run tests
   */
  public String[] build() {
    List<String> result = new ArrayList<>();
    if (withCommonHadoopFlags) {
      CommonArgs.addHadoopFlags(result);
    }
    if (!properties.isEmpty()) {
      Collections.addAll(result, createArgumentArrayFromProperties(properties.values()));
    }
    if (!options.isEmpty()) {
      Collections.addAll(result, createArgumentArrayFromOptions(options.values()));
    }
    if (!toolOptions.isEmpty()) {
      result.add(TOOL_ARG_SEPARATOR);
      Collections.addAll(result, createArgumentArrayFromOptions(toolOptions.values()));
    }
    return result.toArray(new String[result.size()]);
  }

  private String[] createArgumentArrayFromProperties(Iterable<Argument> properties) {
    List<String> result = new ArrayList<>();
    for (Argument property : properties) {
      result.add(PROPERTY_PREFIX);
      result.add(property.toString());
    }
    return result.toArray(new String[result.size()]);
  }

  private String[] createArgumentArrayFromOptions(Iterable<Argument> options) {
    List<String> result = new ArrayList<>();
    for (Argument option : options) {
      result.add(OPTION_PREFIX + option.getName());
      if (!isEmpty(option.getValue())) {
        result.add(option.getValue());
      }
    }
    return result.toArray(new String[result.size()]);
  }

  @Override
  public String toString() {
    return Arrays.toString(build());
  }
}


text:
Since it might not be desired to have the same material design theme for your
app, it is possible to update the base button theme by updating the different
button SCSS variables before importing and including the button styles. If you
have not done so, please read the pretty good write up in the
[theme documentation](/packages/theme#custom-theme) for all the detailed theming
information. It's also recommended to read the
[states documentation](/packages/states) to read about disable the ripple effect
or custom interaction states as well.


text:
namespace AsmResolver.DotNet.TestCases.NestedClasses
{
    public class TopLevelClass2
    {
        public class Nested3
        {
            public class Nested3Nested1
            {
            }

            public class Nested3Nested2
            {
            }
        }

        public class Nested4
        {
            public class Nested4Nested1
            {
            }

            public class Nested4Nested2
            {
            }
        }
    }
}