<commit_before>// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved.
// Use of this source code is governed by a LGPLv2.1
// license that can be found in the LICENSE file.

// +build linux

package lxc

// #include <lxc/lxccontainer.h>
import "C"

import (
	"fmt"
)

// Verbosity type
type Verbosity int

const (
	// Quiet makes some API calls not to write anything to stdout
	Quiet Verbosity = 1 << iota
	// Verbose makes some API calls write to stdout
	Verbose
)

// BackendStore type specifies possible backend types.
type BackendStore int

const (
	// Btrfs backendstore type
	Btrfs BackendStore = iota + 1
	// Directory backendstore type
	Directory
	// LVM backendstore type
	LVM
	// ZFS backendstore type
	ZFS
	// Aufs backendstore type
	Aufs
	// Overlayfs backendstore type
	Overlayfs
	// Loopback backendstore type
	Loopback
	// Best backendstore type
	Best
)

// BackendStore as string
func (t BackendStore) String() string {
	switch t {
	case Directory:
		return "dir"
	case ZFS:
		return "zfs"
	case Btrfs:
		return "btrfs"
	case LVM:
		return "lvm"
	case Aufs:
		return "aufs"
	case Overlayfs:
		return "overlayfs"
	case Loopback:
		return "loopback"
	case Best:
		return "best"
	}
	return "<INVALID>"
}

// State type specifies possible container states.
type State int

const (
	// STOPPED means container is not running
	STOPPED State = iota + 1
	// STARTING means container is starting
	STARTING
	// RUNNING means container is running
	RUNNING
	// STOPPING means container is stopping
	STOPPING
	// ABORTING means container is aborting
	ABORTING
	// FREEZING means container is freezing
	FREEZING
	// FROZEN means containe is frozen
	FROZEN
	// THAWED means container is thawed
	THAWED
)

var stateMap = map[string]State{
	"STOPPED":  STOPPED,
	"STARTING": STARTING,
	"RUNNING":  RUNNING,
	"STOPPING": STOPPING,
	"ABORTING": ABORTING,
	"FREEZING": FREEZING,
	"FROZEN":   FROZEN,
	"THAWED":   THAWED,
}

// State as string
func (t State) String() string {
	switch t {
	case STOPPED:
		return "STOPPED"
	case STARTING:
		return "STARTING"
	case RUNNING:
		return "RUNNING"
	case STOPPING:
		return "STOPPING"
	case ABORTING:
		return "ABORTING"
	case FREEZING:
		return "FREEZING"
	case FROZEN:
		return "FROZEN"
	case THAWED:
		return "THAWED"
	}
	return "<INVALID>"
}

// Taken from http://golang.org/doc/effective_go.html#constants

// ByteSize type
type ByteSize float64

const (
	_ = iota
	// KB - kilobyte
	KB ByteSize = 1 << (10 * iota)
	// MB - megabyte
	MB
	// GB - gigabyte
	GB
	// TB - terabyte
	TB
	// PB - petabyte
	PB
	// EB - exabyte
	EB
	// ZB - zettabyte
	ZB
	// YB - yottabyte
	YB
)

func (b ByteSize) String() string {
	switch {
	case b >= YB:
		return fmt.Sprintf("%.2fYB", b/YB)
	case b >= ZB:
		return fmt.Sprintf("%.2fZB", b/ZB)
	case b >= EB:
		return fmt.Sprintf("%.2fEB", b/EB)
	case b >= PB:
		return fmt.Sprintf("%.2fPB", b/PB)
	case b >= TB:
		return fmt.Sprintf("%.2fTB", b/TB)
	case b >= GB:
		return fmt.Sprintf("%.2fGB", b/GB)
	case b >= MB:
		return fmt.Sprintf("%.2fMB", b/MB)
	case b >= KB:
		return fmt.Sprintf("%.2fKB", b/KB)
	}
	return fmt.Sprintf("%.2fB", b)
}

// LogLevel type specifies possible log levels.
type LogLevel int

const (
	// TRACE priority
	TRACE LogLevel = iota
	// DEBUG priority
	DEBUG
	// INFO priority
	INFO
	// NOTICE priority
	NOTICE
	// WARN priority
	WARN
	// ERROR priority
	ERROR
	// CRIT priority
	CRIT
	// ALERT priority
	ALERT
	// FATAL priority
	FATAL
)

var logLevelMap = map[string]LogLevel{
	"TRACE":  TRACE,
	"DEBUG":  DEBUG,
	"INFO":   INFO,
	"NOTICE": NOTICE,
	"WARN":   WARN,
	"ERROR":  ERROR,
	"CRIT":   CRIT,
	"ALERT":  ALERT,
	"FATAL":  FATAL,
}

func (l LogLevel) String() string {
	switch l {
	case TRACE:
		return "TRACE"
	case DEBUG:
		return "DEBUG"
	case INFO:
		return "INFO"
	case NOTICE:
		return "NOTICE"
	case WARN:
		return "WARN"
	case ERROR:
		return "ERROR"
	case CRIT:
		return "CRIT"
	case ALERT:
		return "ALERT"
	case FATAL:
		return "FATAL"
	}
	return "NOTSET"
}

// CloneFlags type
type CloneFlags int

const (
	// CloneKeepName means do not edit the rootfs to change the hostname
	CloneKeepName CloneFlags = 1 << iota
	// CloneKeepMACAddr means do not change the mac address on network interfaces
	CloneKeepMACAddr
	// CloneSnapshot means snapshot the original filesystem(s)
	CloneSnapshot
	// CloneKeepBdevType means use the same bdev type
	CloneKeepBdevType
	// CloneMaybeSnapshot means snapshot only if bdev supports it, else copy
	CloneMaybeSnapshot
)

type Personality int64

const (
	X86    = 0x0008
	X86_64 = 0x0000
)
<commit_msg>use the Personality type<commit_after>// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved.
// Use of this source code is governed by a LGPLv2.1
// license that can be found in the LICENSE file.

// +build linux

package lxc

// #include <lxc/lxccontainer.h>
import "C"

import (
	"fmt"
)

// Verbosity type
type Verbosity int

const (
	// Quiet makes some API calls not to write anything to stdout
	Quiet Verbosity = 1 << iota
	// Verbose makes some API calls write to stdout
	Verbose
)

// BackendStore type specifies possible backend types.
type BackendStore int

const (
	// Btrfs backendstore type
	Btrfs BackendStore = iota + 1
	// Directory backendstore type
	Directory
	// LVM backendstore type
	LVM
	// ZFS backendstore type
	ZFS
	// Aufs backendstore type
	Aufs
	// Overlayfs backendstore type
	Overlayfs
	// Loopback backendstore type
	Loopback
	// Best backendstore type
	Best
)

// BackendStore as string
func (t BackendStore) String() string {
	switch t {
	case Directory:
		return "dir"
	case ZFS:
		return "zfs"
	case Btrfs:
		return "btrfs"
	case LVM:
		return "lvm"
	case Aufs:
		return "aufs"
	case Overlayfs:
		return "overlayfs"
	case Loopback:
		return "loopback"
	case Best:
		return "best"
	}
	return "<INVALID>"
}

// State type specifies possible container states.
type State int

const (
	// STOPPED means container is not running
	STOPPED State = iota + 1
	// STARTING means container is starting
	STARTING
	// RUNNING means container is running
	RUNNING
	// STOPPING means container is stopping
	STOPPING
	// ABORTING means container is aborting
	ABORTING
	// FREEZING means container is freezing
	FREEZING
	// FROZEN means containe is frozen
	FROZEN
	// THAWED means container is thawed
	THAWED
)

var stateMap = map[string]State{
	"STOPPED":  STOPPED,
	"STARTING": STARTING,
	"RUNNING":  RUNNING,
	"STOPPING": STOPPING,
	"ABORTING": ABORTING,
	"FREEZING": FREEZING,
	"FROZEN":   FROZEN,
	"THAWED":   THAWED,
}

// State as string
func (t State) String() string {
	switch t {
	case STOPPED:
		return "STOPPED"
	case STARTING:
		return "STARTING"
	case RUNNING:
		return "RUNNING"
	case STOPPING:
		return "STOPPING"
	case ABORTING:
		return "ABORTING"
	case FREEZING:
		return "FREEZING"
	case FROZEN:
		return "FROZEN"
	case THAWED:
		return "THAWED"
	}
	return "<INVALID>"
}

// Taken from http://golang.org/doc/effective_go.html#constants

// ByteSize type
type ByteSize float64

const (
	_ = iota
	// KB - kilobyte
	KB ByteSize = 1 << (10 * iota)
	// MB - megabyte
	MB
	// GB - gigabyte
	GB
	// TB - terabyte
	TB
	// PB - petabyte
	PB
	// EB - exabyte
	EB
	// ZB - zettabyte
	ZB
	// YB - yottabyte
	YB
)

func (b ByteSize) String() string {
	switch {
	case b >= YB:
		return fmt.Sprintf("%.2fYB", b/YB)
	case b >= ZB:
		return fmt.Sprintf("%.2fZB", b/ZB)
	case b >= EB:
		return fmt.Sprintf("%.2fEB", b/EB)
	case b >= PB:
		return fmt.Sprintf("%.2fPB", b/PB)
	case b >= TB:
		return fmt.Sprintf("%.2fTB", b/TB)
	case b >= GB:
		return fmt.Sprintf("%.2fGB", b/GB)
	case b >= MB:
		return fmt.Sprintf("%.2fMB", b/MB)
	case b >= KB:
		return fmt.Sprintf("%.2fKB", b/KB)
	}
	return fmt.Sprintf("%.2fB", b)
}

// LogLevel type specifies possible log levels.
type LogLevel int

const (
	// TRACE priority
	TRACE LogLevel = iota
	// DEBUG priority
	DEBUG
	// INFO priority
	INFO
	// NOTICE priority
	NOTICE
	// WARN priority
	WARN
	// ERROR priority
	ERROR
	// CRIT priority
	CRIT
	// ALERT priority
	ALERT
	// FATAL priority
	FATAL
)

var logLevelMap = map[string]LogLevel{
	"TRACE":  TRACE,
	"DEBUG":  DEBUG,
	"INFO":   INFO,
	"NOTICE": NOTICE,
	"WARN":   WARN,
	"ERROR":  ERROR,
	"CRIT":   CRIT,
	"ALERT":  ALERT,
	"FATAL":  FATAL,
}

func (l LogLevel) String() string {
	switch l {
	case TRACE:
		return "TRACE"
	case DEBUG:
		return "DEBUG"
	case INFO:
		return "INFO"
	case NOTICE:
		return "NOTICE"
	case WARN:
		return "WARN"
	case ERROR:
		return "ERROR"
	case CRIT:
		return "CRIT"
	case ALERT:
		return "ALERT"
	case FATAL:
		return "FATAL"
	}
	return "NOTSET"
}

// CloneFlags type
type CloneFlags int

const (
	// CloneKeepName means do not edit the rootfs to change the hostname
	CloneKeepName CloneFlags = 1 << iota
	// CloneKeepMACAddr means do not change the mac address on network interfaces
	CloneKeepMACAddr
	// CloneSnapshot means snapshot the original filesystem(s)
	CloneSnapshot
	// CloneKeepBdevType means use the same bdev type
	CloneKeepBdevType
	// CloneMaybeSnapshot means snapshot only if bdev supports it, else copy
	CloneMaybeSnapshot
)

type Personality int64

const (
	X86    Personality = 0x0008
	X86_64             = 0x0000
)
<|endoftext|>


<commit_before>package core

import (
	"reflect"
	"sort"
	"strings"
	"time"
)

const (
	POSTGRES = "postgres"
	SQLITE   = "sqlite3"
	MYSQL    = "mysql"
	MSSQL    = "mssql"
	ORACLE   = "oracle"
)

// xorm SQL types
type SQLType struct {
	Name           string
	DefaultLength  int
	DefaultLength2 int
}

const (
	UNKNOW_TYPE = iota
	TEXT_TYPE
	BLOB_TYPE
	TIME_TYPE
	NUMERIC_TYPE
)

func (s *SQLType) IsType(st int) bool {
	if t, ok := SqlTypes[s.Name]; ok && t == st {
		return true
	}
	return false
}

func (s *SQLType) IsText() bool {
	return s.IsType(TEXT_TYPE)
}

func (s *SQLType) IsBlob() bool {
	return s.IsType(BLOB_TYPE)
}

func (s *SQLType) IsTime() bool {
	return s.IsType(TIME_TYPE)
}

func (s *SQLType) IsNumeric() bool {
	return s.IsType(NUMERIC_TYPE)
}

func (s *SQLType) IsJson() bool {
	return s.Name == Json || s.Name == Jsonb
}

var (
	Bit       = "BIT"
	TinyInt   = "TINYINT"
	SmallInt  = "SMALLINT"
	MediumInt = "MEDIUMINT"
	Int       = "INT"
	Integer   = "INTEGER"
	BigInt    = "BIGINT"

	Enum = "ENUM"
	Set  = "SET"

	Char       = "CHAR"
	Varchar    = "VARCHAR"
	NVarchar   = "NVARCHAR"
	TinyText   = "TINYTEXT"
	Text       = "TEXT"
	Clob       = "CLOB"
	MediumText = "MEDIUMTEXT"
	LongText   = "LONGTEXT"
	Uuid       = "UUID"

	Date       = "DATE"
	DateTime   = "DATETIME"
	Time       = "TIME"
	TimeStamp  = "TIMESTAMP"
	TimeStampz = "TIMESTAMPZ"

	Decimal = "DECIMAL"
	Numeric = "NUMERIC"

	Real   = "REAL"
	Float  = "FLOAT"
	Double = "DOUBLE"

	Binary     = "BINARY"
	VarBinary  = "VARBINARY"
	TinyBlob   = "TINYBLOB"
	Blob       = "BLOB"
	MediumBlob = "MEDIUMBLOB"
	LongBlob   = "LONGBLOB"
	Bytea      = "BYTEA"

	Bool    = "BOOL"
	Boolean = "BOOLEAN"

	Serial    = "SERIAL"
	BigSerial = "BIGSERIAL"

	Json  = "JSON"
	Jsonb = "JSONB"

	SqlTypes = map[string]int{
		Bit:       NUMERIC_TYPE,
		TinyInt:   NUMERIC_TYPE,
		SmallInt:  NUMERIC_TYPE,
		MediumInt: NUMERIC_TYPE,
		Int:       NUMERIC_TYPE,
		Integer:   NUMERIC_TYPE,
		BigInt:    NUMERIC_TYPE,

		Enum:  TEXT_TYPE,
		Set:   TEXT_TYPE,
		Json:  TEXT_TYPE,
		Jsonb: TEXT_TYPE,

		Char:       TEXT_TYPE,
		Varchar:    TEXT_TYPE,
		NVarchar:   TEXT_TYPE,
		TinyText:   TEXT_TYPE,
		Text:       TEXT_TYPE,
		MediumText: TEXT_TYPE,
		LongText:   TEXT_TYPE,
		Uuid:       TEXT_TYPE,
		Clob:       TEXT_TYPE,

		Date:       TIME_TYPE,
		DateTime:   TIME_TYPE,
		Time:       TIME_TYPE,
		TimeStamp:  TIME_TYPE,
		TimeStampz: TIME_TYPE,

		Decimal: NUMERIC_TYPE,
		Numeric: NUMERIC_TYPE,
		Real:    NUMERIC_TYPE,
		Float:   NUMERIC_TYPE,
		Double:  NUMERIC_TYPE,

		Binary:    BLOB_TYPE,
		VarBinary: BLOB_TYPE,

		TinyBlob:   BLOB_TYPE,
		Blob:       BLOB_TYPE,
		MediumBlob: BLOB_TYPE,
		LongBlob:   BLOB_TYPE,
		Bytea:      BLOB_TYPE,

		Bool: NUMERIC_TYPE,

		Serial:    NUMERIC_TYPE,
		BigSerial: NUMERIC_TYPE,
	}

	intTypes  = sort.StringSlice{"*int", "*int16", "*int32", "*int8"}
	uintTypes = sort.StringSlice{"*uint", "*uint16", "*uint32", "*uint8"}
)

// !nashtsai! treat following var as interal const values, these are used for reflect.TypeOf comparison
var (
	c_EMPTY_STRING       string
	c_BOOL_DEFAULT       bool
	c_BYTE_DEFAULT       byte
	c_COMPLEX64_DEFAULT  complex64
	c_COMPLEX128_DEFAULT complex128
	c_FLOAT32_DEFAULT    float32
	c_FLOAT64_DEFAULT    float64
	c_INT64_DEFAULT      int64
	c_UINT64_DEFAULT     uint64
	c_INT32_DEFAULT      int32
	c_UINT32_DEFAULT     uint32
	c_INT16_DEFAULT      int16
	c_UINT16_DEFAULT     uint16
	c_INT8_DEFAULT       int8
	c_UINT8_DEFAULT      uint8
	c_INT_DEFAULT        int
	c_UINT_DEFAULT       uint
	c_TIME_DEFAULT       time.Time
)

var (
	IntType   = reflect.TypeOf(c_INT_DEFAULT)
	Int8Type  = reflect.TypeOf(c_INT8_DEFAULT)
	Int16Type = reflect.TypeOf(c_INT16_DEFAULT)
	Int32Type = reflect.TypeOf(c_INT32_DEFAULT)
	Int64Type = reflect.TypeOf(c_INT64_DEFAULT)

	UintType   = reflect.TypeOf(c_UINT_DEFAULT)
	Uint8Type  = reflect.TypeOf(c_UINT8_DEFAULT)
	Uint16Type = reflect.TypeOf(c_UINT16_DEFAULT)
	Uint32Type = reflect.TypeOf(c_UINT32_DEFAULT)
	Uint64Type = reflect.TypeOf(c_UINT64_DEFAULT)

	Float32Type = reflect.TypeOf(c_FLOAT32_DEFAULT)
	Float64Type = reflect.TypeOf(c_FLOAT64_DEFAULT)

	Complex64Type  = reflect.TypeOf(c_COMPLEX64_DEFAULT)
	Complex128Type = reflect.TypeOf(c_COMPLEX128_DEFAULT)

	StringType = reflect.TypeOf(c_EMPTY_STRING)
	BoolType   = reflect.TypeOf(c_BOOL_DEFAULT)
	ByteType   = reflect.TypeOf(c_BYTE_DEFAULT)
	BytesType  = reflect.SliceOf(ByteType)

	TimeType = reflect.TypeOf(c_TIME_DEFAULT)
)

var (
	PtrIntType   = reflect.PtrTo(IntType)
	PtrInt8Type  = reflect.PtrTo(Int8Type)
	PtrInt16Type = reflect.PtrTo(Int16Type)
	PtrInt32Type = reflect.PtrTo(Int32Type)
	PtrInt64Type = reflect.PtrTo(Int64Type)

	PtrUintType   = reflect.PtrTo(UintType)
	PtrUint8Type  = reflect.PtrTo(Uint8Type)
	PtrUint16Type = reflect.PtrTo(Uint16Type)
	PtrUint32Type = reflect.PtrTo(Uint32Type)
	PtrUint64Type = reflect.PtrTo(Uint64Type)

	PtrFloat32Type = reflect.PtrTo(Float32Type)
	PtrFloat64Type = reflect.PtrTo(Float64Type)

	PtrComplex64Type  = reflect.PtrTo(Complex64Type)
	PtrComplex128Type = reflect.PtrTo(Complex128Type)

	PtrStringType = reflect.PtrTo(StringType)
	PtrBoolType   = reflect.PtrTo(BoolType)
	PtrByteType   = reflect.PtrTo(ByteType)

	PtrTimeType = reflect.PtrTo(TimeType)
)

// Type2SQLType generate SQLType acorrding Go's type
func Type2SQLType(t reflect.Type) (st SQLType) {
	switch k := t.Kind(); k {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32:
		st = SQLType{Int, 0, 0}
	case reflect.Int64, reflect.Uint64:
		st = SQLType{BigInt, 0, 0}
	case reflect.Float32:
		st = SQLType{Float, 0, 0}
	case reflect.Float64:
		st = SQLType{Double, 0, 0}
	case reflect.Complex64, reflect.Complex128:
		st = SQLType{Varchar, 64, 0}
	case reflect.Array, reflect.Slice, reflect.Map:
		if t.Elem() == reflect.TypeOf(c_BYTE_DEFAULT) {
			st = SQLType{Blob, 0, 0}
		} else {
			st = SQLType{Text, 0, 0}
		}
	case reflect.Bool:
		st = SQLType{Bool, 0, 0}
	case reflect.String:
		st = SQLType{Varchar, 255, 0}
	case reflect.Struct:
		if t.ConvertibleTo(TimeType) {
			st = SQLType{DateTime, 0, 0}
		} else {
			// TODO need to handle association struct
			st = SQLType{Text, 0, 0}
		}
	case reflect.Ptr:
		st = Type2SQLType(t.Elem())
	default:
		st = SQLType{Text, 0, 0}
	}
	return
}

// default sql type change to go types
func SQLType2Type(st SQLType) reflect.Type {
	name := strings.ToUpper(st.Name)
	switch name {
	case Bit, TinyInt, SmallInt, MediumInt, Int, Integer, Serial:
		return reflect.TypeOf(1)
	case BigInt, BigSerial:
		return reflect.TypeOf(int64(1))
	case Float, Real:
		return reflect.TypeOf(float32(1))
	case Double:
		return reflect.TypeOf(float64(1))
	case Char, Varchar, NVarchar, TinyText, Text, MediumText, LongText, Enum, Set, Uuid, Clob:
		return reflect.TypeOf("")
	case TinyBlob, Blob, LongBlob, Bytea, Binary, MediumBlob, VarBinary:
		return reflect.TypeOf([]byte{})
	case Bool:
		return reflect.TypeOf(true)
	case DateTime, Date, Time, TimeStamp, TimeStampz:
		return reflect.TypeOf(c_TIME_DEFAULT)
	case Decimal, Numeric:
		return reflect.TypeOf("")
	default:
		return reflect.TypeOf("")
	}
}
<commit_msg>add UniqueIdentifier type for supporting mssql<commit_after>package core

import (
	"reflect"
	"sort"
	"strings"
	"time"
)

const (
	POSTGRES = "postgres"
	SQLITE   = "sqlite3"
	MYSQL    = "mysql"
	MSSQL    = "mssql"
	ORACLE   = "oracle"
)

// xorm SQL types
type SQLType struct {
	Name           string
	DefaultLength  int
	DefaultLength2 int
}

const (
	UNKNOW_TYPE = iota
	TEXT_TYPE
	BLOB_TYPE
	TIME_TYPE
	NUMERIC_TYPE
)

func (s *SQLType) IsType(st int) bool {
	if t, ok := SqlTypes[s.Name]; ok && t == st {
		return true
	}
	return false
}

func (s *SQLType) IsText() bool {
	return s.IsType(TEXT_TYPE)
}

func (s *SQLType) IsBlob() bool {
	return s.IsType(BLOB_TYPE)
}

func (s *SQLType) IsTime() bool {
	return s.IsType(TIME_TYPE)
}

func (s *SQLType) IsNumeric() bool {
	return s.IsType(NUMERIC_TYPE)
}

func (s *SQLType) IsJson() bool {
	return s.Name == Json || s.Name == Jsonb
}

var (
	Bit       = "BIT"
	TinyInt   = "TINYINT"
	SmallInt  = "SMALLINT"
	MediumInt = "MEDIUMINT"
	Int       = "INT"
	Integer   = "INTEGER"
	BigInt    = "BIGINT"

	Enum = "ENUM"
	Set  = "SET"

	Char             = "CHAR"
	Varchar          = "VARCHAR"
	NVarchar         = "NVARCHAR"
	TinyText         = "TINYTEXT"
	Text             = "TEXT"
	Clob             = "CLOB"
	MediumText       = "MEDIUMTEXT"
	LongText         = "LONGTEXT"
	Uuid             = "UUID"
	UniqueIdentifier = "UNIQUEIDENTIFIER"

	Date       = "DATE"
	DateTime   = "DATETIME"
	Time       = "TIME"
	TimeStamp  = "TIMESTAMP"
	TimeStampz = "TIMESTAMPZ"

	Decimal = "DECIMAL"
	Numeric = "NUMERIC"

	Real   = "REAL"
	Float  = "FLOAT"
	Double = "DOUBLE"

	Binary     = "BINARY"
	VarBinary  = "VARBINARY"
	TinyBlob   = "TINYBLOB"
	Blob       = "BLOB"
	MediumBlob = "MEDIUMBLOB"
	LongBlob   = "LONGBLOB"
	Bytea      = "BYTEA"

	Bool    = "BOOL"
	Boolean = "BOOLEAN"

	Serial    = "SERIAL"
	BigSerial = "BIGSERIAL"

	Json  = "JSON"
	Jsonb = "JSONB"

	SqlTypes = map[string]int{
		Bit:       NUMERIC_TYPE,
		TinyInt:   NUMERIC_TYPE,
		SmallInt:  NUMERIC_TYPE,
		MediumInt: NUMERIC_TYPE,
		Int:       NUMERIC_TYPE,
		Integer:   NUMERIC_TYPE,
		BigInt:    NUMERIC_TYPE,

		Enum:  TEXT_TYPE,
		Set:   TEXT_TYPE,
		Json:  TEXT_TYPE,
		Jsonb: TEXT_TYPE,

		Char:       TEXT_TYPE,
		Varchar:    TEXT_TYPE,
		NVarchar:   TEXT_TYPE,
		TinyText:   TEXT_TYPE,
		Text:       TEXT_TYPE,
		MediumText: TEXT_TYPE,
		LongText:   TEXT_TYPE,
		Uuid:       TEXT_TYPE,
		Clob:       TEXT_TYPE,

		Date:       TIME_TYPE,
		DateTime:   TIME_TYPE,
		Time:       TIME_TYPE,
		TimeStamp:  TIME_TYPE,
		TimeStampz: TIME_TYPE,

		Decimal: NUMERIC_TYPE,
		Numeric: NUMERIC_TYPE,
		Real:    NUMERIC_TYPE,
		Float:   NUMERIC_TYPE,
		Double:  NUMERIC_TYPE,

		Binary:    BLOB_TYPE,
		VarBinary: BLOB_TYPE,

		TinyBlob:         BLOB_TYPE,
		Blob:             BLOB_TYPE,
		MediumBlob:       BLOB_TYPE,
		LongBlob:         BLOB_TYPE,
		Bytea:            BLOB_TYPE,
		UniqueIdentifier: BLOB_TYPE,

		Bool: NUMERIC_TYPE,

		Serial:    NUMERIC_TYPE,
		BigSerial: NUMERIC_TYPE,
	}

	intTypes  = sort.StringSlice{"*int", "*int16", "*int32", "*int8"}
	uintTypes = sort.StringSlice{"*uint", "*uint16", "*uint32", "*uint8"}
)

// !nashtsai! treat following var as interal const values, these are used for reflect.TypeOf comparison
var (
	c_EMPTY_STRING       string
	c_BOOL_DEFAULT       bool
	c_BYTE_DEFAULT       byte
	c_COMPLEX64_DEFAULT  complex64
	c_COMPLEX128_DEFAULT complex128
	c_FLOAT32_DEFAULT    float32
	c_FLOAT64_DEFAULT    float64
	c_INT64_DEFAULT      int64
	c_UINT64_DEFAULT     uint64
	c_INT32_DEFAULT      int32
	c_UINT32_DEFAULT     uint32
	c_INT16_DEFAULT      int16
	c_UINT16_DEFAULT     uint16
	c_INT8_DEFAULT       int8
	c_UINT8_DEFAULT      uint8
	c_INT_DEFAULT        int
	c_UINT_DEFAULT       uint
	c_TIME_DEFAULT       time.Time
)

var (
	IntType   = reflect.TypeOf(c_INT_DEFAULT)
	Int8Type  = reflect.TypeOf(c_INT8_DEFAULT)
	Int16Type = reflect.TypeOf(c_INT16_DEFAULT)
	Int32Type = reflect.TypeOf(c_INT32_DEFAULT)
	Int64Type = reflect.TypeOf(c_INT64_DEFAULT)

	UintType   = reflect.TypeOf(c_UINT_DEFAULT)
	Uint8Type  = reflect.TypeOf(c_UINT8_DEFAULT)
	Uint16Type = reflect.TypeOf(c_UINT16_DEFAULT)
	Uint32Type = reflect.TypeOf(c_UINT32_DEFAULT)
	Uint64Type = reflect.TypeOf(c_UINT64_DEFAULT)

	Float32Type = reflect.TypeOf(c_FLOAT32_DEFAULT)
	Float64Type = reflect.TypeOf(c_FLOAT64_DEFAULT)

	Complex64Type  = reflect.TypeOf(c_COMPLEX64_DEFAULT)
	Complex128Type = reflect.TypeOf(c_COMPLEX128_DEFAULT)

	StringType = reflect.TypeOf(c_EMPTY_STRING)
	BoolType   = reflect.TypeOf(c_BOOL_DEFAULT)
	ByteType   = reflect.TypeOf(c_BYTE_DEFAULT)
	BytesType  = reflect.SliceOf(ByteType)

	TimeType = reflect.TypeOf(c_TIME_DEFAULT)
)

var (
	PtrIntType   = reflect.PtrTo(IntType)
	PtrInt8Type  = reflect.PtrTo(Int8Type)
	PtrInt16Type = reflect.PtrTo(Int16Type)
	PtrInt32Type = reflect.PtrTo(Int32Type)
	PtrInt64Type = reflect.PtrTo(Int64Type)

	PtrUintType   = reflect.PtrTo(UintType)
	PtrUint8Type  = reflect.PtrTo(Uint8Type)
	PtrUint16Type = reflect.PtrTo(Uint16Type)
	PtrUint32Type = reflect.PtrTo(Uint32Type)
	PtrUint64Type = reflect.PtrTo(Uint64Type)

	PtrFloat32Type = reflect.PtrTo(Float32Type)
	PtrFloat64Type = reflect.PtrTo(Float64Type)

	PtrComplex64Type  = reflect.PtrTo(Complex64Type)
	PtrComplex128Type = reflect.PtrTo(Complex128Type)

	PtrStringType = reflect.PtrTo(StringType)
	PtrBoolType   = reflect.PtrTo(BoolType)
	PtrByteType   = reflect.PtrTo(ByteType)

	PtrTimeType = reflect.PtrTo(TimeType)
)

// Type2SQLType generate SQLType acorrding Go's type
func Type2SQLType(t reflect.Type) (st SQLType) {
	switch k := t.Kind(); k {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32:
		st = SQLType{Int, 0, 0}
	case reflect.Int64, reflect.Uint64:
		st = SQLType{BigInt, 0, 0}
	case reflect.Float32:
		st = SQLType{Float, 0, 0}
	case reflect.Float64:
		st = SQLType{Double, 0, 0}
	case reflect.Complex64, reflect.Complex128:
		st = SQLType{Varchar, 64, 0}
	case reflect.Array, reflect.Slice, reflect.Map:
		if t.Elem() == reflect.TypeOf(c_BYTE_DEFAULT) {
			st = SQLType{Blob, 0, 0}
		} else {
			st = SQLType{Text, 0, 0}
		}
	case reflect.Bool:
		st = SQLType{Bool, 0, 0}
	case reflect.String:
		st = SQLType{Varchar, 255, 0}
	case reflect.Struct:
		if t.ConvertibleTo(TimeType) {
			st = SQLType{DateTime, 0, 0}
		} else {
			// TODO need to handle association struct
			st = SQLType{Text, 0, 0}
		}
	case reflect.Ptr:
		st = Type2SQLType(t.Elem())
	default:
		st = SQLType{Text, 0, 0}
	}
	return
}

// default sql type change to go types
func SQLType2Type(st SQLType) reflect.Type {
	name := strings.ToUpper(st.Name)
	switch name {
	case Bit, TinyInt, SmallInt, MediumInt, Int, Integer, Serial:
		return reflect.TypeOf(1)
	case BigInt, BigSerial:
		return reflect.TypeOf(int64(1))
	case Float, Real:
		return reflect.TypeOf(float32(1))
	case Double:
		return reflect.TypeOf(float64(1))
	case Char, Varchar, NVarchar, TinyText, Text, MediumText, LongText, Enum, Set, Uuid, Clob:
		return reflect.TypeOf("")
	case TinyBlob, Blob, LongBlob, Bytea, Binary, MediumBlob, VarBinary, UniqueIdentifier:
		return reflect.TypeOf([]byte{})
	case Bool:
		return reflect.TypeOf(true)
	case DateTime, Date, Time, TimeStamp, TimeStampz:
		return reflect.TypeOf(c_TIME_DEFAULT)
	case Decimal, Numeric:
		return reflect.TypeOf("")
	default:
		return reflect.TypeOf("")
	}
}
<|endoftext|>


<commit_before>package goio

import (
	"log"
	"sync"
)

type User struct {
	Event
	Id        string
	ClientIds MapBool
	RoomIds   MapBool
	lock      sync.RWMutex
}

func (self *User) Receive(message *Message) {
	self.lock.Lock()
	defer self.lock.Unlock()

	for cltId := range self.ClientIds.Map {
		clt := GlobalClients().Get(cltId)
		if clt != nil {
			clt.Receive(message)
		}
	}
}

func (self *User) Delete(id string) {
	self.lock.Lock()
	defer self.lock.Unlock()

	self.ClientIds.Delete(id)
	if 0 == self.ClientIds.Count() {
		log.Println("user client count 0")
		self.Destory()
	}
}

func (self *User) Destory() {
	self.Emit("destory", nil)
}

func (self *User) Add(clt *Client) {
	if self.ClientIds.Has(clt.Id) {
		return
	}

	clt.On("destory", func(message *Message) {
		self.Delete(clt.Id)
	})

	clt.UserId = self.Id
	self.ClientIds.Add(clt.Id)
}
<commit_msg>don't send message to myself<commit_after>package goio

import (
	"log"
	"sync"
)

type User struct {
	Event
	Id        string
	ClientIds MapBool
	RoomIds   MapBool
	lock      sync.RWMutex
}

func (self *User) Receive(message *Message) {

	// Don't send message to myself
	if message != nil && message.CallerId == self.Id {
		return
	}

	self.lock.Lock()
	defer self.lock.Unlock()

	for cltId := range self.ClientIds.Map {
		clt := GlobalClients().Get(cltId)
		if clt != nil {
			clt.Receive(message)
		}
	}
}

func (self *User) Delete(id string) {
	self.lock.Lock()
	defer self.lock.Unlock()

	self.ClientIds.Delete(id)
	if 0 == self.ClientIds.Count() {
		log.Println("user client count 0")
		self.Destory()
	}
}

func (self *User) Destory() {
	self.Emit("destory", nil)
}

func (self *User) Add(clt *Client) {
	if self.ClientIds.Has(clt.Id) {
		return
	}

	clt.On("destory", func(message *Message) {
		self.Delete(clt.Id)
	})

	clt.UserId = self.Id
	self.ClientIds.Add(clt.Id)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os/exec"

	"github.com/pkg/errors"
)

func CreateUser(etcd *Etcd, username string) error {
	if err := etcd.Mkdir("/paus/users/" + username); err != nil {
		return errors.Wrap(err, fmt.Sprintf("Failed to create user. username: %s", username))
	}

	return nil
}

func UserExists(etcd *Etcd, username string) bool {
	return etcd.HasKey("/paus/users/" + username)
}

func UploadPublicKey(username, pubKey string) (string, error) {
	// libcompose does not support `docker-compose run`...
	out, err := exec.Command("docker-compose", "-p", "paus", "run", "--rm", "gitreceive-upload-key", username, pubKey).Output()

	if err != nil {
		return "", errors.Wrap(err, fmt.Sprintf("Failed to upload SSH public key. username: %s, pubKey: %s", username, pubKey))
	}

	return string(out), nil
}
<commit_msg>Create app directory with new user<commit_after>package main

import (
	"fmt"
	"os/exec"

	"github.com/pkg/errors"
)

func CreateUser(etcd *Etcd, username string) error {
	if err := etcd.Mkdir("/paus/users/" + username); err != nil {
		return errors.Wrap(err, fmt.Sprintf("Failed to create user. username: %s", username))
	}

	if err := etcd.Mkdir("/paus/users/" + username + "/apps"); err != nil {
		return errors.Wrap(err, fmt.Sprintf("Failed to create user app directory. username: %s", username))
	}

	return nil
}

func UserExists(etcd *Etcd, username string) bool {
	return etcd.HasKey("/paus/users/" + username)
}

func UploadPublicKey(username, pubKey string) (string, error) {
	// libcompose does not support `docker-compose run`...
	out, err := exec.Command("docker-compose", "-p", "paus", "run", "--rm", "gitreceive-upload-key", username, pubKey).Output()

	if err != nil {
		return "", errors.Wrap(err, fmt.Sprintf("Failed to upload SSH public key. username: %s, pubKey: %s", username, pubKey))
	}

	return string(out), nil
}
<|endoftext|>


<commit_before>package aceproject

import (
	"net/http"

	sling "gopkg.in/dghubble/sling.v1"
)

// GetUsersParam represents getusers request parameter
type GetUsersParam struct {
	FilterActive bool `url:"FilterActive,omitempty"`
}

// UserResponse represents user listing response
type UserResponse struct {
	Status  string `json:"status"`
	Results []User `json:"results"`
}

// User is representing user in ACEProject
type User struct {
	ID            int64   `json:"USER_ID"`
	Username      string  `json:"USERNAME"`
	Email         string  `json:"EMAIL_ALERT"`
	FirstName     string  `json:"FIRST_NAME"`
	LastName      string  `json:"LAST_NAME"`
	UserGroupID   int64   `json:"USER_GROUP_ID"`
	UserGroupName string  `json:"USER_GROUP_NAME"`
	Active        bool    `json:"ACTIVE"`
	ErrorDesc     *string `json:"ERRORDESCRIPTION,omitempty"`
}

// UserService provides methods to interact with user specific action
type UserService struct {
	sling *sling.Sling
}

// NewUserService return a new UserService
func NewUserService(httpClient *http.Client, guidInfo *GUIDInfo) *UserService {
	return &UserService{
		sling: sling.New().Client(httpClient).Base(baseURL).QueryStruct(guidInfo),
	}
}

// List returns the user list
func (s *UserService) List() ([]User, *http.Response, error) {
	resObj := new(UserResponse)
	resp, err := s.sling.New().
		QueryStruct(CreateFunctionParam("getusers")).
		ReceiveSuccess(resObj)
	if resObj != nil && len(resObj.Results) > 0 {
		if resObj.Results[0].ErrorDesc != nil {
			return nil, resp, Error{*resObj.Results[0].ErrorDesc}
		}
		return *(&resObj.Results), resp, err
	}
	return make([]User, 0), resp, err
}

// ListWithActiveness returns the list of active / non-active users
func (s *UserService) ListWithActiveness(active bool) ([]User, *http.Response, error) {
	resObj := new(UserResponse)
	resp, err := s.sling.New().
		QueryStruct(CreateFunctionParam("getusers")).
		QueryStruct(&GetUsersParam{FilterActive: active}).
		ReceiveSuccess(resObj)
	if resObj != nil && len(resObj.Results) > 0 {
		if resObj.Results[0].ErrorDesc != nil {
			return nil, resp, Error{*resObj.Results[0].ErrorDesc}
		}
		return *(&resObj.Results), resp, err
	}
	return make([]User, 0), resp, err
}
<commit_msg>allow query inactive user (#9)<commit_after>package aceproject

import (
	"net/http"

	sling "gopkg.in/dghubble/sling.v1"
)

// GetUsersParam represents getusers request parameter
type GetUsersParam struct {
	FilterActive bool `url:"FilterActive"`
}

// UserResponse represents user listing response
type UserResponse struct {
	Status  string `json:"status"`
	Results []User `json:"results"`
}

// User is representing user in ACEProject
type User struct {
	ID            int64   `json:"USER_ID"`
	Username      string  `json:"USERNAME"`
	Email         string  `json:"EMAIL_ALERT"`
	FirstName     string  `json:"FIRST_NAME"`
	LastName      string  `json:"LAST_NAME"`
	UserGroupID   int64   `json:"USER_GROUP_ID"`
	UserGroupName string  `json:"USER_GROUP_NAME"`
	Active        bool    `json:"ACTIVE"`
	ErrorDesc     *string `json:"ERRORDESCRIPTION,omitempty"`
}

// UserService provides methods to interact with user specific action
type UserService struct {
	sling *sling.Sling
}

// NewUserService return a new UserService
func NewUserService(httpClient *http.Client, guidInfo *GUIDInfo) *UserService {
	return &UserService{
		sling: sling.New().Client(httpClient).Base(baseURL).QueryStruct(guidInfo),
	}
}

// List returns the user list
func (s *UserService) List() ([]User, *http.Response, error) {
	resObj := new(UserResponse)
	resp, err := s.sling.New().
		QueryStruct(CreateFunctionParam("getusers")).
		ReceiveSuccess(resObj)
	if resObj != nil && len(resObj.Results) > 0 {
		if resObj.Results[0].ErrorDesc != nil {
			return nil, resp, Error{*resObj.Results[0].ErrorDesc}
		}
		return *(&resObj.Results), resp, err
	}
	return make([]User, 0), resp, err
}

// ListWithActiveness returns the list of active / non-active users
func (s *UserService) ListWithActiveness(active bool) ([]User, *http.Response, error) {
	resObj := new(UserResponse)
	resp, err := s.sling.New().
		QueryStruct(CreateFunctionParam("getusers")).
		QueryStruct(&GetUsersParam{FilterActive: active}).
		ReceiveSuccess(resObj)
	if resObj != nil && len(resObj.Results) > 0 {
		if resObj.Results[0].ErrorDesc != nil {
			return nil, resp, Error{*resObj.Results[0].ErrorDesc}
		}
		return *(&resObj.Results), resp, err
	}
	return make([]User, 0), resp, err
}
<|endoftext|>


<commit_before>package cloudflare

import (
	"encoding/json"
	"fmt"
)

/*
Information about the logged-in user.

API reference: https://api.cloudflare.com/#user-user-details
*/
func (api API) UserDetails() (User, error) {
	var r UserResponse
	res, err := api.makeRequest("GET", "/user", nil)
	if err != nil {
		return User{}, err
	}
	fmt.Printf("%s\n", res)
	err = json.Unmarshal(res, &r)
	if err != nil {
		return User{}, err
	}
	return r.Result, nil
}

/*
Update user properties.

API reference: https://api.cloudflare.com/#user-update-user
*/
func (api API) UpdateUser() (User, error) {
	// api.makeRequest("PATCH", "/user", user)
	return User{}, nil
}
<commit_msg>Remove more debug prints<commit_after>package cloudflare

import "encoding/json"

/*
Information about the logged-in user.

API reference: https://api.cloudflare.com/#user-user-details
*/
func (api API) UserDetails() (User, error) {
	var r UserResponse
	res, err := api.makeRequest("GET", "/user", nil)
	if err != nil {
		return User{}, err
	}
	err = json.Unmarshal(res, &r)
	if err != nil {
		return User{}, err
	}
	return r.Result, nil
}

/*
Update user properties.

API reference: https://api.cloudflare.com/#user-update-user
*/
func (api API) UpdateUser() (User, error) {
	// api.makeRequest("PATCH", "/user", user)
	return User{}, nil
}
<|endoftext|>


<commit_before>package cuckoofilter

import (
	"encoding/binary"

	"github.com/dgryski/go-metro"
)

func getAltIndex(fp byte, i uint, numBuckets uint) uint {
	bytes := []byte{0, 0, 0, 0, 0, 0, 0, fp}
	hash := binary.LittleEndian.Uint64(bytes)
	return uint(uint64(i)^(hash*0x5bd1e995)) % numBuckets
}

func getFingerprint(data []byte) byte {
	fp := byte(metro.Hash64(data, 1337))
	if fp == 0 {
		fp += 7
	}
	return fp
}

// getIndicesAndFingerprint returns the 2 bucket indices and fingerprint to be used
func getIndicesAndFingerprint(data []byte, numBuckets uint) (uint, uint, byte) {
	hash := metro.Hash64(data, 1337)
	f := getFingerprint(data)
	i1 := uint(hash) % numBuckets
	i2 := getAltIndex(f, i1, numBuckets)
	return i1, i2, f
}

func getNextPow2(n uint64) uint {
	n--
	n |= n >> 1
	n |= n >> 2
	n |= n >> 4
	n |= n >> 8
	n |= n >> 16
	n |= n >> 32
	n++
	return uint(n)
}
<commit_msg>use different hashing algorithm for fingerprint<commit_after>package cuckoofilter

import (
	"github.com/dgryski/go-metro"
)

func getAltIndex(fp byte, i uint, numBuckets uint) uint {
	hash := uint(metro.Hash64([]byte{fp}, 1337))
	return (i ^ hash) % numBuckets
}

func getFingerprint(data []byte) byte {
	fp := byte(metro.Hash64(data, 1335)%255 + 1)
	return fp
}

// getIndicesAndFingerprint returns the 2 bucket indices and fingerprint to be used
func getIndicesAndFingerprint(data []byte, numBuckets uint) (uint, uint, byte) {
	hash := metro.Hash64(data, 1337)
	f := getFingerprint(data)
	i1 := uint(hash) % numBuckets
	i2 := getAltIndex(f, i1, numBuckets)
	return i1, i2, f
}

func getNextPow2(n uint64) uint {
	n--
	n |= n >> 1
	n |= n >> 2
	n |= n >> 4
	n |= n >> 8
	n |= n >> 16
	n |= n >> 32
	n++
	return uint(n)
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"errors"
	"fmt"
	"os"
	"runtime"
	"strconv"
	"strings"
	"sync"
)

func ParseLine(line string) (*Example, error) {
	tokens := strings.Split(line, "\t")
	var url string
	if len(tokens) == 1 {
		url = tokens[0]
		return NewExample(url, UNLABELED), nil
	} else if len(tokens) == 2 {
		url = tokens[0]
		label, _ := strconv.ParseInt(tokens[1], 10, 0)
		switch LabelType(label) {
		case POSITIVE, NEGATIVE, UNLABELED:
			return NewExample(url, LabelType(label)), nil
		default:
			return nil, errors.New(fmt.Sprintf("Invalid Label type %d in %s", label, line))
		}
	} else {
		return nil, errors.New(fmt.Sprintf("Invalid line: %s", line))
	}
}

func ReadExamples(filename string) ([]*Example, error) {
	fp, err := os.Open(filename)
	defer fp.Close()
	if err != nil {
		return nil, err
	}

	scanner := bufio.NewScanner(fp)
	var examples Examples
	for scanner.Scan() {
		line := scanner.Text()
		e, err := ParseLine(line)
		if err != nil {
			return nil, err
		}
		examples = append(examples, e)
	}
	if err := scanner.Err(); err != nil {
		return nil, err
	}
	return examples, nil
}

func WriteExamples(examples Examples, filename string) error {
	fp, err := os.Create(filename)
	defer fp.Close()
	if err != nil {
		return err
	}

	writer := bufio.NewWriter(fp)
	for _, e := range examples {
		if e.IsNew && e.IsLabeled() {
			_, err := writer.WriteString(e.Url + "\t" + strconv.Itoa(int(e.Label)) + "\n")
			if err != nil {
				return err
			}
		}
	}

	writer.Flush()
	return nil
}

func FilterLabeledExamples(examples Examples) Examples {
	var result Examples
	for _, e := range examples {
		if e.IsLabeled() {
			result = append(result, e)
		}
	}
	return result
}

func FilterUnlabeledExamples(examples Examples) Examples {
	result := Examples{}

	alreadyLabeledByURL := make(map[string]bool)
	alreadyLabeledByTitle := make(map[string]bool)
	for _, e := range FilterLabeledExamples(examples) {
		alreadyLabeledByURL[e.Url] = true
		alreadyLabeledByTitle[e.Title] = true
	}

	for _, e := range examples {
		if _, ok := alreadyLabeledByURL[e.Url]; ok {
			continue
		}
		if _, ok := alreadyLabeledByTitle[e.Title]; ok {
			continue
		}
		if !e.IsLabeled() {
			alreadyLabeledByURL[e.Url] = true
			alreadyLabeledByTitle[e.Title] = true
			result = append(result, e)
		}
	}
	return result
}

func removeDuplicate(args []string) []string {
	results := make([]string, 0)
	encountered := map[string]bool{}
	for i := 0; i < len(args); i++ {
		if !encountered[args[i]] {
			encountered[args[i]] = true
			results = append(results, args[i])
		}
	}
	return results
}

func AttachMetaData(cache *Cache, examples Examples) {
	shuffle(examples)

	wg := &sync.WaitGroup{}
	cpus := runtime.NumCPU()
	runtime.GOMAXPROCS(cpus)
	sem := make(chan struct{}, 2000)
	for idx, e := range examples {
		wg.Add(1)
		sem <- struct{}{}
		go func(e *Example, idx int) {
			defer wg.Done()
			if example, ok := cache.Get(*e); ok {
				e.Title = example.Title
				e.FinalUrl = example.FinalUrl
				e.Description = example.Description
				e.Body = example.Body
				e.StatusCode = example.StatusCode
			} else {
				article := GetArticle(e.Url)
				fmt.Fprintln(os.Stderr, "Fetching("+strconv.Itoa(idx)+"): "+article.Url)
				e.Title = article.Title
				e.FinalUrl = article.Url
				e.Description = article.Description
				e.Body = article.Body
				e.StatusCode = article.StatusCode
				cache.Add(*e)
			}
			e.Fv = removeDuplicate(ExtractFeatures(*e))
			<-sem
		}(e, idx)
	}
	wg.Wait()
}

func FilterStatusCodeOkExamples(examples Examples) Examples {
	result := Examples{}

	for _, e := range examples {
		if e.StatusCode == 200 {
			result = append(result, e)
		}
	}

	return result
}
<commit_msg>並列数下げる<commit_after>package main

import (
	"bufio"
	"errors"
	"fmt"
	"os"
	"runtime"
	"strconv"
	"strings"
	"sync"
)

func ParseLine(line string) (*Example, error) {
	tokens := strings.Split(line, "\t")
	var url string
	if len(tokens) == 1 {
		url = tokens[0]
		return NewExample(url, UNLABELED), nil
	} else if len(tokens) == 2 {
		url = tokens[0]
		label, _ := strconv.ParseInt(tokens[1], 10, 0)
		switch LabelType(label) {
		case POSITIVE, NEGATIVE, UNLABELED:
			return NewExample(url, LabelType(label)), nil
		default:
			return nil, errors.New(fmt.Sprintf("Invalid Label type %d in %s", label, line))
		}
	} else {
		return nil, errors.New(fmt.Sprintf("Invalid line: %s", line))
	}
}

func ReadExamples(filename string) ([]*Example, error) {
	fp, err := os.Open(filename)
	defer fp.Close()
	if err != nil {
		return nil, err
	}

	scanner := bufio.NewScanner(fp)
	var examples Examples
	for scanner.Scan() {
		line := scanner.Text()
		e, err := ParseLine(line)
		if err != nil {
			return nil, err
		}
		examples = append(examples, e)
	}
	if err := scanner.Err(); err != nil {
		return nil, err
	}
	return examples, nil
}

func WriteExamples(examples Examples, filename string) error {
	fp, err := os.Create(filename)
	defer fp.Close()
	if err != nil {
		return err
	}

	writer := bufio.NewWriter(fp)
	for _, e := range examples {
		if e.IsNew && e.IsLabeled() {
			_, err := writer.WriteString(e.Url + "\t" + strconv.Itoa(int(e.Label)) + "\n")
			if err != nil {
				return err
			}
		}
	}

	writer.Flush()
	return nil
}

func FilterLabeledExamples(examples Examples) Examples {
	var result Examples
	for _, e := range examples {
		if e.IsLabeled() {
			result = append(result, e)
		}
	}
	return result
}

func FilterUnlabeledExamples(examples Examples) Examples {
	result := Examples{}

	alreadyLabeledByURL := make(map[string]bool)
	alreadyLabeledByTitle := make(map[string]bool)
	for _, e := range FilterLabeledExamples(examples) {
		alreadyLabeledByURL[e.Url] = true
		alreadyLabeledByTitle[e.Title] = true
	}

	for _, e := range examples {
		if _, ok := alreadyLabeledByURL[e.Url]; ok {
			continue
		}
		if _, ok := alreadyLabeledByTitle[e.Title]; ok {
			continue
		}
		if !e.IsLabeled() {
			alreadyLabeledByURL[e.Url] = true
			alreadyLabeledByTitle[e.Title] = true
			result = append(result, e)
		}
	}
	return result
}

func removeDuplicate(args []string) []string {
	results := make([]string, 0)
	encountered := map[string]bool{}
	for i := 0; i < len(args); i++ {
		if !encountered[args[i]] {
			encountered[args[i]] = true
			results = append(results, args[i])
		}
	}
	return results
}

func AttachMetaData(cache *Cache, examples Examples) {
	shuffle(examples)

	wg := &sync.WaitGroup{}
	cpus := runtime.NumCPU()
	runtime.GOMAXPROCS(cpus)
	sem := make(chan struct{}, 20)
	for idx, e := range examples {
		wg.Add(1)
		sem <- struct{}{}
		go func(e *Example, idx int) {
			defer wg.Done()
			if example, ok := cache.Get(*e); ok {
				e.Title = example.Title
				e.FinalUrl = example.FinalUrl
				e.Description = example.Description
				e.Body = example.Body
				e.StatusCode = example.StatusCode
			} else {
				article := GetArticle(e.Url)
				fmt.Fprintln(os.Stderr, "Fetching("+strconv.Itoa(idx)+"): "+article.Url)
				e.Title = article.Title
				e.FinalUrl = article.Url
				e.Description = article.Description
				e.Body = article.Body
				e.StatusCode = article.StatusCode
				cache.Add(*e)
			}
			e.Fv = removeDuplicate(ExtractFeatures(*e))
			<-sem
		}(e, idx)
	}
	wg.Wait()
}

func FilterStatusCodeOkExamples(examples Examples) Examples {
	result := Examples{}

	for _, e := range examples {
		if e.StatusCode == 200 {
			result = append(result, e)
		}
	}

	return result
}
<|endoftext|>


<commit_before>// Copyright (c) 2016 Jeevanandam M (https://github.com/jeevatkm)
// resty source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.

package log

import (
	"bytes"
	"fmt"
	"io"
	"os"
	"strings"
)

func strIsEmpty(v string) bool {
	return len(strings.TrimSpace(v)) == 0
}

func closeSilently(v interface{}) {
	if d, ok := v.(io.Closer); ok {
		_ = d.Close()
	}
}

func lines(fileName string) int {
	f, err := os.Open(fileName)
	if err != nil {
		return 0
	}
	defer closeSilently(f)

	buf := make([]byte, 8196)
	count := 0
	lineSep := []byte{'\n'}

	for {
		c, err := f.Read(buf)
		if err != nil && err != io.EOF {
			return count
		}

		count += bytes.Count(buf[:c], lineSep)

		if err == io.EOF {
			break
		}
	}

	return count
}

// createDir method creates nested directories if not exists
func mkDirAll(path string) error {
	if _, err := os.Lstat(path); err != nil {
		if os.IsNotExist(err) {
			if err = os.MkdirAll(path, filePermission); err != nil {
				return fmt.Errorf("unable to create directory '%v': %v", path, err)
			}
		} else {
			return fmt.Errorf("unable to create directory '%v': %v", path, err)
		}
	}
	return nil
}
<commit_msg>godoc update<commit_after>// Copyright (c) 2016 Jeevanandam M (https://github.com/jeevatkm)
// resty source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.

package log

import (
	"bytes"
	"fmt"
	"io"
	"os"
	"strings"
)

func strIsEmpty(v string) bool {
	return len(strings.TrimSpace(v)) == 0
}

func closeSilently(v interface{}) {
	if d, ok := v.(io.Closer); ok {
		_ = d.Close()
	}
}

func lines(fileName string) int {
	f, err := os.Open(fileName)
	if err != nil {
		return 0
	}
	defer closeSilently(f)

	buf := make([]byte, 8196)
	count := 0
	lineSep := []byte{'\n'}

	for {
		c, err := f.Read(buf)
		if err != nil && err != io.EOF {
			return count
		}

		count += bytes.Count(buf[:c], lineSep)

		if err == io.EOF {
			break
		}
	}

	return count
}

// mkDirAll method creates nested directories if not exists
func mkDirAll(path string) error {
	if _, err := os.Lstat(path); err != nil {
		if os.IsNotExist(err) {
			if err = os.MkdirAll(path, filePermission); err != nil {
				return fmt.Errorf("unable to create directory '%v': %v", path, err)
			}
		} else {
			return fmt.Errorf("unable to create directory '%v': %v", path, err)
		}
	}
	return nil
}
<|endoftext|>


<commit_before>package docli

import (
	"bufio"
	"bytes"
	"encoding/json"
	"flag"
	"io"

	"github.com/codegangsta/cli"
	"github.com/digitalocean/godo"
	"golang.org/x/oauth2"
)

var DefaultClientSource ClientSource = &LiveClientSource{}

type TokenSource struct {
	AccessToken string
}

type TestClientSource struct {
	Client *godo.Client
}

func (cs *TestClientSource) NewClient(_ string) *godo.Client {
	return cs.Client
}

func (t *TokenSource) Token() (*oauth2.Token, error) {
	return &oauth2.Token{
		AccessToken: t.AccessToken,
	}, nil
}

func LoadOpts(c *cli.Context) *Opts {
	return &Opts{
		Debug: c.GlobalBool("debug"),
	}
}

func WriteJSON(item interface{}, w io.Writer) error {
	b, err := json.Marshal(item)
	if err != nil {
		return err
	}

	var out bytes.Buffer
	json.Indent(&out, b, "", "  ")
	_, err = out.WriteTo(w)
	return err

}

func ToJSON(item interface{}) (string, error) {
	b, err := json.MarshalIndent(item, "", "  ")
	if err != nil {
		return "", err
	}

	return string(b), nil
}

type ClientSource interface {
	NewClient(token string) *godo.Client
}

type LiveClientSource struct{}

func (cs *LiveClientSource) NewClient(token string) *godo.Client {
	tokenSource := &TokenSource{
		AccessToken: token,
	}

	oauthClient := oauth2.NewClient(oauth2.NoContext, tokenSource)
	return godo.NewClient(oauthClient)
}

func NewClient(c *cli.Context, cs ClientSource) *godo.Client {
	if cs == nil {
		cs = &LiveClientSource{}
	}

	pat := c.GlobalString("token")
	return cs.NewClient(pat)
}

func WithinTest(cs ClientSource, fs *flag.FlagSet, fn func(*cli.Context)) {
	ogSource := DefaultClientSource
	DefaultClientSource = cs

	defer func() {
		DefaultClientSource = ogSource
	}()

	var b bytes.Buffer
	app := cli.NewApp()
	app.Writer = bufio.NewWriter(&b)

	globalSet := flag.NewFlagSet("global test", 0)
	globalSet.String("token", "token", "token")

	if fs == nil {
		fs = flag.NewFlagSet("local test", 0)
	}

	c := cli.NewContext(app, fs, globalSet)

	fn(c)
}
<commit_msg>update to use global context<commit_after>package docli

import (
	"bufio"
	"bytes"
	"encoding/json"
	"flag"
	"io"

	"github.com/codegangsta/cli"
	"github.com/digitalocean/godo"
	"golang.org/x/oauth2"
)

var DefaultClientSource ClientSource = &LiveClientSource{}

type TokenSource struct {
	AccessToken string
}

type TestClientSource struct {
	Client *godo.Client
}

func (cs *TestClientSource) NewClient(_ string) *godo.Client {
	return cs.Client
}

func (t *TokenSource) Token() (*oauth2.Token, error) {
	return &oauth2.Token{
		AccessToken: t.AccessToken,
	}, nil
}

func LoadOpts(c *cli.Context) *Opts {
	return &Opts{
		Debug: c.GlobalBool("debug"),
	}
}

func WriteJSON(item interface{}, w io.Writer) error {
	b, err := json.Marshal(item)
	if err != nil {
		return err
	}

	var out bytes.Buffer
	json.Indent(&out, b, "", "  ")
	_, err = out.WriteTo(w)
	return err

}

func ToJSON(item interface{}) (string, error) {
	b, err := json.MarshalIndent(item, "", "  ")
	if err != nil {
		return "", err
	}

	return string(b), nil
}

type ClientSource interface {
	NewClient(token string) *godo.Client
}

type LiveClientSource struct{}

func (cs *LiveClientSource) NewClient(token string) *godo.Client {
	tokenSource := &TokenSource{
		AccessToken: token,
	}

	oauthClient := oauth2.NewClient(oauth2.NoContext, tokenSource)
	return godo.NewClient(oauthClient)
}

func NewClient(c *cli.Context, cs ClientSource) *godo.Client {
	if cs == nil {
		cs = &LiveClientSource{}
	}

	pat := c.GlobalString("token")
	return cs.NewClient(pat)
}

func WithinTest(cs ClientSource, fs *flag.FlagSet, fn func(*cli.Context)) {
	ogSource := DefaultClientSource
	DefaultClientSource = cs

	defer func() {
		DefaultClientSource = ogSource
	}()

	var b bytes.Buffer
	app := cli.NewApp()
	app.Writer = bufio.NewWriter(&b)

	globalSet := flag.NewFlagSet("global test", 0)
	globalSet.String("token", "token", "token")

	globalCtx := cli.NewContext(app, globalSet, nil)

	if fs == nil {
		fs = flag.NewFlagSet("local test", 0)
	}

	c := cli.NewContext(app, fs, globalCtx)

	fn(c)
}
<|endoftext|>


<commit_before>package dpdk

/*
#include <rte_config.h>
#include <rte_malloc.h>
*/
import "C"
import "unsafe"

func GetCArray(n uint) *unsafe.Pointer {
	var p *unsafe.Pointer
	arr := C.rte_malloc((*C.char)(nil), C.size_t(n)*C.size_t(unsafe.Sizeof(p)), C.unsigned(0))
	return (*unsafe.Pointer)(arr)
}

func SliceFromCArray(arr *unsafe.Pointer, n uint) []unsafe.Pointer {
	return (*[1 << 30](unsafe.Pointer))(unsafe.Pointer(arr))[:n:n]
}
<commit_msg>util: Add rte_errno error string helper<commit_after>package dpdk

/*
#include <rte_config.h>
#include <rte_malloc.h>
#include <rte_errno.h>
*/
import "C"
import "unsafe"

func GetCArray(n uint) *unsafe.Pointer {
	var p *unsafe.Pointer
	arr := C.rte_malloc((*C.char)(nil), C.size_t(n)*C.size_t(unsafe.Sizeof(p)), C.unsigned(0))
	return (*unsafe.Pointer)(arr)
}

func SliceFromCArray(arr *unsafe.Pointer, n uint) []unsafe.Pointer {
	return (*[1 << 30](unsafe.Pointer))(unsafe.Pointer(arr))[:n:n]
}

func StrError(errno int) string {
    return C.GoString(C.rte_strerror(C.int(errno)))
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 Dmitry Chestnykh
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

// UUID package implements UUID (version 4, random) type and methods for the manipulation of it.
package uuid

import (
	"fmt"
	"crypto/rand"
	"encoding/hex"
	"os"
	"strings"
)

const (
	UUIDLen = 16
)

type UUID [UUIDLen]byte

// New generates and returns new UUID v4 (generated randomly).
func New() (u UUID) {
	rand.Read(u[:])
	u[6] = u[6]>>4 | 0x40 // set version number
	u[8] &^= 1 << 6       // set 6th bit to 0
	u[8] |= 1 << 7        // set 7th bit to 1
	return
}

// NewShortString converts a short string (hex uuid without dashes) to UUID.
func NewShortString(s string) (u UUID, err os.Error) {
	b := []byte(s)
	if hex.DecodedLen(len(s)) != UUIDLen {
		err = os.NewError("uuid: wrong string length for decode")
		return
	}
	_, err = hex.Decode(u[:], b)
	return
}

// NewShortString converts a string (hex uuid, can include dashes) to UUID.
func NewString(s string) (UUID, os.Error) {
	s = strings.Replace(s, "-", "", -1)
	return NewShortString(s)
}

// String returns string representation of UUID.
// Example: b7c016dc-2ba4-a68d-b368-a97da9f43cee
func (u UUID) String() string {
	return fmt.Sprintf("%x-%x-%x-%x-%x", u[:4], u[4:6], u[6:8], u[8:10], u[10:])
}

// ShortString returns short string representation (without dashes) of UUID.
// Example: b7c016dc2ba4a68db368a97da9f43cee
func (u UUID) ShortString() string {
	return fmt.Sprintf("%x", u[:])
}

// Bytes returns a byte slice of UUID.
func (u UUID) Bytes() []byte {
	return u[:]
}

// Equal returns a boolean reporting whether UUID equals another one (a).
func (u UUID) Equal(a UUID) bool {
	for i, v := range u {
		if v != a[i] {
			return false
		}
	}
	return true
}

// MarshalJSON encodes UUID pointer into JSON representation.
func (u *UUID) MarshalJSON() ([]byte, os.Error) {
	return []byte("\"" + u.ShortString() + "\""), nil
}

// UnmarshalJSON decodes UUID pointer from JSON representation.
func (u *UUID) UnmarshalJSON(b []byte) os.Error {
	if len(b) < 3 {
		return os.NewError("uuid: JSON value is too short for UUID")
	}
	x, err := NewShortString(string(b[1 : len(b)-1]))
	copy((*u)[:], x[:])
	return err
}
<commit_msg>Use io.ReadFull to read from random source.<commit_after>// Copyright (c) 2011 Dmitry Chestnykh
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

// UUID package implements UUID (version 4, random) type and methods for the manipulation of it.
package uuid

import (
	"fmt"
	"crypto/rand"
	"encoding/hex"
	"os"
	"strings"
)

const (
	UUIDLen = 16
)

type UUID [UUIDLen]byte

// New generates and returns new UUID v4 (generated randomly).
func New() (u UUID) {
	if _, err := io.ReadFull(rand.Reader, u[:]); err != nil {
		panic("error reading from random source: " + err.String())
	}
	u[6] = u[6]>>4 | 0x40 // set version number
	u[8] &^= 1 << 6       // set 6th bit to 0
	u[8] |= 1 << 7        // set 7th bit to 1
	return
}

// NewShortString converts a short string (hex uuid without dashes) to UUID.
func NewShortString(s string) (u UUID, err os.Error) {
	b := []byte(s)
	if hex.DecodedLen(len(s)) != UUIDLen {
		err = os.NewError("uuid: wrong string length for decode")
		return
	}
	_, err = hex.Decode(u[:], b)
	return
}

// NewShortString converts a string (hex uuid, can include dashes) to UUID.
func NewString(s string) (UUID, os.Error) {
	s = strings.Replace(s, "-", "", -1)
	return NewShortString(s)
}

// String returns string representation of UUID.
// Example: b7c016dc-2ba4-a68d-b368-a97da9f43cee
func (u UUID) String() string {
	return fmt.Sprintf("%x-%x-%x-%x-%x", u[:4], u[4:6], u[6:8], u[8:10], u[10:])
}

// ShortString returns short string representation (without dashes) of UUID.
// Example: b7c016dc2ba4a68db368a97da9f43cee
func (u UUID) ShortString() string {
	return fmt.Sprintf("%x", u[:])
}

// Bytes returns a byte slice of UUID.
func (u UUID) Bytes() []byte {
	return u[:]
}

// Equal returns a boolean reporting whether UUID equals another one (a).
func (u UUID) Equal(a UUID) bool {
	for i, v := range u {
		if v != a[i] {
			return false
		}
	}
	return true
}

// MarshalJSON encodes UUID pointer into JSON representation.
func (u *UUID) MarshalJSON() ([]byte, os.Error) {
	return []byte("\"" + u.ShortString() + "\""), nil
}

// UnmarshalJSON decodes UUID pointer from JSON representation.
func (u *UUID) UnmarshalJSON(b []byte) os.Error {
	if len(b) < 3 {
		return os.NewError("uuid: JSON value is too short for UUID")
	}
	x, err := NewShortString(string(b[1 : len(b)-1]))
	copy((*u)[:], x[:])
	return err
}
<|endoftext|>


<commit_before>package tql
import (
    "errors"
    "math"
)

const (
	ValString = iota
	ValInt
	ValFloat
	ValQuoteString
	ValBool
	ValNull
	ValReference
	ValList
)

type Val struct {
	ValType int
	V     interface{}
}

var ErrTypeNotMatch = errors.New("type not match")

func (v Val) LT(v1 interface{}) (bool, error) {
    switch v.ValType {
        case ValInt:
            return v.V.(int64) < v1.(int64), nil
        case ValFloat:
            return v.V.(float64) < v1.(float64), nil
    }
    return false, ErrTypeNotMatch
}

func (v Val) GT(v1 interface{}) (bool, error) {
    switch v.ValType {
        case ValInt:
            return v.V.(int64) > v1.(int64), nil
        case ValFloat:
            return v.V.(float64) > v1.(float64), nil
    }
    return false, ErrTypeNotMatch
}

func (v Val) EQ(v1 interface{}) (bool, error) {
    switch v.ValType {
        case ValInt:
            return v.V.(int64) == v1.(int64), nil
        case ValFloat:
            return math.Abs(v.V.(float64) - v1.(float64)) < 1e-7, nil
        case ValQuoteString:
            return v.V.(string) == v1.(string), nil
    }
    return false, ErrTypeNotMatch
}

func (v Val) NOTEQ(v1 interface{}) (bool, error) {
    return true, nil
}

func (v Val) LTE(v1 interface{}) (bool, error) {
    b, err := v.GT(v1)
    return !b, err
}

func (v Val) GTE(v1 interface{}) (bool, error) {
    b, err := v.LT(v1)
    return !b, err
}

<commit_msg>implement not eq<commit_after>package tql
import (
    "errors"
    "math"
)

const (
	ValString = iota
	ValInt
	ValFloat
	ValQuoteString
	ValBool
	ValNull
	ValReference
	ValList
)

type Val struct {
	ValType int
	V     interface{}
}

var ErrTypeNotMatch = errors.New("type not match")

func (v Val) LT(v1 interface{}) (bool, error) {
    switch v.ValType {
        case ValInt:
            return v.V.(int64) < v1.(int64), nil
        case ValFloat:
            return v.V.(float64) < v1.(float64), nil
    }
    return false, ErrTypeNotMatch
}

func (v Val) GT(v1 interface{}) (bool, error) {
    switch v.ValType {
        case ValInt:
            return v.V.(int64) > v1.(int64), nil
        case ValFloat:
            return v.V.(float64) > v1.(float64), nil
    }
    return false, ErrTypeNotMatch
}

func (v Val) EQ(v1 interface{}) (bool, error) {
    switch v.ValType {
        case ValInt:
            return v.V.(int64) == v1.(int64), nil
        case ValFloat:
            return math.Abs(v.V.(float64) - v1.(float64)) < 1e-7, nil
        case ValQuoteString:
            return v.V.(string) == v1.(string), nil
    }
    return false, ErrTypeNotMatch
}

func (v Val) NOTEQ(v1 interface{}) (bool, error) {
    b, err := v.EQ(v1)
    return !b, err
}

func (v Val) LTE(v1 interface{}) (bool, error) {
    b, err := v.GT(v1)
    return !b, err
}

func (v Val) GTE(v1 interface{}) (bool, error) {
    b, err := v.LT(v1)
    return !b, err
}

<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"math"
	"strings"

	"github.com/nsf/termbox-go"
)

// Colors
const backgroundColor = termbox.ColorBlue
const boardColor = termbox.ColorBlack
const instructionsColor = termbox.ColorYellow

var pieceColors = []termbox.Attribute{
	termbox.ColorBlack,
	termbox.ColorRed,
	termbox.ColorGreen,
	termbox.ColorYellow,
	termbox.ColorBlue,
	termbox.ColorMagenta,
	termbox.ColorCyan,
	termbox.ColorWhite,
}

// Layout
const defaultMarginWidth = 2
const defaultMarginHeight = 1
const titleStartX = defaultMarginWidth
const titleStartY = defaultMarginHeight
const titleHeight = 1
const titleEndY = titleStartY + titleHeight
const boardStartX = defaultMarginWidth
const boardStartY = titleEndY + defaultMarginHeight
const boardWidth = 10
const boardHeight = 16
const cellWidth = 2
const boardEndX = boardStartX + boardWidth*cellWidth
const boardEndY = boardStartY + boardHeight
const instructionsStartX = boardEndX + defaultMarginWidth
const instructionsStartY = boardStartY

// Text in the UI
const title = "TETRIS WRITTEN IN GO"

var instructions = []string{
	"Goal: Fill in 5 lines!",
	"",
	"\u2190      Left",
	"\u2192      Right",
	"\u2191      Rotate",
	"\u2193      Down",
	"Space  Fall",
	"s      Start",
	"p      Pause",
	"esc    Exit",
	"",
	"Level: %v",
	"Lines: %v",
	"",
	"GAME OVER!",
}

// This takes care of rendering everything.
func render(g *Game) {
	termbox.Clear(backgroundColor, backgroundColor)
	tbprint(titleStartX, titleStartY, instructionsColor, backgroundColor, title)
	for y := 0; y < boardHeight; y++ {
		for x := 0; x < boardWidth; x++ {
			cellValue := g.board[y][x]
			absCellValue := int(math.Abs(float64(cellValue)))
			cellColor := pieceColors[absCellValue]
			for i := 0; i < cellWidth; i++ {
				termbox.SetCell(boardStartX+cellWidth*x+i, boardStartY+y, ' ', cellColor, cellColor)
			}
		}
	}
	for y, instruction := range instructions {
		if strings.HasPrefix(instruction, "Level:") {
			instruction = fmt.Sprintf(instruction, g.level)
		} else if strings.HasPrefix(instruction, "Lines:") {
			instruction = fmt.Sprintf(instruction, g.numLines)
		} else if strings.HasPrefix(instruction, "GAME OVER") && g.state != gameOver {
			instruction = ""
		}
		tbprint(instructionsStartX, instructionsStartY+y, instructionsColor, backgroundColor, instruction)
	}
	termbox.Flush()
}

// Function tbprint draws a string.
func tbprint(x, y int, fg, bg termbox.Attribute, msg string) {
	for _, c := range msg {
		termbox.SetCell(x, y, c, fg, bg)
		x++
	}
}
<commit_msg>Don't use unicode arrows--doesn't work well on Windows<commit_after>package main

import (
	"fmt"
	"math"
	"strings"

	"github.com/nsf/termbox-go"
)

// Colors
const backgroundColor = termbox.ColorBlue
const boardColor = termbox.ColorBlack
const instructionsColor = termbox.ColorYellow

var pieceColors = []termbox.Attribute{
	termbox.ColorBlack,
	termbox.ColorRed,
	termbox.ColorGreen,
	termbox.ColorYellow,
	termbox.ColorBlue,
	termbox.ColorMagenta,
	termbox.ColorCyan,
	termbox.ColorWhite,
}

// Layout
const defaultMarginWidth = 2
const defaultMarginHeight = 1
const titleStartX = defaultMarginWidth
const titleStartY = defaultMarginHeight
const titleHeight = 1
const titleEndY = titleStartY + titleHeight
const boardStartX = defaultMarginWidth
const boardStartY = titleEndY + defaultMarginHeight
const boardWidth = 10
const boardHeight = 16
const cellWidth = 2
const boardEndX = boardStartX + boardWidth*cellWidth
const boardEndY = boardStartY + boardHeight
const instructionsStartX = boardEndX + defaultMarginWidth
const instructionsStartY = boardStartY

// Text in the UI
const title = "TETRIS WRITTEN IN GO"

var instructions = []string{
	"Goal: Fill in 5 lines!",
	"",
	"left   Left",
	"right  Right",
	"up     Rotate",
	"down   Down",
	"space  Fall",
	"s      Start",
	"p      Pause",
	"esc    Exit",
	"",
	"Level: %v",
	"Lines: %v",
	"",
	"GAME OVER!",
}

// This takes care of rendering everything.
func render(g *Game) {
	termbox.Clear(backgroundColor, backgroundColor)
	tbprint(titleStartX, titleStartY, instructionsColor, backgroundColor, title)
	for y := 0; y < boardHeight; y++ {
		for x := 0; x < boardWidth; x++ {
			cellValue := g.board[y][x]
			absCellValue := int(math.Abs(float64(cellValue)))
			cellColor := pieceColors[absCellValue]
			for i := 0; i < cellWidth; i++ {
				termbox.SetCell(boardStartX+cellWidth*x+i, boardStartY+y, ' ', cellColor, cellColor)
			}
		}
	}
	for y, instruction := range instructions {
		if strings.HasPrefix(instruction, "Level:") {
			instruction = fmt.Sprintf(instruction, g.level)
		} else if strings.HasPrefix(instruction, "Lines:") {
			instruction = fmt.Sprintf(instruction, g.numLines)
		} else if strings.HasPrefix(instruction, "GAME OVER") && g.state != gameOver {
			instruction = ""
		}
		tbprint(instructionsStartX, instructionsStartY+y, instructionsColor, backgroundColor, instruction)
	}
	termbox.Flush()
}

// Function tbprint draws a string.
func tbprint(x, y int, fg, bg termbox.Attribute, msg string) {
	for _, c := range msg {
		termbox.SetCell(x, y, c, fg, bg)
		x++
	}
}
<|endoftext|>


<commit_before>package couchdb

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/google/go-querystring/query"
)

// Execute specified view function from specified design document.
func (v *View) Get(name string, params QueryParameters) (*ViewResponse, error) {
	q, err := query.Values(params)
	if err != nil {
		return nil, err
	}
	uri := fmt.Sprintf("%s_view/%s?%s", v.Url, name, q.Encode())
	body, err := request("GET", uri, nil, "")
	if err != nil {
		return nil, err
	}
	return newViewResponse(body)
}

// Execute specified view function from specified design document.
// Unlike View.Get for accessing views, View.Post supports
// the specification of explicit keys to be retrieved from the view results.
func (v *View) Post(name string, keys []string, params QueryParameters) (*ViewResponse, error) {
	// create POST body
	res, err := json.Marshal(keys)
	if err != nil {
		return nil, err
	}
	// create query string
	q, err := query.Values(params)
	if err != nil {
		return nil, err
	}
	url := fmt.Sprintf("%s_view/%s?%s", v.Url, name, q.Encode())
	data := bytes.NewReader(res)
	body, err := request("GET", url, data, "application/json")
	if err != nil {
		return nil, err
	}
	return newViewResponse(body)
}

func newViewResponse(body []byte) (*ViewResponse, error) {
	var response *ViewResponse
	return response, json.Unmarshal(body, &response)
}
<commit_msg>use double quoted query string for view functions<commit_after>package couchdb

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/google/go-querystring/query"
)

// Execute specified view function from specified design document.
func (v *View) Get(name string, params QueryParameters) (*ViewResponse, error) {
	q, err := query.Values(params)
	if err != nil {
		return nil, err
	}
	quoted := quote(q)
	uri := fmt.Sprintf("%s_view/%s?%s", v.Url, name, quoted.Encode())
	body, err := request("GET", uri, nil, "")
	if err != nil {
		return nil, err
	}
	return newViewResponse(body)
}

// Execute specified view function from specified design document.
// Unlike View.Get for accessing views, View.Post supports
// the specification of explicit keys to be retrieved from the view results.
func (v *View) Post(name string, keys []string, params QueryParameters) (*ViewResponse, error) {
	// create POST body
	res, err := json.Marshal(keys)
	if err != nil {
		return nil, err
	}
	// create query string
	q, err := query.Values(params)
	if err != nil {
		return nil, err
	}
	quoted := quote(q)
	url := fmt.Sprintf("%s_view/%s?%s", v.Url, name, quoted.Encode())
	data := bytes.NewReader(res)
	body, err := request("GET", url, data, "application/json")
	if err != nil {
		return nil, err
	}
	return newViewResponse(body)
}

func newViewResponse(body []byte) (*ViewResponse, error) {
	var response *ViewResponse
	return response, json.Unmarshal(body, &response)
}
<|endoftext|>


<commit_before>// Package vlog add leveled log on std log(golang.org/pkg/log/)
// It implements most std log functions(except logger), variables
// and add provides V-style logging controlled by the -v flag or SetLogLevel()
// If flag.Parse be called before any logging, -v flag(default 0) use automaticlly.

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

// Basic examples:
//  vlog.SetLogLevel(3)
//  vlog.GetLogLevel()
//
//	vlog.Println("Prepare to repel boarders")
//
//	vlog.Fatalf("Initialization failed: %s", err)
//
// See the documentation for the V function for an explanation of these examples:
//
//	if vlog.V(2) {
//		vlog.Print("Starting transaction...")
//	}
//
//	vlog.V(2).Println("Processed", nItems, "elements")
package vlog

import (
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"strconv"
)

// These flags define which text to prefix to each log entry generated by the Logger.
const (
	// Bits or'ed together to control what's printed.
	// There is no control over the order they appear (the order listed
	// here) or the format they present (as described in the comments).
	// The prefix is followed by a colon only when Llongfile or Lshortfile
	// is specified.
	// For example, flags Ldate | Ltime (or LstdFlags) produce,
	//	2009/01/23 01:23:23 message
	// while flags Ldate | Ltime | Lmicroseconds | Llongfile produce,
	//	2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message
	Ldate         = log.Ldate             // the date in the local time zone: 2009/01/23
	Ltime         = log.Ltime             // the time in the local time zone: 01:23:23
	Lmicroseconds = log.Lmicroseconds     // microsecond resolution: 01:23:23.123123.  assumes Ltime.
	Llongfile     = log.Llongfile         // full file name and line number: /a/b/c/d.go:23
	Lshortfile    = log.Lshortfile        // final file name element and line number: d.go:23. overrides Llongfile
	LUTC          = log.LUTC              // if Ldate or Ltime is set, use UTC rather than the local time zone
	LstdFlags     = log.Ldate | log.Ltime // initial values for the standard logger
)

var (
	level Level

	vParsed bool

	std = log.New(os.Stderr, "", LstdFlags)
)

func init() {
	flag.Var(&level, "v", "log level for V logs(default 0)")
}

type Level int32

// String is part of the flag.Value interface.
func (l *Level) String() string {
	return strconv.FormatInt(int64(*l), 10)
}

// Get is part of the flag.Value interface.
func (l *Level) Get() interface{} {
	return int32(*l)
}

// Set is part of the flag.Value interface.
func (l *Level) Set(value string) error {
	v, err := strconv.ParseInt(value, 0, 32)
	if err != nil {
		return err
	}
	*l = Level(v)
	vParsed = true
	return nil
}

// Set log level, just use at parameter initialize zone.
func SetLogLevel(v Level) {
	level = v
}

// Get log level, just use at parameter initialize zone.
func GetLogLevel() Level {
	return level
}

// Get bool, whether be parsed for command line(use or not use -v flag)
func IsLevelParsed() bool {
	return vParsed
}

// Verbose is a boolean type that implements Print like function.
// See the documentation of V for more information.
type Verbose bool

// Whether an individual call to V generates a log record depends on the setting of level.
func V(v Level) Verbose {
	if v <= level {
		return true
	}
	return false
}

func (vb Verbose) Printf(format string, v ...interface{}) {
	if vb {
		std.Output(2, fmt.Sprintf(format, v...))
	}
}

func (vb Verbose) Println(v ...interface{}) {
	if vb {
		std.Output(2, fmt.Sprintln(v...))
	}
}

func (vb Verbose) Print(v ...interface{}) {
	if vb {
		std.Output(2, fmt.Sprint(v...))
	}
}

// SetOutput sets the output destination for the standard logger.
func SetOutput(w io.Writer) {
	std.SetOutput(w)
}

// Flags returns the output flags for the standard logger.
func Flags() int {
	return std.Flags()
}

// SetFlags sets the output flags for the standard logger.
func SetFlags(flag int) {
	std.SetFlags(flag)
}

// Prefix returns the output prefix for the standard logger.
func Prefix() string {
	return std.Prefix()
}

// SetPrefix sets the output prefix for the standard logger.
func SetPrefix(prefix string) {
	std.SetPrefix(prefix)
}

// These functions write to the standard logger.

// Print calls Output to print to the standard logger.
// Arguments are handled in the manner of fmt.Print.
func Print(v ...interface{}) {
	std.Output(2, fmt.Sprint(v...))
}

// Printf calls Output to print to the standard logger.
// Arguments are handled in the manner of fmt.Printf.
func Printf(format string, v ...interface{}) {
	std.Output(2, fmt.Sprintf(format, v...))
}

// Println calls Output to print to the standard logger.
// Arguments are handled in the manner of fmt.Println.
func Println(v ...interface{}) {
	std.Output(2, fmt.Sprintln(v...))
}

// Fatal is equivalent to Print() followed by a call to os.Exit(1).
func Fatal(v ...interface{}) {
	std.Output(2, fmt.Sprint(v...))
	os.Exit(1)
}

// Fatalf is equivalent to Printf() followed by a call to os.Exit(1).
func Fatalf(format string, v ...interface{}) {
	std.Output(2, fmt.Sprintf(format, v...))
	os.Exit(1)
}

// Fatalln is equivalent to Println() followed by a call to os.Exit(1).
func Fatalln(v ...interface{}) {
	std.Output(2, fmt.Sprintln(v...))
	os.Exit(1)
}

// Panic is equivalent to Print() followed by a call to panic().
func Panic(v ...interface{}) {
	s := fmt.Sprint(v...)
	std.Output(2, s)
	panic(s)
}

// Panicf is equivalent to Printf() followed by a call to panic().
func Panicf(format string, v ...interface{}) {
	s := fmt.Sprintf(format, v...)
	std.Output(2, s)
	panic(s)
}

// Panicln is equivalent to Println() followed by a call to panic().
func Panicln(v ...interface{}) {
	s := fmt.Sprintln(v...)
	std.Output(2, s)
	panic(s)
}

// Output writes the output for a logging event.  The string s contains
// the text to print after the prefix specified by the flags of the
// Logger.  A newline is appended if the last character of s is not
// already a newline.  Calldepth is the count of the number of
// frames to skip when computing the file name and line number
// if Llongfile or Lshortfile is set; a value of 1 will print the details
// for the caller of Output.
func Output(calldepth int, s string) error {
	return std.Output(calldepth+1, s) // +1 for this frame.
}
<commit_msg>change comment doc<commit_after>// Package vlog add leveled log on std log(golang.org/pkg/log/)
// It implements most std log functions(except logger), variables
// and add provides V-style logging controlled by the -v flag or SetLogLevel()
// If flag.Parse be called before any logging, -v flag(default 0) use automaticlly.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Basic examples:
//  vlog.SetLogLevel(3)
//  vlog.GetLogLevel()
//
//	vlog.Println("Prepare to repel boarders")
//
//	vlog.Fatalf("Initialization failed: %s", err)
//
// See the documentation for the V function for an explanation of these examples:
//
//	if vlog.V(2) {
//		vlog.Print("Starting transaction...")
//	}
//
//	vlog.V(2).Println("Processed", nItems, "elements")
package vlog

import (
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"strconv"
)

// These flags define which text to prefix to each log entry generated by the Logger.
const (
	// Bits or'ed together to control what's printed.
	// There is no control over the order they appear (the order listed
	// here) or the format they present (as described in the comments).
	// The prefix is followed by a colon only when Llongfile or Lshortfile
	// is specified.
	// For example, flags Ldate | Ltime (or LstdFlags) produce,
	//	2009/01/23 01:23:23 message
	// while flags Ldate | Ltime | Lmicroseconds | Llongfile produce,
	//	2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message
	Ldate         = log.Ldate             // the date in the local time zone: 2009/01/23
	Ltime         = log.Ltime             // the time in the local time zone: 01:23:23
	Lmicroseconds = log.Lmicroseconds     // microsecond resolution: 01:23:23.123123.  assumes Ltime.
	Llongfile     = log.Llongfile         // full file name and line number: /a/b/c/d.go:23
	Lshortfile    = log.Lshortfile        // final file name element and line number: d.go:23. overrides Llongfile
	LUTC          = log.LUTC              // if Ldate or Ltime is set, use UTC rather than the local time zone
	LstdFlags     = log.Ldate | log.Ltime // initial values for the standard logger
)

var (
	level Level

	vParsed bool

	std = log.New(os.Stderr, "", LstdFlags)
)

func init() {
	flag.Var(&level, "v", "log level for V logs(default 0)")
}

// Level log level
type Level int32

// String is part of the flag.Value interface.
func (l *Level) String() string {
	return strconv.FormatInt(int64(*l), 10)
}

// Get is part of the flag.Value interface.
func (l *Level) Get() interface{} {
	return int32(*l)
}

// Set is part of the flag.Value interface.
func (l *Level) Set(value string) error {
	v, err := strconv.ParseInt(value, 0, 32)
	if err != nil {
		return err
	}
	*l = Level(v)
	vParsed = true
	return nil
}

// SetLogLevel set log level, just use at parameter initialize zone.
func SetLogLevel(v Level) {
	level = v
}

// GetLogLevel get log level, just use at parameter initialize zone.
func GetLogLevel() Level {
	return level
}

// IsLevelParsed get bool, whether be parsed for command line(use or not use -v flag)
func IsLevelParsed() bool {
	return vParsed
}

// Verbose is a boolean type that implements Print like function.
// See the documentation of V for more information.
type Verbose bool

// V function return Verbose,
// whether an individual call to V generates a log record depends on the setting of level.
func V(v Level) Verbose {
	if v <= level {
		return true
	}
	return false
}

// Printf calls Output to print to the standard logger.
// Arguments are handled in the manner of fmt.Printf.
func (vb Verbose) Printf(format string, v ...interface{}) {
	if vb {
		std.Output(2, fmt.Sprintf(format, v...))
	}
}

// Println calls Output to print to the standard logger.
// Arguments are handled in the manner of fmt.Println.
func (vb Verbose) Println(v ...interface{}) {
	if vb {
		std.Output(2, fmt.Sprintln(v...))
	}
}

// Print calls Output to print to the standard logger.
// Arguments are handled in the manner of fmt.Print.
func (vb Verbose) Print(v ...interface{}) {
	if vb {
		std.Output(2, fmt.Sprint(v...))
	}
}

// SetOutput sets the output destination for the standard logger.
func SetOutput(w io.Writer) {
	std.SetOutput(w)
}

// Flags returns the output flags for the standard logger.
func Flags() int {
	return std.Flags()
}

// SetFlags sets the output flags for the standard logger.
func SetFlags(flag int) {
	std.SetFlags(flag)
}

// Prefix returns the output prefix for the standard logger.
func Prefix() string {
	return std.Prefix()
}

// SetPrefix sets the output prefix for the standard logger.
func SetPrefix(prefix string) {
	std.SetPrefix(prefix)
}

// These functions write to the standard logger.

// Print calls Output to print to the standard logger.
// Arguments are handled in the manner of fmt.Print.
func Print(v ...interface{}) {
	std.Output(2, fmt.Sprint(v...))
}

// Printf calls Output to print to the standard logger.
// Arguments are handled in the manner of fmt.Printf.
func Printf(format string, v ...interface{}) {
	std.Output(2, fmt.Sprintf(format, v...))
}

// Println calls Output to print to the standard logger.
// Arguments are handled in the manner of fmt.Println.
func Println(v ...interface{}) {
	std.Output(2, fmt.Sprintln(v...))
}

// Fatal is equivalent to Print() followed by a call to os.Exit(1).
func Fatal(v ...interface{}) {
	std.Output(2, fmt.Sprint(v...))
	os.Exit(1)
}

// Fatalf is equivalent to Printf() followed by a call to os.Exit(1).
func Fatalf(format string, v ...interface{}) {
	std.Output(2, fmt.Sprintf(format, v...))
	os.Exit(1)
}

// Fatalln is equivalent to Println() followed by a call to os.Exit(1).
func Fatalln(v ...interface{}) {
	std.Output(2, fmt.Sprintln(v...))
	os.Exit(1)
}

// Panic is equivalent to Print() followed by a call to panic().
func Panic(v ...interface{}) {
	s := fmt.Sprint(v...)
	std.Output(2, s)
	panic(s)
}

// Panicf is equivalent to Printf() followed by a call to panic().
func Panicf(format string, v ...interface{}) {
	s := fmt.Sprintf(format, v...)
	std.Output(2, s)
	panic(s)
}

// Panicln is equivalent to Println() followed by a call to panic().
func Panicln(v ...interface{}) {
	s := fmt.Sprintln(v...)
	std.Output(2, s)
	panic(s)
}

// Output writes the output for a logging event.  The string s contains
// the text to print after the prefix specified by the flags of the
// Logger.  A newline is appended if the last character of s is not
// already a newline.  Calldepth is the count of the number of
// frames to skip when computing the file name and line number
// if Llongfile or Lshortfile is set; a value of 1 will print the details
// for the caller of Output.
func Output(calldepth int, s string) error {
	return std.Output(calldepth+1, s) // +1 for this frame.
}
<|endoftext|>


<commit_before>// Packet vlog provides package level verbose logging.
// The actual logging is done with the standard log package.
//
// To define a package level logging variable,
//   var v = vlog.New()
//
// To log a message at INFO level,
//   v.I("a")
//
// The logging level can be set with either the flag -vlog or
// the environment variable GO_VLOG.
//
// The -vlog or GO_VLOG format is,
//  k=v(,k=v)*
//  k can be exact match like "foo/bar" or prefix match like "foo/*".
//  v can be w|i|v1|v2
// Default level can be set with prefix match "*".
package vlog

import (
	"bytes"
	"errors"
	"flag"
	"fmt"
	"log"
	"os"
	"path"
	"runtime"
	"sort"
	"strconv"
	"strings"
	"sync/atomic"
)

//go:generate stringer -type=Level
type Level int32

const (
	v2 Level = -2 + iota
	v1
	info
	warn
)

// W logs warning message.
// If args[0] is a format string, args is formatted with Printf,
// otherwise args is formatted with Println.
func (v *Level) W(args ...interface{}) {
	if *v <= warn {
		lg.Log(Format(args...))
	}
}

// I logs info message.
func (v *Level) I(args ...interface{}) {
	if *v <= info {
		lg.Log(Format(args...))
	}
}

// V1 logs verbose level 1 message.
func (v *Level) V1(args ...interface{}) {
	if *v <= v1 {
		lg.Log(Format(args...))
	}
}

// V2 logs verbose level 2 message.
func (v *Level) V2(args ...interface{}) {
	if *v <= v2 {
		lg.Log(Format(args...))
	}
}

// Vstack logs the message and the stacktrace of this goroutine.
// It is noop when verbose logging is not enabled.
func (v *Level) Vstack(args ...interface{}) {
	if *v >= info {
		return
	}
	s := Format(args...)
	lg.Log(stackTrace(s))
}

// On returns true if the specific verbose level 1-3 is enabled.
func (v *Level) On(l int) bool {
	lv := Level(-l)
	return *v <= lv
}

// Vset sets the verbose logging level.
func (v *Level) Vset(l int) Level {
	lv := Level(-l)
	if lv < v2 || lv >= info {
		lg.Log(Format("invalid verbose level=%d", l))
		return *v
	}
	old := *v
	atomic.StoreInt32((*int32)(v), int32(lv))
	return old
}

// Error returns an error. The message of the error is formatted
// from args. If verbose level 1 is enabled, the error messag includes
// the caller, and if verbose level 2 is enabled, the error message
// includes the call stack.
func (v *Level) Error(args ...interface{}) error {
	return v.newError(Format(args...))
}

// newError is necessary to get the correct call stack
func (v *Level) newError(s string) error {
	switch *v {
	default:
		return errors.New(s)

	case v1:
		_, fn, ln, ok := runtime.Caller(3)
		if !ok {
			return errors.New("???: " + s)
		}
		return errors.New("E[" + fn + ":" + strconv.Itoa(ln) + "]" + s)

	case v2:
		return errors.New(stackTrace(s))
	}
}

func parseLevel(lvs string) Level {
	switch strings.ToLower(lvs) {
	case "2", "v2":
		return v2
	case "1", "v1":
		return v1
	case "i", "info":
		return info
	case "w", "warn":
		return warn
	default:
		lg.Log(Format("ignore invalid logging level=%s", lvs))
		return info
	}
}

// New returns a vlog Level variable.
// The name of the Level variable is inferred with these rules,
//  - file name of the caller must be under "/src/", to follow go path convention
//  - if the file is ".../src/<foo_pkg>/{main,cmd}/bar.go", name is "foo_pkg/bar".
//  - if the file is ".../src/<foo_pkg>/bar.go", name is "foo_pkg".
//
// New must be called before Parse() is callled.
func New() *Level {
	// Note: 1 to skip New
	_, fn, _, ok := runtime.Caller(1)
	if !ok {
		lg.Log("fail to get file from runtime.caller")
		return &levelVars[0].Level // [0] is default
	}
	name := inferName(fn)
	return newVar(name, fn)
}

func newVar(name, fn string) *Level {
	if name == "" {
		lg.Log(Format("fail to infer name from file=%s", fn))
		return &levelVars[0].Level // [0] is default
	}
	for _, lv := range levelVars {
		if lv.Name == name {
			lg.Log(Format("dup level name=%s inferred from file=%s", name, fn))
			return &lv.Level
		}
	}
	lv := &levelVar{
		Name: name,
		File: fn,
	}
	levelVars = append(levelVars, lv)
	return &lv.Level
}

func inferName(fn string) string {
	fn = strings.ToLower(fn)
	i := strings.LastIndex(fn, "/src/")
	if i < 0 {
		return ""
	}
	dn, fn := path.Split(fn[i+len("/src/"):])
	if !strings.HasSuffix(fn, ".go") {
		return ""
	}
	for _, p := range []string{"/main/", "/cmd/"} {
		if strings.HasSuffix(dn, p) {
			dn = dn[:len(dn)-len(p)]
			fn = fn[:len(fn)-len(".go")]
			return path.Join(dn, fn)
		}
	}
	return strings.TrimRight(dn, "/")
}

type levelVar struct {
	Name  string
	File  string
	Level Level
}

func (lv *levelVar) String() string {
	return fmt.Sprintf("%s@%s", lv.Name, lv.File)
}

var levelVars = []*levelVar{&levelVar{}} // default level

func Parse() {
	flag.Parse()
	setLevels(*vlogFlag)
	if *vlogHelp {
		lg.Log("vlog setting:" + printLevelVars())
		flag.Usage()
		os.Exit(2)
	}
	if *vlogFile != "" {
		lg = newRotateLogger(*vlogFile)
	}
}

func ParseEnv() {
	if val := os.Getenv("GO_VLOG"); val != "" { // for testing
		setLevels(val)
		lg.Log(printLevelVars())
	}
}

func setLevels(value string) {
	exact, prefix := parseFlag(value)
	if v, ok := prefix["/"]; ok {
		levelVars[0].Level = v // default level
	}
	def := levelVars[0].Level
	for _, lv := range levelVars[1:] {
		lv.Level = def
	}
	if len(prefix) > 0 {
		prefixes := make([]string, 0, len(prefix))
		for k := range prefix {
			prefixes = append(prefixes, k)
		}
		sort.Strings(prefixes)

		for _, lv := range levelVars[1:] {
			for i := len(prefixes) - 1; i >= 0; i-- {
				k := prefixes[i]
				// Match "foo" with "foo/" and "foo/bar" with "foo/"
				if lv.Name == k[:len(k)-1] || strings.HasPrefix(lv.Name, k) {
					lv.Level = prefix[k]
					break
				}
			}
		}
	}
	for _, lv := range levelVars[1:] {
		if i, ok := exact[lv.Name]; ok {
			lv.Level = i
		}
	}
}

func parseFlag(value string) (exact, prefix map[string]Level) {
	exact = make(map[string]Level)
	prefix = make(map[string]Level)
	s := value
	for s != "" {
		k := s
		if i := strings.Index(s, ","); i >= 0 {
			k, s = s[:i], s[i+1:]
		} else {
			s = ""
		}
		j := strings.Index(k, "=")
		if j < 0 {
			panic(Format("malformed: no level", value))
		}
		k, v := k[:j], k[j+1:]
		lv := parseLevel(v)
		k = strings.ToLower(k)
		pre := false
		if k == "*" || strings.HasSuffix(k, "/*") {
			k = k[:len(k)-1]
			if strings.Contains(k, "*") {
				panic(Format("malformed: multiple star", s))
			}
			pre = true
		} else if strings.Contains(k, "*") {
			panic(Format("malformed: star in middle", s))
		}
		k = strings.TrimRight(k, "/")
		if pre {
			prefix[k+"/"] = lv
		} else {
			exact[k] = lv
		}
	}
	return exact, prefix
}

func printLevelVars() string {
	var b bytes.Buffer
	fmt.Fprintf(&b, "*=%v", levelVars[0].Level)
	for _, lv := range levelVars[1:] {
		fmt.Fprintf(&b, ",%s=%v", lv.Name, lv.Level)
	}
	return b.String()
}

var (
	vlogFlag = flag.String("vlog", "", "vlog settings, k=v(,k=v)*")
	vlogFile = flag.String("vlogfile", "", "vlog file prefix")
	vlogHelp = flag.Bool("vloghelp", false, "show vlog setting and flag help")
)

type Logger interface {
	Log(s string)
	Flush()
}

type stderrLogger struct {
	lg *log.Logger
}

func (l *stderrLogger) Log(s string) {
	l.lg.Output(3, s)
}

func (l *stderrLogger) Flush() {}

const logPrefix = log.Ldate | log.Lmicroseconds | log.Lshortfile

// lg should always be available
var lg Logger = &stderrLogger{lg: log.New(os.Stderr, "", logPrefix)}

var stackTraceBegin = []byte("/vlog.go:")

func stackTrace(s string) string {
	var buf [4 << 10]byte
	m := copy(buf[:], s)
	n := runtime.Stack(buf[m:], false)
	n += m

	// Trim the frames in vlog.go, any line that contains "/vlog.go:"
	b := buf[m:n]
	j := bytes.LastIndex(b, stackTraceBegin)
	if j < 0 {
		return string(buf[:n])
	}
	b = b[j:]
	j = bytes.IndexAny(b, "\n")
	if j < 0 {
		return string(buf[:n])
	}
	b = b[j+1:]
	buf[m] = '\n' // put a newline between s and stack frames
	n = copy(buf[m+1:], b)
	n += m + 1
	if buf[n] != '\n' {
		buf[n] = '\n' // always end with newline
	}
	return string(buf[:n])
}
<commit_msg>fix caller depth; change verbose error format<commit_after>// Packet vlog provides package level verbose logging.
// The actual logging is done with the standard log package.
//
// To define a package level logging variable,
//   var v = vlog.New()
//
// To log a message at INFO level,
//   v.I("a")
//
// The logging level can be set with either the flag -vlog or
// the environment variable GO_VLOG.
//
// The -vlog or GO_VLOG format is,
//  k=v(,k=v)*
//  k can be exact match like "foo/bar" or prefix match like "foo/*".
//  v can be w|i|v1|v2
// Default level can be set with prefix match "*".
package vlog

import (
	"bytes"
	"errors"
	"flag"
	"fmt"
	"log"
	"os"
	"path"
	"runtime"
	"sort"
	"strconv"
	"strings"
	"sync/atomic"
)

//go:generate stringer -type=Level
type Level int32

const (
	v2 Level = -2 + iota
	v1
	info
	warn
)

// W logs warning message.
// If args[0] is a format string, args is formatted with Printf,
// otherwise args is formatted with Println.
func (v *Level) W(args ...interface{}) {
	if *v <= warn {
		lg.Log(Format(args...))
	}
}

// I logs info message.
func (v *Level) I(args ...interface{}) {
	if *v <= info {
		lg.Log(Format(args...))
	}
}

// V1 logs verbose level 1 message.
func (v *Level) V1(args ...interface{}) {
	if *v <= v1 {
		lg.Log(Format(args...))
	}
}

// V2 logs verbose level 2 message.
func (v *Level) V2(args ...interface{}) {
	if *v <= v2 {
		lg.Log(Format(args...))
	}
}

// Vstack logs the message and the stacktrace of this goroutine.
// It is noop when verbose logging is not enabled.
func (v *Level) Vstack(args ...interface{}) {
	if *v >= info {
		return
	}
	s := Format(args...)
	lg.Log(stackTrace(s))
}

// On returns true if the specific verbose level 1-3 is enabled.
func (v *Level) On(l int) bool {
	lv := Level(-l)
	return *v <= lv
}

// Vset sets the verbose logging level.
func (v *Level) Vset(l int) Level {
	lv := Level(-l)
	if lv < v2 || lv >= info {
		lg.Log(Format("invalid verbose level=%d", l))
		return *v
	}
	old := *v
	atomic.StoreInt32((*int32)(v), int32(lv))
	return old
}

// Error returns an error. The message of the error is formatted
// from args. If verbose level 1 is enabled, the error messag includes
// the caller, and if verbose level 2 is enabled, the error message
// includes the call stack.
func (v *Level) Error(args ...interface{}) error {
	return v.newError(Format(args...))
}

// newError is necessary to get the correct call stack
func (v *Level) newError(s string) error {
	switch *v {
	default:
		return errors.New(s)

	case v1:
		_, fn, ln, ok := runtime.Caller(2)
		if !ok {
			return errors.New("???: " + s)
		}
		return errors.New(fn + ":" + strconv.Itoa(ln) + " " + s)

	case v2:
		return errors.New(stackTrace(s))
	}
}

func parseLevel(lvs string) Level {
	switch strings.ToLower(lvs) {
	case "2", "v2":
		return v2
	case "1", "v1":
		return v1
	case "i", "info":
		return info
	case "w", "warn":
		return warn
	default:
		lg.Log(Format("ignore invalid logging level=%s", lvs))
		return info
	}
}

// New returns a vlog Level variable.
// The name of the Level variable is inferred with these rules,
//  - file name of the caller must be under "/src/", to follow go path convention
//  - if the file is ".../src/<foo_pkg>/{main,cmd}/bar.go", name is "foo_pkg/bar".
//  - if the file is ".../src/<foo_pkg>/bar.go", name is "foo_pkg".
//
// New must be called before Parse() is callled.
func New() *Level {
	// Note: 1 to skip New
	_, fn, _, ok := runtime.Caller(1)
	if !ok {
		lg.Log("fail to get file from runtime.caller")
		return &levelVars[0].Level // [0] is default
	}
	name := inferName(fn)
	return newVar(name, fn)
}

func newVar(name, fn string) *Level {
	if name == "" {
		lg.Log(Format("fail to infer name from file=%s", fn))
		return &levelVars[0].Level // [0] is default
	}
	for _, lv := range levelVars {
		if lv.Name == name {
			lg.Log(Format("dup level name=%s inferred from file=%s", name, fn))
			return &lv.Level
		}
	}
	lv := &levelVar{
		Name: name,
		File: fn,
	}
	levelVars = append(levelVars, lv)
	return &lv.Level
}

func inferName(fn string) string {
	fn = strings.ToLower(fn)
	i := strings.LastIndex(fn, "/src/")
	if i < 0 {
		return ""
	}
	dn, fn := path.Split(fn[i+len("/src/"):])
	if !strings.HasSuffix(fn, ".go") {
		return ""
	}
	for _, p := range []string{"/main/", "/cmd/"} {
		if strings.HasSuffix(dn, p) {
			dn = dn[:len(dn)-len(p)]
			fn = fn[:len(fn)-len(".go")]
			return path.Join(dn, fn)
		}
	}
	return strings.TrimRight(dn, "/")
}

type levelVar struct {
	Name  string
	File  string
	Level Level
}

func (lv *levelVar) String() string {
	return fmt.Sprintf("%s@%s", lv.Name, lv.File)
}

var levelVars = []*levelVar{&levelVar{}} // default level

func Parse() {
	flag.Parse()
	setLevels(*vlogFlag)
	if *vlogHelp {
		lg.Log("vlog setting:" + printLevelVars())
		flag.Usage()
		os.Exit(2)
	}
	if *vlogFile != "" {
		lg = newRotateLogger(*vlogFile)
	}
}

func ParseEnv() {
	if val := os.Getenv("GO_VLOG"); val != "" { // for testing
		setLevels(val)
		lg.Log(printLevelVars())
	}
}

func setLevels(value string) {
	exact, prefix := parseFlag(value)
	if v, ok := prefix["/"]; ok {
		levelVars[0].Level = v // default level
	}
	def := levelVars[0].Level
	for _, lv := range levelVars[1:] {
		lv.Level = def
	}
	if len(prefix) > 0 {
		prefixes := make([]string, 0, len(prefix))
		for k := range prefix {
			prefixes = append(prefixes, k)
		}
		sort.Strings(prefixes)

		for _, lv := range levelVars[1:] {
			for i := len(prefixes) - 1; i >= 0; i-- {
				k := prefixes[i]
				// Match "foo" with "foo/" and "foo/bar" with "foo/"
				if lv.Name == k[:len(k)-1] || strings.HasPrefix(lv.Name, k) {
					lv.Level = prefix[k]
					break
				}
			}
		}
	}
	for _, lv := range levelVars[1:] {
		if i, ok := exact[lv.Name]; ok {
			lv.Level = i
		}
	}
}

func parseFlag(value string) (exact, prefix map[string]Level) {
	exact = make(map[string]Level)
	prefix = make(map[string]Level)
	s := value
	for s != "" {
		k := s
		if i := strings.Index(s, ","); i >= 0 {
			k, s = s[:i], s[i+1:]
		} else {
			s = ""
		}
		j := strings.Index(k, "=")
		if j < 0 {
			panic(Format("malformed: no level", value))
		}
		k, v := k[:j], k[j+1:]
		lv := parseLevel(v)
		k = strings.ToLower(k)
		pre := false
		if k == "*" || strings.HasSuffix(k, "/*") {
			k = k[:len(k)-1]
			if strings.Contains(k, "*") {
				panic(Format("malformed: multiple star", s))
			}
			pre = true
		} else if strings.Contains(k, "*") {
			panic(Format("malformed: star in middle", s))
		}
		k = strings.TrimRight(k, "/")
		if pre {
			prefix[k+"/"] = lv
		} else {
			exact[k] = lv
		}
	}
	return exact, prefix
}

func printLevelVars() string {
	var b bytes.Buffer
	fmt.Fprintf(&b, "*=%v", levelVars[0].Level)
	for _, lv := range levelVars[1:] {
		fmt.Fprintf(&b, ",%s=%v", lv.Name, lv.Level)
	}
	return b.String()
}

var (
	vlogFlag = flag.String("vlog", "", "vlog settings, k=v(,k=v)*")
	vlogFile = flag.String("vlogfile", "", "vlog file prefix")
	vlogHelp = flag.Bool("vloghelp", false, "show vlog setting and flag help")
)

type Logger interface {
	Log(s string)
	Flush()
}

type stderrLogger struct {
	lg *log.Logger
}

func (l *stderrLogger) Log(s string) {
	l.lg.Output(3, s)
}

func (l *stderrLogger) Flush() {}

const logPrefix = log.Ldate | log.Lmicroseconds | log.Lshortfile

// lg should always be available
var lg Logger = &stderrLogger{lg: log.New(os.Stderr, "", logPrefix)}

var stackTraceBegin = []byte("/vlog.go:")

func stackTrace(s string) string {
	var buf [4 << 10]byte
	m := copy(buf[:], s)
	n := runtime.Stack(buf[m:], false)
	n += m

	// Trim the frames in vlog.go, any line that contains "/vlog.go:"
	b := buf[m:n]
	j := bytes.LastIndex(b, stackTraceBegin)
	if j < 0 {
		return string(buf[:n])
	}
	b = b[j:]
	j = bytes.IndexAny(b, "\n")
	if j < 0 {
		return string(buf[:n])
	}
	b = b[j+1:]
	buf[m] = '\n' // put a newline between s and stack frames
	n = copy(buf[m+1:], b)
	n += m + 1
	if buf[n] != '\n' {
		buf[n] = '\n' // always end with newline
	}
	return string(buf[:n])
}
<|endoftext|>