repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
go-gorp/gorp | index.go | SetUnique | func (idx *IndexMap) SetUnique(b bool) *IndexMap {
idx.Unique = b
return idx
} | go | func (idx *IndexMap) SetUnique(b bool) *IndexMap {
idx.Unique = b
return idx
} | [
"func",
"(",
"idx",
"*",
"IndexMap",
")",
"SetUnique",
"(",
"b",
"bool",
")",
"*",
"IndexMap",
"{",
"idx",
".",
"Unique",
"=",
"b",
"\n",
"return",
"idx",
"\n",
"}"
] | // SetUnique adds "unique" to the create index statements for this
// index, if b is true. | [
"SetUnique",
"adds",
"unique",
"to",
"the",
"create",
"index",
"statements",
"for",
"this",
"index",
"if",
"b",
"is",
"true",
"."
] | f3677d4a0a8838c846ed41bf41927f2c8713bd60 | https://github.com/go-gorp/gorp/blob/f3677d4a0a8838c846ed41bf41927f2c8713bd60/index.go#L47-L50 | train |
go-gorp/gorp | index.go | SetIndexType | func (idx *IndexMap) SetIndexType(indtype string) *IndexMap {
idx.IndexType = indtype
return idx
} | go | func (idx *IndexMap) SetIndexType(indtype string) *IndexMap {
idx.IndexType = indtype
return idx
} | [
"func",
"(",
"idx",
"*",
"IndexMap",
")",
"SetIndexType",
"(",
"indtype",
"string",
")",
"*",
"IndexMap",
"{",
"idx",
".",
"IndexType",
"=",
"indtype",
"\n",
"return",
"idx",
"\n",
"}"
] | // SetIndexType specifies the index type supported by chousen SQL Dialect | [
"SetIndexType",
"specifies",
"the",
"index",
"type",
"supported",
"by",
"chousen",
"SQL",
"Dialect"
] | f3677d4a0a8838c846ed41bf41927f2c8713bd60 | https://github.com/go-gorp/gorp/blob/f3677d4a0a8838c846ed41bf41927f2c8713bd60/index.go#L53-L56 | train |
go-gorp/gorp | dialect_sqlite.go | QuotedTableForQuery | func (d SqliteDialect) QuotedTableForQuery(schema string, table string) string {
return d.QuoteField(table)
} | go | func (d SqliteDialect) QuotedTableForQuery(schema string, table string) string {
return d.QuoteField(table)
} | [
"func",
"(",
"d",
"SqliteDialect",
")",
"QuotedTableForQuery",
"(",
"schema",
"string",
",",
"table",
"string",
")",
"string",
"{",
"return",
"d",
".",
"QuoteField",
"(",
"table",
")",
"\n",
"}"
] | // sqlite does not have schemas like PostgreSQL does, so just escape it like normal | [
"sqlite",
"does",
"not",
"have",
"schemas",
"like",
"PostgreSQL",
"does",
"so",
"just",
"escape",
"it",
"like",
"normal"
] | f3677d4a0a8838c846ed41bf41927f2c8713bd60 | https://github.com/go-gorp/gorp/blob/f3677d4a0a8838c846ed41bf41927f2c8713bd60/dialect_sqlite.go#L105-L107 | train |
go-gorp/gorp | dialect_oracle.go | InsertQueryToTarget | func (d OracleDialect) InsertQueryToTarget(exec SqlExecutor, insertSql, idSql string, target interface{}, params ...interface{}) error {
_, err := exec.Exec(insertSql, params...)
if err != nil {
return err
}
id, err := exec.SelectInt(idSql)
if err != nil {
return err
}
switch target.(type) {
case *int64:
*(target.(*int64)) = id
case *int32:
*(target.(*int32)) = int32(id)
case int:
*(target.(*int)) = int(id)
default:
return fmt.Errorf("Id field can be int, int32 or int64")
}
return nil
} | go | func (d OracleDialect) InsertQueryToTarget(exec SqlExecutor, insertSql, idSql string, target interface{}, params ...interface{}) error {
_, err := exec.Exec(insertSql, params...)
if err != nil {
return err
}
id, err := exec.SelectInt(idSql)
if err != nil {
return err
}
switch target.(type) {
case *int64:
*(target.(*int64)) = id
case *int32:
*(target.(*int32)) = int32(id)
case int:
*(target.(*int)) = int(id)
default:
return fmt.Errorf("Id field can be int, int32 or int64")
}
return nil
} | [
"func",
"(",
"d",
"OracleDialect",
")",
"InsertQueryToTarget",
"(",
"exec",
"SqlExecutor",
",",
"insertSql",
",",
"idSql",
"string",
",",
"target",
"interface",
"{",
"}",
",",
"params",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"_",
",",
"err",
":... | // After executing the insert uses the ColMap IdQuery to get the generated id | [
"After",
"executing",
"the",
"insert",
"uses",
"the",
"ColMap",
"IdQuery",
"to",
"get",
"the",
"generated",
"id"
] | f3677d4a0a8838c846ed41bf41927f2c8713bd60 | https://github.com/go-gorp/gorp/blob/f3677d4a0a8838c846ed41bf41927f2c8713bd60/dialect_oracle.go#L102-L122 | train |
go-gorp/gorp | transaction.go | SelectInt | func (t *Transaction) SelectInt(query string, args ...interface{}) (int64, error) {
if t.dbmap.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
return SelectInt(t, query, args...)
} | go | func (t *Transaction) SelectInt(query string, args ...interface{}) (int64, error) {
if t.dbmap.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
return SelectInt(t, query, args...)
} | [
"func",
"(",
"t",
"*",
"Transaction",
")",
"SelectInt",
"(",
"query",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"(",
"int64",
",",
"error",
")",
"{",
"if",
"t",
".",
"dbmap",
".",
"ExpandSliceArgs",
"{",
"expandSliceArgs",
"(",
"&",
"... | // SelectInt is a convenience wrapper around the gorp.SelectInt function. | [
"SelectInt",
"is",
"a",
"convenience",
"wrapper",
"around",
"the",
"gorp",
".",
"SelectInt",
"function",
"."
] | f3677d4a0a8838c846ed41bf41927f2c8713bd60 | https://github.com/go-gorp/gorp/blob/f3677d4a0a8838c846ed41bf41927f2c8713bd60/transaction.go#L86-L92 | train |
go-gorp/gorp | transaction.go | SelectNullInt | func (t *Transaction) SelectNullInt(query string, args ...interface{}) (sql.NullInt64, error) {
if t.dbmap.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
return SelectNullInt(t, query, args...)
} | go | func (t *Transaction) SelectNullInt(query string, args ...interface{}) (sql.NullInt64, error) {
if t.dbmap.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
return SelectNullInt(t, query, args...)
} | [
"func",
"(",
"t",
"*",
"Transaction",
")",
"SelectNullInt",
"(",
"query",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"(",
"sql",
".",
"NullInt64",
",",
"error",
")",
"{",
"if",
"t",
".",
"dbmap",
".",
"ExpandSliceArgs",
"{",
"expandSlice... | // SelectNullInt is a convenience wrapper around the gorp.SelectNullInt function. | [
"SelectNullInt",
"is",
"a",
"convenience",
"wrapper",
"around",
"the",
"gorp",
".",
"SelectNullInt",
"function",
"."
] | f3677d4a0a8838c846ed41bf41927f2c8713bd60 | https://github.com/go-gorp/gorp/blob/f3677d4a0a8838c846ed41bf41927f2c8713bd60/transaction.go#L95-L101 | train |
go-gorp/gorp | transaction.go | SelectFloat | func (t *Transaction) SelectFloat(query string, args ...interface{}) (float64, error) {
if t.dbmap.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
return SelectFloat(t, query, args...)
} | go | func (t *Transaction) SelectFloat(query string, args ...interface{}) (float64, error) {
if t.dbmap.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
return SelectFloat(t, query, args...)
} | [
"func",
"(",
"t",
"*",
"Transaction",
")",
"SelectFloat",
"(",
"query",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"(",
"float64",
",",
"error",
")",
"{",
"if",
"t",
".",
"dbmap",
".",
"ExpandSliceArgs",
"{",
"expandSliceArgs",
"(",
"&",... | // SelectFloat is a convenience wrapper around the gorp.SelectFloat function. | [
"SelectFloat",
"is",
"a",
"convenience",
"wrapper",
"around",
"the",
"gorp",
".",
"SelectFloat",
"function",
"."
] | f3677d4a0a8838c846ed41bf41927f2c8713bd60 | https://github.com/go-gorp/gorp/blob/f3677d4a0a8838c846ed41bf41927f2c8713bd60/transaction.go#L104-L110 | train |
go-gorp/gorp | transaction.go | SelectNullFloat | func (t *Transaction) SelectNullFloat(query string, args ...interface{}) (sql.NullFloat64, error) {
if t.dbmap.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
return SelectNullFloat(t, query, args...)
} | go | func (t *Transaction) SelectNullFloat(query string, args ...interface{}) (sql.NullFloat64, error) {
if t.dbmap.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
return SelectNullFloat(t, query, args...)
} | [
"func",
"(",
"t",
"*",
"Transaction",
")",
"SelectNullFloat",
"(",
"query",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"(",
"sql",
".",
"NullFloat64",
",",
"error",
")",
"{",
"if",
"t",
".",
"dbmap",
".",
"ExpandSliceArgs",
"{",
"expandS... | // SelectNullFloat is a convenience wrapper around the gorp.SelectNullFloat function. | [
"SelectNullFloat",
"is",
"a",
"convenience",
"wrapper",
"around",
"the",
"gorp",
".",
"SelectNullFloat",
"function",
"."
] | f3677d4a0a8838c846ed41bf41927f2c8713bd60 | https://github.com/go-gorp/gorp/blob/f3677d4a0a8838c846ed41bf41927f2c8713bd60/transaction.go#L113-L119 | train |
go-gorp/gorp | transaction.go | SelectStr | func (t *Transaction) SelectStr(query string, args ...interface{}) (string, error) {
if t.dbmap.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
return SelectStr(t, query, args...)
} | go | func (t *Transaction) SelectStr(query string, args ...interface{}) (string, error) {
if t.dbmap.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
return SelectStr(t, query, args...)
} | [
"func",
"(",
"t",
"*",
"Transaction",
")",
"SelectStr",
"(",
"query",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"t",
".",
"dbmap",
".",
"ExpandSliceArgs",
"{",
"expandSliceArgs",
"(",
"&",
... | // SelectStr is a convenience wrapper around the gorp.SelectStr function. | [
"SelectStr",
"is",
"a",
"convenience",
"wrapper",
"around",
"the",
"gorp",
".",
"SelectStr",
"function",
"."
] | f3677d4a0a8838c846ed41bf41927f2c8713bd60 | https://github.com/go-gorp/gorp/blob/f3677d4a0a8838c846ed41bf41927f2c8713bd60/transaction.go#L122-L128 | train |
go-gorp/gorp | transaction.go | SelectNullStr | func (t *Transaction) SelectNullStr(query string, args ...interface{}) (sql.NullString, error) {
if t.dbmap.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
return SelectNullStr(t, query, args...)
} | go | func (t *Transaction) SelectNullStr(query string, args ...interface{}) (sql.NullString, error) {
if t.dbmap.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
return SelectNullStr(t, query, args...)
} | [
"func",
"(",
"t",
"*",
"Transaction",
")",
"SelectNullStr",
"(",
"query",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"(",
"sql",
".",
"NullString",
",",
"error",
")",
"{",
"if",
"t",
".",
"dbmap",
".",
"ExpandSliceArgs",
"{",
"expandSlic... | // SelectNullStr is a convenience wrapper around the gorp.SelectNullStr function. | [
"SelectNullStr",
"is",
"a",
"convenience",
"wrapper",
"around",
"the",
"gorp",
".",
"SelectNullStr",
"function",
"."
] | f3677d4a0a8838c846ed41bf41927f2c8713bd60 | https://github.com/go-gorp/gorp/blob/f3677d4a0a8838c846ed41bf41927f2c8713bd60/transaction.go#L131-L137 | train |
go-gorp/gorp | transaction.go | SelectOne | func (t *Transaction) SelectOne(holder interface{}, query string, args ...interface{}) error {
if t.dbmap.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
return SelectOne(t.dbmap, t, holder, query, args...)
} | go | func (t *Transaction) SelectOne(holder interface{}, query string, args ...interface{}) error {
if t.dbmap.ExpandSliceArgs {
expandSliceArgs(&query, args...)
}
return SelectOne(t.dbmap, t, holder, query, args...)
} | [
"func",
"(",
"t",
"*",
"Transaction",
")",
"SelectOne",
"(",
"holder",
"interface",
"{",
"}",
",",
"query",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"t",
".",
"dbmap",
".",
"ExpandSliceArgs",
"{",
"expandSliceArgs",
... | // SelectOne is a convenience wrapper around the gorp.SelectOne function. | [
"SelectOne",
"is",
"a",
"convenience",
"wrapper",
"around",
"the",
"gorp",
".",
"SelectOne",
"function",
"."
] | f3677d4a0a8838c846ed41bf41927f2c8713bd60 | https://github.com/go-gorp/gorp/blob/f3677d4a0a8838c846ed41bf41927f2c8713bd60/transaction.go#L140-L146 | train |
go-gorp/gorp | transaction.go | Savepoint | func (t *Transaction) Savepoint(name string) error {
query := "savepoint " + t.dbmap.Dialect.QuoteField(name)
if t.dbmap.logger != nil {
now := time.Now()
defer t.dbmap.trace(now, query, nil)
}
_, err := exec(t, query)
return err
} | go | func (t *Transaction) Savepoint(name string) error {
query := "savepoint " + t.dbmap.Dialect.QuoteField(name)
if t.dbmap.logger != nil {
now := time.Now()
defer t.dbmap.trace(now, query, nil)
}
_, err := exec(t, query)
return err
} | [
"func",
"(",
"t",
"*",
"Transaction",
")",
"Savepoint",
"(",
"name",
"string",
")",
"error",
"{",
"query",
":=",
"\"savepoint \"",
"+",
"t",
".",
"dbmap",
".",
"Dialect",
".",
"QuoteField",
"(",
"name",
")",
"\n",
"if",
"t",
".",
"dbmap",
".",
"logge... | // Savepoint creates a savepoint with the given name. The name is interpolated
// directly into the SQL SAVEPOINT statement, so you must sanitize it if it is
// derived from user input. | [
"Savepoint",
"creates",
"a",
"savepoint",
"with",
"the",
"given",
"name",
".",
"The",
"name",
"is",
"interpolated",
"directly",
"into",
"the",
"SQL",
"SAVEPOINT",
"statement",
"so",
"you",
"must",
"sanitize",
"it",
"if",
"it",
"is",
"derived",
"from",
"user"... | f3677d4a0a8838c846ed41bf41927f2c8713bd60 | https://github.com/go-gorp/gorp/blob/f3677d4a0a8838c846ed41bf41927f2c8713bd60/transaction.go#L179-L187 | train |
go-gorp/gorp | lockerror.go | Error | func (e OptimisticLockError) Error() string {
if e.RowExists {
return fmt.Sprintf("gorp: OptimisticLockError table=%s keys=%v out of date version=%d", e.TableName, e.Keys, e.LocalVersion)
}
return fmt.Sprintf("gorp: OptimisticLockError no row found for table=%s keys=%v", e.TableName, e.Keys)
} | go | func (e OptimisticLockError) Error() string {
if e.RowExists {
return fmt.Sprintf("gorp: OptimisticLockError table=%s keys=%v out of date version=%d", e.TableName, e.Keys, e.LocalVersion)
}
return fmt.Sprintf("gorp: OptimisticLockError no row found for table=%s keys=%v", e.TableName, e.Keys)
} | [
"func",
"(",
"e",
"OptimisticLockError",
")",
"Error",
"(",
")",
"string",
"{",
"if",
"e",
".",
"RowExists",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"gorp: OptimisticLockError table=%s keys=%v out of date version=%d\"",
",",
"e",
".",
"TableName",
",",
"e",
... | // Error returns a description of the cause of the lock error | [
"Error",
"returns",
"a",
"description",
"of",
"the",
"cause",
"of",
"the",
"lock",
"error"
] | f3677d4a0a8838c846ed41bf41927f2c8713bd60 | https://github.com/go-gorp/gorp/blob/f3677d4a0a8838c846ed41bf41927f2c8713bd60/lockerror.go#L41-L47 | train |
go-gorp/gorp | select.go | SelectInt | func SelectInt(e SqlExecutor, query string, args ...interface{}) (int64, error) {
var h int64
err := selectVal(e, &h, query, args...)
if err != nil && err != sql.ErrNoRows {
return 0, err
}
return h, nil
} | go | func SelectInt(e SqlExecutor, query string, args ...interface{}) (int64, error) {
var h int64
err := selectVal(e, &h, query, args...)
if err != nil && err != sql.ErrNoRows {
return 0, err
}
return h, nil
} | [
"func",
"SelectInt",
"(",
"e",
"SqlExecutor",
",",
"query",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"(",
"int64",
",",
"error",
")",
"{",
"var",
"h",
"int64",
"\n",
"err",
":=",
"selectVal",
"(",
"e",
",",
"&",
"h",
",",
"query",
... | // SelectInt executes the given query, which should be a SELECT statement for a single
// integer column, and returns the value of the first row returned. If no rows are
// found, zero is returned. | [
"SelectInt",
"executes",
"the",
"given",
"query",
"which",
"should",
"be",
"a",
"SELECT",
"statement",
"for",
"a",
"single",
"integer",
"column",
"and",
"returns",
"the",
"value",
"of",
"the",
"first",
"row",
"returned",
".",
"If",
"no",
"rows",
"are",
"fo... | f3677d4a0a8838c846ed41bf41927f2c8713bd60 | https://github.com/go-gorp/gorp/blob/f3677d4a0a8838c846ed41bf41927f2c8713bd60/select.go#L23-L30 | train |
hashicorp/go-version | constraint.go | NewConstraint | func NewConstraint(v string) (Constraints, error) {
vs := strings.Split(v, ",")
result := make([]*Constraint, len(vs))
for i, single := range vs {
c, err := parseSingle(single)
if err != nil {
return nil, err
}
result[i] = c
}
return Constraints(result), nil
} | go | func NewConstraint(v string) (Constraints, error) {
vs := strings.Split(v, ",")
result := make([]*Constraint, len(vs))
for i, single := range vs {
c, err := parseSingle(single)
if err != nil {
return nil, err
}
result[i] = c
}
return Constraints(result), nil
} | [
"func",
"NewConstraint",
"(",
"v",
"string",
")",
"(",
"Constraints",
",",
"error",
")",
"{",
"vs",
":=",
"strings",
".",
"Split",
"(",
"v",
",",
"\",\"",
")",
"\n",
"result",
":=",
"make",
"(",
"[",
"]",
"*",
"Constraint",
",",
"len",
"(",
"vs",
... | // NewConstraint will parse one or more constraints from the given
// constraint string. The string must be a comma-separated list of
// constraints. | [
"NewConstraint",
"will",
"parse",
"one",
"or",
"more",
"constraints",
"from",
"the",
"given",
"constraint",
"string",
".",
"The",
"string",
"must",
"be",
"a",
"comma",
"-",
"separated",
"list",
"of",
"constraints",
"."
] | 192140e6f3e645d971b134d4e35b5191adb9dfd3 | https://github.com/hashicorp/go-version/blob/192140e6f3e645d971b134d4e35b5191adb9dfd3/constraint.go#L54-L67 | train |
hashicorp/go-version | constraint.go | Check | func (cs Constraints) Check(v *Version) bool {
for _, c := range cs {
if !c.Check(v) {
return false
}
}
return true
} | go | func (cs Constraints) Check(v *Version) bool {
for _, c := range cs {
if !c.Check(v) {
return false
}
}
return true
} | [
"func",
"(",
"cs",
"Constraints",
")",
"Check",
"(",
"v",
"*",
"Version",
")",
"bool",
"{",
"for",
"_",
",",
"c",
":=",
"range",
"cs",
"{",
"if",
"!",
"c",
".",
"Check",
"(",
"v",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"retu... | // Check tests if a version satisfies all the constraints. | [
"Check",
"tests",
"if",
"a",
"version",
"satisfies",
"all",
"the",
"constraints",
"."
] | 192140e6f3e645d971b134d4e35b5191adb9dfd3 | https://github.com/hashicorp/go-version/blob/192140e6f3e645d971b134d4e35b5191adb9dfd3/constraint.go#L70-L78 | train |
hashicorp/go-version | constraint.go | String | func (cs Constraints) String() string {
csStr := make([]string, len(cs))
for i, c := range cs {
csStr[i] = c.String()
}
return strings.Join(csStr, ",")
} | go | func (cs Constraints) String() string {
csStr := make([]string, len(cs))
for i, c := range cs {
csStr[i] = c.String()
}
return strings.Join(csStr, ",")
} | [
"func",
"(",
"cs",
"Constraints",
")",
"String",
"(",
")",
"string",
"{",
"csStr",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"cs",
")",
")",
"\n",
"for",
"i",
",",
"c",
":=",
"range",
"cs",
"{",
"csStr",
"[",
"i",
"]",
"=",
"c",... | // Returns the string format of the constraints | [
"Returns",
"the",
"string",
"format",
"of",
"the",
"constraints"
] | 192140e6f3e645d971b134d4e35b5191adb9dfd3 | https://github.com/hashicorp/go-version/blob/192140e6f3e645d971b134d4e35b5191adb9dfd3/constraint.go#L81-L88 | train |
hashicorp/go-version | constraint.go | Check | func (c *Constraint) Check(v *Version) bool {
return c.f(v, c.check)
} | go | func (c *Constraint) Check(v *Version) bool {
return c.f(v, c.check)
} | [
"func",
"(",
"c",
"*",
"Constraint",
")",
"Check",
"(",
"v",
"*",
"Version",
")",
"bool",
"{",
"return",
"c",
".",
"f",
"(",
"v",
",",
"c",
".",
"check",
")",
"\n",
"}"
] | // Check tests if a constraint is validated by the given version. | [
"Check",
"tests",
"if",
"a",
"constraint",
"is",
"validated",
"by",
"the",
"given",
"version",
"."
] | 192140e6f3e645d971b134d4e35b5191adb9dfd3 | https://github.com/hashicorp/go-version/blob/192140e6f3e645d971b134d4e35b5191adb9dfd3/constraint.go#L91-L93 | train |
hashicorp/go-version | version.go | Compare | func (v *Version) Compare(other *Version) int {
// A quick, efficient equality check
if v.String() == other.String() {
return 0
}
segmentsSelf := v.Segments64()
segmentsOther := other.Segments64()
// If the segments are the same, we must compare on prerelease info
if reflect.DeepEqual(segmentsSelf, segmentsOther) {
preSelf := v.Prerelease()
preOther := other.Prerelease()
if preSelf == "" && preOther == "" {
return 0
}
if preSelf == "" {
return 1
}
if preOther == "" {
return -1
}
return comparePrereleases(preSelf, preOther)
}
// Get the highest specificity (hS), or if they're equal, just use segmentSelf length
lenSelf := len(segmentsSelf)
lenOther := len(segmentsOther)
hS := lenSelf
if lenSelf < lenOther {
hS = lenOther
}
// Compare the segments
// Because a constraint could have more/less specificity than the version it's
// checking, we need to account for a lopsided or jagged comparison
for i := 0; i < hS; i++ {
if i > lenSelf-1 {
// This means Self had the lower specificity
// Check to see if the remaining segments in Other are all zeros
if !allZero(segmentsOther[i:]) {
// if not, it means that Other has to be greater than Self
return -1
}
break
} else if i > lenOther-1 {
// this means Other had the lower specificity
// Check to see if the remaining segments in Self are all zeros -
if !allZero(segmentsSelf[i:]) {
//if not, it means that Self has to be greater than Other
return 1
}
break
}
lhs := segmentsSelf[i]
rhs := segmentsOther[i]
if lhs == rhs {
continue
} else if lhs < rhs {
return -1
}
// Otherwis, rhs was > lhs, they're not equal
return 1
}
// if we got this far, they're equal
return 0
} | go | func (v *Version) Compare(other *Version) int {
// A quick, efficient equality check
if v.String() == other.String() {
return 0
}
segmentsSelf := v.Segments64()
segmentsOther := other.Segments64()
// If the segments are the same, we must compare on prerelease info
if reflect.DeepEqual(segmentsSelf, segmentsOther) {
preSelf := v.Prerelease()
preOther := other.Prerelease()
if preSelf == "" && preOther == "" {
return 0
}
if preSelf == "" {
return 1
}
if preOther == "" {
return -1
}
return comparePrereleases(preSelf, preOther)
}
// Get the highest specificity (hS), or if they're equal, just use segmentSelf length
lenSelf := len(segmentsSelf)
lenOther := len(segmentsOther)
hS := lenSelf
if lenSelf < lenOther {
hS = lenOther
}
// Compare the segments
// Because a constraint could have more/less specificity than the version it's
// checking, we need to account for a lopsided or jagged comparison
for i := 0; i < hS; i++ {
if i > lenSelf-1 {
// This means Self had the lower specificity
// Check to see if the remaining segments in Other are all zeros
if !allZero(segmentsOther[i:]) {
// if not, it means that Other has to be greater than Self
return -1
}
break
} else if i > lenOther-1 {
// this means Other had the lower specificity
// Check to see if the remaining segments in Self are all zeros -
if !allZero(segmentsSelf[i:]) {
//if not, it means that Self has to be greater than Other
return 1
}
break
}
lhs := segmentsSelf[i]
rhs := segmentsOther[i]
if lhs == rhs {
continue
} else if lhs < rhs {
return -1
}
// Otherwis, rhs was > lhs, they're not equal
return 1
}
// if we got this far, they're equal
return 0
} | [
"func",
"(",
"v",
"*",
"Version",
")",
"Compare",
"(",
"other",
"*",
"Version",
")",
"int",
"{",
"if",
"v",
".",
"String",
"(",
")",
"==",
"other",
".",
"String",
"(",
")",
"{",
"return",
"0",
"\n",
"}",
"\n",
"segmentsSelf",
":=",
"v",
".",
"S... | // Compare compares this version to another version. This
// returns -1, 0, or 1 if this version is smaller, equal,
// or larger than the other version, respectively.
//
// If you want boolean results, use the LessThan, Equal,
// GreaterThan, GreaterThanOrEqual or LessThanOrEqual methods. | [
"Compare",
"compares",
"this",
"version",
"to",
"another",
"version",
".",
"This",
"returns",
"-",
"1",
"0",
"or",
"1",
"if",
"this",
"version",
"is",
"smaller",
"equal",
"or",
"larger",
"than",
"the",
"other",
"version",
"respectively",
".",
"If",
"you",
... | 192140e6f3e645d971b134d4e35b5191adb9dfd3 | https://github.com/hashicorp/go-version/blob/192140e6f3e645d971b134d4e35b5191adb9dfd3/version.go#L116-L183 | train |
hashicorp/go-version | version.go | Segments | func (v *Version) Segments() []int {
segmentSlice := make([]int, len(v.segments))
for i, v := range v.segments {
segmentSlice[i] = int(v)
}
return segmentSlice
} | go | func (v *Version) Segments() []int {
segmentSlice := make([]int, len(v.segments))
for i, v := range v.segments {
segmentSlice[i] = int(v)
}
return segmentSlice
} | [
"func",
"(",
"v",
"*",
"Version",
")",
"Segments",
"(",
")",
"[",
"]",
"int",
"{",
"segmentSlice",
":=",
"make",
"(",
"[",
"]",
"int",
",",
"len",
"(",
"v",
".",
"segments",
")",
")",
"\n",
"for",
"i",
",",
"v",
":=",
"range",
"v",
".",
"segm... | // Segments returns the numeric segments of the version as a slice of ints.
//
// This excludes any metadata or pre-release information. For example,
// for a version "1.2.3-beta", segments will return a slice of
// 1, 2, 3. | [
"Segments",
"returns",
"the",
"numeric",
"segments",
"of",
"the",
"version",
"as",
"a",
"slice",
"of",
"ints",
".",
"This",
"excludes",
"any",
"metadata",
"or",
"pre",
"-",
"release",
"information",
".",
"For",
"example",
"for",
"a",
"version",
"1",
".",
... | 192140e6f3e645d971b134d4e35b5191adb9dfd3 | https://github.com/hashicorp/go-version/blob/192140e6f3e645d971b134d4e35b5191adb9dfd3/version.go#L330-L336 | train |
hashicorp/go-version | version.go | Segments64 | func (v *Version) Segments64() []int64 {
result := make([]int64, len(v.segments))
copy(result, v.segments)
return result
} | go | func (v *Version) Segments64() []int64 {
result := make([]int64, len(v.segments))
copy(result, v.segments)
return result
} | [
"func",
"(",
"v",
"*",
"Version",
")",
"Segments64",
"(",
")",
"[",
"]",
"int64",
"{",
"result",
":=",
"make",
"(",
"[",
"]",
"int64",
",",
"len",
"(",
"v",
".",
"segments",
")",
")",
"\n",
"copy",
"(",
"result",
",",
"v",
".",
"segments",
")",... | // Segments64 returns the numeric segments of the version as a slice of int64s.
//
// This excludes any metadata or pre-release information. For example,
// for a version "1.2.3-beta", segments will return a slice of
// 1, 2, 3. | [
"Segments64",
"returns",
"the",
"numeric",
"segments",
"of",
"the",
"version",
"as",
"a",
"slice",
"of",
"int64s",
".",
"This",
"excludes",
"any",
"metadata",
"or",
"pre",
"-",
"release",
"information",
".",
"For",
"example",
"for",
"a",
"version",
"1",
".... | 192140e6f3e645d971b134d4e35b5191adb9dfd3 | https://github.com/hashicorp/go-version/blob/192140e6f3e645d971b134d4e35b5191adb9dfd3/version.go#L343-L347 | train |
google/gops | main.go | elapsedTime | func elapsedTime(p *process.Process) (string, error) {
crtTime, err := p.CreateTime()
if err != nil {
return "", err
}
etime := time.Since(time.Unix(int64(crtTime/1000), 0))
return fmtEtimeDuration(etime), nil
} | go | func elapsedTime(p *process.Process) (string, error) {
crtTime, err := p.CreateTime()
if err != nil {
return "", err
}
etime := time.Since(time.Unix(int64(crtTime/1000), 0))
return fmtEtimeDuration(etime), nil
} | [
"func",
"elapsedTime",
"(",
"p",
"*",
"process",
".",
"Process",
")",
"(",
"string",
",",
"error",
")",
"{",
"crtTime",
",",
"err",
":=",
"p",
".",
"CreateTime",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"... | // elapsedTime shows the elapsed time of the process indicating how long the
// process has been running for. | [
"elapsedTime",
"shows",
"the",
"elapsed",
"time",
"of",
"the",
"process",
"indicating",
"how",
"long",
"the",
"process",
"has",
"been",
"running",
"for",
"."
] | 036f72c5be1f7a0970ffae4907e05dd11f49de35 | https://github.com/google/gops/blob/036f72c5be1f7a0970ffae4907e05dd11f49de35/main.go#L170-L177 | train |
google/gops | main.go | displayProcessTree | func displayProcessTree() {
ps := goprocess.FindAll()
pstree = make(map[int][]goprocess.P)
for _, p := range ps {
pstree[p.PPID] = append(pstree[p.PPID], p)
}
tree := treeprint.New()
tree.SetValue("...")
seen := map[int]bool{}
for _, p := range ps {
constructProcessTree(p.PPID, p, seen, tree)
}
fmt.Println(tree.String())
} | go | func displayProcessTree() {
ps := goprocess.FindAll()
pstree = make(map[int][]goprocess.P)
for _, p := range ps {
pstree[p.PPID] = append(pstree[p.PPID], p)
}
tree := treeprint.New()
tree.SetValue("...")
seen := map[int]bool{}
for _, p := range ps {
constructProcessTree(p.PPID, p, seen, tree)
}
fmt.Println(tree.String())
} | [
"func",
"displayProcessTree",
"(",
")",
"{",
"ps",
":=",
"goprocess",
".",
"FindAll",
"(",
")",
"\n",
"pstree",
"=",
"make",
"(",
"map",
"[",
"int",
"]",
"[",
"]",
"goprocess",
".",
"P",
")",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"ps",
"{",
... | // displayProcessTree displays a tree of all the running Go processes. | [
"displayProcessTree",
"displays",
"a",
"tree",
"of",
"all",
"the",
"running",
"Go",
"processes",
"."
] | 036f72c5be1f7a0970ffae4907e05dd11f49de35 | https://github.com/google/gops/blob/036f72c5be1f7a0970ffae4907e05dd11f49de35/main.go#L183-L196 | train |
google/gops | main.go | constructProcessTree | func constructProcessTree(ppid int, process goprocess.P, seen map[int]bool, tree treeprint.Tree) {
if seen[ppid] {
return
}
seen[ppid] = true
if ppid != process.PPID {
output := strconv.Itoa(ppid) + " (" + process.Exec + ")" + " {" + process.BuildVersion + "}"
if process.Agent {
tree = tree.AddMetaBranch("*", output)
} else {
tree = tree.AddBranch(output)
}
} else {
tree = tree.AddBranch(ppid)
}
for index := range pstree[ppid] {
process := pstree[ppid][index]
constructProcessTree(process.PID, process, seen, tree)
}
} | go | func constructProcessTree(ppid int, process goprocess.P, seen map[int]bool, tree treeprint.Tree) {
if seen[ppid] {
return
}
seen[ppid] = true
if ppid != process.PPID {
output := strconv.Itoa(ppid) + " (" + process.Exec + ")" + " {" + process.BuildVersion + "}"
if process.Agent {
tree = tree.AddMetaBranch("*", output)
} else {
tree = tree.AddBranch(output)
}
} else {
tree = tree.AddBranch(ppid)
}
for index := range pstree[ppid] {
process := pstree[ppid][index]
constructProcessTree(process.PID, process, seen, tree)
}
} | [
"func",
"constructProcessTree",
"(",
"ppid",
"int",
",",
"process",
"goprocess",
".",
"P",
",",
"seen",
"map",
"[",
"int",
"]",
"bool",
",",
"tree",
"treeprint",
".",
"Tree",
")",
"{",
"if",
"seen",
"[",
"ppid",
"]",
"{",
"return",
"\n",
"}",
"\n",
... | // constructProcessTree constructs the process tree in a depth-first fashion. | [
"constructProcessTree",
"constructs",
"the",
"process",
"tree",
"in",
"a",
"depth",
"-",
"first",
"fashion",
"."
] | 036f72c5be1f7a0970ffae4907e05dd11f49de35 | https://github.com/google/gops/blob/036f72c5be1f7a0970ffae4907e05dd11f49de35/main.go#L199-L218 | train |
google/gops | goprocess/gp.go | FindAll | func FindAll() []P {
pss, err := ps.Processes()
if err != nil {
return nil
}
var wg sync.WaitGroup
wg.Add(len(pss))
found := make(chan P)
for _, pr := range pss {
pr := pr
go func() {
defer wg.Done()
path, version, agent, ok, err := isGo(pr)
if err != nil {
// TODO(jbd): Return a list of errors.
}
if !ok {
return
}
found <- P{
PID: pr.Pid(),
PPID: pr.PPid(),
Exec: pr.Executable(),
Path: path,
BuildVersion: version,
Agent: agent,
}
}()
}
go func() {
wg.Wait()
close(found)
}()
var results []P
for p := range found {
results = append(results, p)
}
return results
} | go | func FindAll() []P {
pss, err := ps.Processes()
if err != nil {
return nil
}
var wg sync.WaitGroup
wg.Add(len(pss))
found := make(chan P)
for _, pr := range pss {
pr := pr
go func() {
defer wg.Done()
path, version, agent, ok, err := isGo(pr)
if err != nil {
// TODO(jbd): Return a list of errors.
}
if !ok {
return
}
found <- P{
PID: pr.Pid(),
PPID: pr.PPid(),
Exec: pr.Executable(),
Path: path,
BuildVersion: version,
Agent: agent,
}
}()
}
go func() {
wg.Wait()
close(found)
}()
var results []P
for p := range found {
results = append(results, p)
}
return results
} | [
"func",
"FindAll",
"(",
")",
"[",
"]",
"P",
"{",
"pss",
",",
"err",
":=",
"ps",
".",
"Processes",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"var",
"wg",
"sync",
".",
"WaitGroup",
"\n",
"wg",
".",
"Add",
... | // FindAll returns all the Go processes currently running on this host. | [
"FindAll",
"returns",
"all",
"the",
"Go",
"processes",
"currently",
"running",
"on",
"this",
"host",
"."
] | 036f72c5be1f7a0970ffae4907e05dd11f49de35 | https://github.com/google/gops/blob/036f72c5be1f7a0970ffae4907e05dd11f49de35/goprocess/gp.go#L29-L70 | train |
google/gops | goprocess/gp.go | Find | func Find(pid int) (p P, ok bool, err error) {
pr, err := ps.FindProcess(pid)
if err != nil {
return P{}, false, err
}
path, version, agent, ok, err := isGo(pr)
if !ok {
return P{}, false, nil
}
return P{
PID: pr.Pid(),
PPID: pr.PPid(),
Exec: pr.Executable(),
Path: path,
BuildVersion: version,
Agent: agent,
}, true, nil
} | go | func Find(pid int) (p P, ok bool, err error) {
pr, err := ps.FindProcess(pid)
if err != nil {
return P{}, false, err
}
path, version, agent, ok, err := isGo(pr)
if !ok {
return P{}, false, nil
}
return P{
PID: pr.Pid(),
PPID: pr.PPid(),
Exec: pr.Executable(),
Path: path,
BuildVersion: version,
Agent: agent,
}, true, nil
} | [
"func",
"Find",
"(",
"pid",
"int",
")",
"(",
"p",
"P",
",",
"ok",
"bool",
",",
"err",
"error",
")",
"{",
"pr",
",",
"err",
":=",
"ps",
".",
"FindProcess",
"(",
"pid",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"P",
"{",
"}",
",",
"... | // Find finds info about the process identified with the given PID. | [
"Find",
"finds",
"info",
"about",
"the",
"process",
"identified",
"with",
"the",
"given",
"PID",
"."
] | 036f72c5be1f7a0970ffae4907e05dd11f49de35 | https://github.com/google/gops/blob/036f72c5be1f7a0970ffae4907e05dd11f49de35/goprocess/gp.go#L73-L90 | train |
google/gops | goprocess/gp.go | isGo | func isGo(pr ps.Process) (path, version string, agent, ok bool, err error) {
if pr.Pid() == 0 {
// ignore system process
return
}
path, err = pr.Path()
if err != nil {
return
}
var versionInfo goversion.Version
versionInfo, err = goversion.ReadExe(path)
if err != nil {
return
}
ok = true
version = versionInfo.Release
pidfile, err := internal.PIDFile(pr.Pid())
if err == nil {
_, err := os.Stat(pidfile)
agent = err == nil
}
return path, version, agent, ok, nil
} | go | func isGo(pr ps.Process) (path, version string, agent, ok bool, err error) {
if pr.Pid() == 0 {
// ignore system process
return
}
path, err = pr.Path()
if err != nil {
return
}
var versionInfo goversion.Version
versionInfo, err = goversion.ReadExe(path)
if err != nil {
return
}
ok = true
version = versionInfo.Release
pidfile, err := internal.PIDFile(pr.Pid())
if err == nil {
_, err := os.Stat(pidfile)
agent = err == nil
}
return path, version, agent, ok, nil
} | [
"func",
"isGo",
"(",
"pr",
"ps",
".",
"Process",
")",
"(",
"path",
",",
"version",
"string",
",",
"agent",
",",
"ok",
"bool",
",",
"err",
"error",
")",
"{",
"if",
"pr",
".",
"Pid",
"(",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n",
"path",
... | // isGo looks up the runtime.buildVersion symbol
// in the process' binary and determines if the process
// if a Go process or not. If the process is a Go process,
// it reports PID, binary name and full path of the binary. | [
"isGo",
"looks",
"up",
"the",
"runtime",
".",
"buildVersion",
"symbol",
"in",
"the",
"process",
"binary",
"and",
"determines",
"if",
"the",
"process",
"if",
"a",
"Go",
"process",
"or",
"not",
".",
"If",
"the",
"process",
"is",
"a",
"Go",
"process",
"it",... | 036f72c5be1f7a0970ffae4907e05dd11f49de35 | https://github.com/google/gops/blob/036f72c5be1f7a0970ffae4907e05dd11f49de35/goprocess/gp.go#L96-L118 | train |
google/gops | agent/agent.go | Close | func Close() {
mu.Lock()
defer mu.Unlock()
if portfile != "" {
os.Remove(portfile)
portfile = ""
}
if listener != nil {
listener.Close()
}
} | go | func Close() {
mu.Lock()
defer mu.Unlock()
if portfile != "" {
os.Remove(portfile)
portfile = ""
}
if listener != nil {
listener.Close()
}
} | [
"func",
"Close",
"(",
")",
"{",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"portfile",
"!=",
"\"\"",
"{",
"os",
".",
"Remove",
"(",
"portfile",
")",
"\n",
"portfile",
"=",
"\"\"",
"\n",
"}",
"\n",
"if... | // Close closes the agent, removing temporary files and closing the TCP listener.
// If no agent is listening, Close does nothing. | [
"Close",
"closes",
"the",
"agent",
"removing",
"temporary",
"files",
"and",
"closing",
"the",
"TCP",
"listener",
".",
"If",
"no",
"agent",
"is",
"listening",
"Close",
"does",
"nothing",
"."
] | 036f72c5be1f7a0970ffae4907e05dd11f49de35 | https://github.com/google/gops/blob/036f72c5be1f7a0970ffae4907e05dd11f49de35/agent/agent.go#L150-L161 | train |
mitchellh/gox | go.go | GoMainDirs | func GoMainDirs(packages []string, GoCmd string) ([]string, error) {
args := make([]string, 0, len(packages)+3)
args = append(args, "list", "-f", "{{.Name}}|{{.ImportPath}}")
args = append(args, packages...)
output, err := execGo(GoCmd, nil, "", args...)
if err != nil {
return nil, err
}
results := make([]string, 0, len(output))
for _, line := range strings.Split(output, "\n") {
if line == "" {
continue
}
parts := strings.SplitN(line, "|", 2)
if len(parts) != 2 {
log.Printf("Bad line reading packages: %s", line)
continue
}
if parts[0] == "main" {
results = append(results, parts[1])
}
}
return results, nil
} | go | func GoMainDirs(packages []string, GoCmd string) ([]string, error) {
args := make([]string, 0, len(packages)+3)
args = append(args, "list", "-f", "{{.Name}}|{{.ImportPath}}")
args = append(args, packages...)
output, err := execGo(GoCmd, nil, "", args...)
if err != nil {
return nil, err
}
results := make([]string, 0, len(output))
for _, line := range strings.Split(output, "\n") {
if line == "" {
continue
}
parts := strings.SplitN(line, "|", 2)
if len(parts) != 2 {
log.Printf("Bad line reading packages: %s", line)
continue
}
if parts[0] == "main" {
results = append(results, parts[1])
}
}
return results, nil
} | [
"func",
"GoMainDirs",
"(",
"packages",
"[",
"]",
"string",
",",
"GoCmd",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"args",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"packages",
")",
"+",
"3",
")",
"... | // GoMainDirs returns the file paths to the packages that are "main"
// packages, from the list of packages given. The list of packages can
// include relative paths, the special "..." Go keyword, etc. | [
"GoMainDirs",
"returns",
"the",
"file",
"paths",
"to",
"the",
"packages",
"that",
"are",
"main",
"packages",
"from",
"the",
"list",
"of",
"packages",
"given",
".",
"The",
"list",
"of",
"packages",
"can",
"include",
"relative",
"paths",
"the",
"special",
"...... | d8caaff5a9dc98f4cfa1fcce6e7265a04689f641 | https://github.com/mitchellh/gox/blob/d8caaff5a9dc98f4cfa1fcce6e7265a04689f641/go.go#L129-L157 | train |
mitchellh/gox | go.go | GoRoot | func GoRoot() (string, error) {
output, err := execGo("go", nil, "", "env", "GOROOT")
if err != nil {
return "", err
}
return strings.TrimSpace(output), nil
} | go | func GoRoot() (string, error) {
output, err := execGo("go", nil, "", "env", "GOROOT")
if err != nil {
return "", err
}
return strings.TrimSpace(output), nil
} | [
"func",
"GoRoot",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"output",
",",
"err",
":=",
"execGo",
"(",
"\"go\"",
",",
"nil",
",",
"\"\"",
",",
"\"env\"",
",",
"\"GOROOT\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"... | // GoRoot returns the GOROOT value for the compiled `go` binary. | [
"GoRoot",
"returns",
"the",
"GOROOT",
"value",
"for",
"the",
"compiled",
"go",
"binary",
"."
] | d8caaff5a9dc98f4cfa1fcce6e7265a04689f641 | https://github.com/mitchellh/gox/blob/d8caaff5a9dc98f4cfa1fcce6e7265a04689f641/go.go#L160-L167 | train |
mitchellh/gox | toolchain.go | mainBuildToolchain | func mainBuildToolchain(parallel int, platformFlag PlatformFlag, verbose bool) int {
if _, err := exec.LookPath("go"); err != nil {
fmt.Fprintf(os.Stderr, "You must have Go already built for your native platform\n")
fmt.Fprintf(os.Stderr, "and the `go` binary on the PATH to build toolchains.\n")
return 1
}
// If we're version 1.5 or greater, then we don't need to do this anymore!
versionParts, err := GoVersionParts()
if err != nil {
fmt.Fprintf(os.Stderr, "error reading Go version: %s", err)
return 1
}
if versionParts[0] >= 1 && versionParts[1] >= 5 {
fmt.Fprintf(
os.Stderr,
"-build-toolchain is no longer required for Go 1.5 or later.\n"+
"You can start using Gox immediately!\n")
return 1
}
version, err := GoVersion()
if err != nil {
fmt.Fprintf(os.Stderr, "error reading Go version: %s", err)
return 1
}
root, err := GoRoot()
if err != nil {
fmt.Fprintf(os.Stderr, "error finding GOROOT: %s\n", err)
return 1
}
if verbose {
fmt.Println("Verbose mode enabled. Output from building each toolchain will be")
fmt.Println("outputted to stdout as they are built.\n ")
}
// Determine the platforms we're building the toolchain for.
platforms := platformFlag.Platforms(SupportedPlatforms(version))
// The toolchain build can't be parallelized.
if parallel > 1 {
fmt.Println("The toolchain build can't be parallelized because compiling a single")
fmt.Println("Go source directory can only be done for one platform at a time. Therefore,")
fmt.Println("the toolchain for each platform will be built one at a time.\n ")
}
parallel = 1
var errorLock sync.Mutex
var wg sync.WaitGroup
errs := make([]error, 0)
semaphore := make(chan int, parallel)
for _, platform := range platforms {
wg.Add(1)
go func(platform Platform) {
err := buildToolchain(&wg, semaphore, root, platform, verbose)
if err != nil {
errorLock.Lock()
defer errorLock.Unlock()
errs = append(errs, fmt.Errorf("%s: %s", platform.String(), err))
}
}(platform)
}
wg.Wait()
if len(errs) > 0 {
fmt.Fprintf(os.Stderr, "\n%d errors occurred:\n", len(errs))
for _, err := range errs {
fmt.Fprintf(os.Stderr, "%s\n", err)
}
return 1
}
return 0
} | go | func mainBuildToolchain(parallel int, platformFlag PlatformFlag, verbose bool) int {
if _, err := exec.LookPath("go"); err != nil {
fmt.Fprintf(os.Stderr, "You must have Go already built for your native platform\n")
fmt.Fprintf(os.Stderr, "and the `go` binary on the PATH to build toolchains.\n")
return 1
}
// If we're version 1.5 or greater, then we don't need to do this anymore!
versionParts, err := GoVersionParts()
if err != nil {
fmt.Fprintf(os.Stderr, "error reading Go version: %s", err)
return 1
}
if versionParts[0] >= 1 && versionParts[1] >= 5 {
fmt.Fprintf(
os.Stderr,
"-build-toolchain is no longer required for Go 1.5 or later.\n"+
"You can start using Gox immediately!\n")
return 1
}
version, err := GoVersion()
if err != nil {
fmt.Fprintf(os.Stderr, "error reading Go version: %s", err)
return 1
}
root, err := GoRoot()
if err != nil {
fmt.Fprintf(os.Stderr, "error finding GOROOT: %s\n", err)
return 1
}
if verbose {
fmt.Println("Verbose mode enabled. Output from building each toolchain will be")
fmt.Println("outputted to stdout as they are built.\n ")
}
// Determine the platforms we're building the toolchain for.
platforms := platformFlag.Platforms(SupportedPlatforms(version))
// The toolchain build can't be parallelized.
if parallel > 1 {
fmt.Println("The toolchain build can't be parallelized because compiling a single")
fmt.Println("Go source directory can only be done for one platform at a time. Therefore,")
fmt.Println("the toolchain for each platform will be built one at a time.\n ")
}
parallel = 1
var errorLock sync.Mutex
var wg sync.WaitGroup
errs := make([]error, 0)
semaphore := make(chan int, parallel)
for _, platform := range platforms {
wg.Add(1)
go func(platform Platform) {
err := buildToolchain(&wg, semaphore, root, platform, verbose)
if err != nil {
errorLock.Lock()
defer errorLock.Unlock()
errs = append(errs, fmt.Errorf("%s: %s", platform.String(), err))
}
}(platform)
}
wg.Wait()
if len(errs) > 0 {
fmt.Fprintf(os.Stderr, "\n%d errors occurred:\n", len(errs))
for _, err := range errs {
fmt.Fprintf(os.Stderr, "%s\n", err)
}
return 1
}
return 0
} | [
"func",
"mainBuildToolchain",
"(",
"parallel",
"int",
",",
"platformFlag",
"PlatformFlag",
",",
"verbose",
"bool",
")",
"int",
"{",
"if",
"_",
",",
"err",
":=",
"exec",
".",
"LookPath",
"(",
"\"go\"",
")",
";",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fpr... | // The "main" method for when the toolchain build is requested. | [
"The",
"main",
"method",
"for",
"when",
"the",
"toolchain",
"build",
"is",
"requested",
"."
] | d8caaff5a9dc98f4cfa1fcce6e7265a04689f641 | https://github.com/mitchellh/gox/blob/d8caaff5a9dc98f4cfa1fcce6e7265a04689f641/toolchain.go#L17-L92 | train |
mitchellh/gox | platform.go | SupportedPlatforms | func SupportedPlatforms(v string) []Platform {
// Use latest if we get an unexpected version string
if !strings.HasPrefix(v, "go") {
return PlatformsLatest
}
// go-version only cares about version numbers
v = v[2:]
current, err := version.NewVersion(v)
if err != nil {
log.Printf("Unable to parse current go version: %s\n%s", v, err.Error())
// Default to latest
return PlatformsLatest
}
var platforms = []struct {
constraint string
plat []Platform
}{
{"<= 1.0", Platforms_1_0},
{">= 1.1, < 1.3", Platforms_1_1},
{">= 1.3, < 1.4", Platforms_1_3},
{">= 1.4, < 1.5", Platforms_1_4},
{">= 1.5, < 1.6", Platforms_1_5},
{">= 1.6, < 1.7", Platforms_1_6},
{">= 1.7, < 1.8", Platforms_1_7},
{">= 1.8, < 1.9", Platforms_1_8},
{">= 1.9, < 1.10", Platforms_1_9},
{">=1.10, < 1.11", Platforms_1_10},
}
for _, p := range platforms {
constraints, err := version.NewConstraint(p.constraint)
if err != nil {
panic(err)
}
if constraints.Check(current) {
return p.plat
}
}
// Assume latest
return Platforms_1_9
} | go | func SupportedPlatforms(v string) []Platform {
// Use latest if we get an unexpected version string
if !strings.HasPrefix(v, "go") {
return PlatformsLatest
}
// go-version only cares about version numbers
v = v[2:]
current, err := version.NewVersion(v)
if err != nil {
log.Printf("Unable to parse current go version: %s\n%s", v, err.Error())
// Default to latest
return PlatformsLatest
}
var platforms = []struct {
constraint string
plat []Platform
}{
{"<= 1.0", Platforms_1_0},
{">= 1.1, < 1.3", Platforms_1_1},
{">= 1.3, < 1.4", Platforms_1_3},
{">= 1.4, < 1.5", Platforms_1_4},
{">= 1.5, < 1.6", Platforms_1_5},
{">= 1.6, < 1.7", Platforms_1_6},
{">= 1.7, < 1.8", Platforms_1_7},
{">= 1.8, < 1.9", Platforms_1_8},
{">= 1.9, < 1.10", Platforms_1_9},
{">=1.10, < 1.11", Platforms_1_10},
}
for _, p := range platforms {
constraints, err := version.NewConstraint(p.constraint)
if err != nil {
panic(err)
}
if constraints.Check(current) {
return p.plat
}
}
// Assume latest
return Platforms_1_9
} | [
"func",
"SupportedPlatforms",
"(",
"v",
"string",
")",
"[",
"]",
"Platform",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"v",
",",
"\"go\"",
")",
"{",
"return",
"PlatformsLatest",
"\n",
"}",
"\n",
"v",
"=",
"v",
"[",
"2",
":",
"]",
"\n",
"cur... | // SupportedPlatforms returns the full list of supported platforms for
// the version of Go that is | [
"SupportedPlatforms",
"returns",
"the",
"full",
"list",
"of",
"supported",
"platforms",
"for",
"the",
"version",
"of",
"Go",
"that",
"is"
] | d8caaff5a9dc98f4cfa1fcce6e7265a04689f641 | https://github.com/mitchellh/gox/blob/d8caaff5a9dc98f4cfa1fcce6e7265a04689f641/platform.go#L105-L149 | train |
skip2/go-qrcode | qrcode.go | encode | func (q *QRCode) encode(numTerminatorBits int) {
q.addTerminatorBits(numTerminatorBits)
q.addPadding()
encoded := q.encodeBlocks()
const numMasks int = 8
penalty := 0
for mask := 0; mask < numMasks; mask++ {
var s *symbol
var err error
s, err = buildRegularSymbol(q.version, mask, encoded)
if err != nil {
log.Panic(err.Error())
}
numEmptyModules := s.numEmptyModules()
if numEmptyModules != 0 {
log.Panicf("bug: numEmptyModules is %d (expected 0) (version=%d)",
numEmptyModules, q.VersionNumber)
}
p := s.penaltyScore()
//log.Printf("mask=%d p=%3d p1=%3d p2=%3d p3=%3d p4=%d\n", mask, p, s.penalty1(), s.penalty2(), s.penalty3(), s.penalty4())
if q.symbol == nil || p < penalty {
q.symbol = s
q.mask = mask
penalty = p
}
}
} | go | func (q *QRCode) encode(numTerminatorBits int) {
q.addTerminatorBits(numTerminatorBits)
q.addPadding()
encoded := q.encodeBlocks()
const numMasks int = 8
penalty := 0
for mask := 0; mask < numMasks; mask++ {
var s *symbol
var err error
s, err = buildRegularSymbol(q.version, mask, encoded)
if err != nil {
log.Panic(err.Error())
}
numEmptyModules := s.numEmptyModules()
if numEmptyModules != 0 {
log.Panicf("bug: numEmptyModules is %d (expected 0) (version=%d)",
numEmptyModules, q.VersionNumber)
}
p := s.penaltyScore()
//log.Printf("mask=%d p=%3d p1=%3d p2=%3d p3=%3d p4=%d\n", mask, p, s.penalty1(), s.penalty2(), s.penalty3(), s.penalty4())
if q.symbol == nil || p < penalty {
q.symbol = s
q.mask = mask
penalty = p
}
}
} | [
"func",
"(",
"q",
"*",
"QRCode",
")",
"encode",
"(",
"numTerminatorBits",
"int",
")",
"{",
"q",
".",
"addTerminatorBits",
"(",
"numTerminatorBits",
")",
"\n",
"q",
".",
"addPadding",
"(",
")",
"\n",
"encoded",
":=",
"q",
".",
"encodeBlocks",
"(",
")",
... | // encode completes the steps required to encode the QR Code. These include
// adding the terminator bits and padding, splitting the data into blocks and
// applying the error correction, and selecting the best data mask. | [
"encode",
"completes",
"the",
"steps",
"required",
"to",
"encode",
"the",
"QR",
"Code",
".",
"These",
"include",
"adding",
"the",
"terminator",
"bits",
"and",
"padding",
"splitting",
"the",
"data",
"into",
"blocks",
"and",
"applying",
"the",
"error",
"correcti... | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/qrcode.go#L374-L409 | train |
skip2/go-qrcode | qrcode.go | addPadding | func (q *QRCode) addPadding() {
numDataBits := q.version.numDataBits()
if q.data.Len() == numDataBits {
return
}
// Pad to the nearest codeword boundary.
q.data.AppendNumBools(q.version.numBitsToPadToCodeword(q.data.Len()), false)
// Pad codewords 0b11101100 and 0b00010001.
padding := [2]*bitset.Bitset{
bitset.New(true, true, true, false, true, true, false, false),
bitset.New(false, false, false, true, false, false, false, true),
}
// Insert pad codewords alternately.
i := 0
for numDataBits-q.data.Len() >= 8 {
q.data.Append(padding[i])
i = 1 - i // Alternate between 0 and 1.
}
if q.data.Len() != numDataBits {
log.Panicf("BUG: got len %d, expected %d", q.data.Len(), numDataBits)
}
} | go | func (q *QRCode) addPadding() {
numDataBits := q.version.numDataBits()
if q.data.Len() == numDataBits {
return
}
// Pad to the nearest codeword boundary.
q.data.AppendNumBools(q.version.numBitsToPadToCodeword(q.data.Len()), false)
// Pad codewords 0b11101100 and 0b00010001.
padding := [2]*bitset.Bitset{
bitset.New(true, true, true, false, true, true, false, false),
bitset.New(false, false, false, true, false, false, false, true),
}
// Insert pad codewords alternately.
i := 0
for numDataBits-q.data.Len() >= 8 {
q.data.Append(padding[i])
i = 1 - i // Alternate between 0 and 1.
}
if q.data.Len() != numDataBits {
log.Panicf("BUG: got len %d, expected %d", q.data.Len(), numDataBits)
}
} | [
"func",
"(",
"q",
"*",
"QRCode",
")",
"addPadding",
"(",
")",
"{",
"numDataBits",
":=",
"q",
".",
"version",
".",
"numDataBits",
"(",
")",
"\n",
"if",
"q",
".",
"data",
".",
"Len",
"(",
")",
"==",
"numDataBits",
"{",
"return",
"\n",
"}",
"\n",
"q... | // addPadding pads the encoded data upto the full length required. | [
"addPadding",
"pads",
"the",
"encoded",
"data",
"upto",
"the",
"full",
"length",
"required",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/qrcode.go#L506-L533 | train |
skip2/go-qrcode | qrcode.go | ToString | func (q *QRCode) ToString(inverseColor bool) string {
bits := q.Bitmap()
var buf bytes.Buffer
for y := range bits {
for x := range bits[y] {
if bits[y][x] != inverseColor {
buf.WriteString(" ")
} else {
buf.WriteString("██")
}
}
buf.WriteString("\n")
}
return buf.String()
} | go | func (q *QRCode) ToString(inverseColor bool) string {
bits := q.Bitmap()
var buf bytes.Buffer
for y := range bits {
for x := range bits[y] {
if bits[y][x] != inverseColor {
buf.WriteString(" ")
} else {
buf.WriteString("██")
}
}
buf.WriteString("\n")
}
return buf.String()
} | [
"func",
"(",
"q",
"*",
"QRCode",
")",
"ToString",
"(",
"inverseColor",
"bool",
")",
"string",
"{",
"bits",
":=",
"q",
".",
"Bitmap",
"(",
")",
"\n",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"for",
"y",
":=",
"range",
"bits",
"{",
"for",
"x",
"... | // ToString produces a multi-line string that forms a QR-code image. | [
"ToString",
"produces",
"a",
"multi",
"-",
"line",
"string",
"that",
"forms",
"a",
"QR",
"-",
"code",
"image",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/qrcode.go#L536-L550 | train |
skip2/go-qrcode | qrcode.go | ToSmallString | func (q *QRCode) ToSmallString(inverseColor bool) string {
bits := q.Bitmap()
var buf bytes.Buffer
// if there is an odd number of rows, the last one needs special treatment
for y := 0; y < len(bits)-1; y += 2 {
for x := range bits[y] {
if bits[y][x] == bits[y+1][x] {
if bits[y][x] != inverseColor {
buf.WriteString(" ")
} else {
buf.WriteString("█")
}
} else {
if bits[y][x] != inverseColor {
buf.WriteString("▄")
} else {
buf.WriteString("▀")
}
}
}
buf.WriteString("\n")
}
// special treatment for the last row if odd
if len(bits)%2 == 1 {
y := len(bits) - 1
for x := range bits[y] {
if bits[y][x] != inverseColor {
buf.WriteString(" ")
} else {
buf.WriteString("▀")
}
}
buf.WriteString("\n")
}
return buf.String()
} | go | func (q *QRCode) ToSmallString(inverseColor bool) string {
bits := q.Bitmap()
var buf bytes.Buffer
// if there is an odd number of rows, the last one needs special treatment
for y := 0; y < len(bits)-1; y += 2 {
for x := range bits[y] {
if bits[y][x] == bits[y+1][x] {
if bits[y][x] != inverseColor {
buf.WriteString(" ")
} else {
buf.WriteString("█")
}
} else {
if bits[y][x] != inverseColor {
buf.WriteString("▄")
} else {
buf.WriteString("▀")
}
}
}
buf.WriteString("\n")
}
// special treatment for the last row if odd
if len(bits)%2 == 1 {
y := len(bits) - 1
for x := range bits[y] {
if bits[y][x] != inverseColor {
buf.WriteString(" ")
} else {
buf.WriteString("▀")
}
}
buf.WriteString("\n")
}
return buf.String()
} | [
"func",
"(",
"q",
"*",
"QRCode",
")",
"ToSmallString",
"(",
"inverseColor",
"bool",
")",
"string",
"{",
"bits",
":=",
"q",
".",
"Bitmap",
"(",
")",
"\n",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"for",
"y",
":=",
"0",
";",
"y",
"<",
"len",
"("... | // ToSmallString produces a multi-line string that forms a QR-code image, a
// factor two smaller in x and y then ToString. | [
"ToSmallString",
"produces",
"a",
"multi",
"-",
"line",
"string",
"that",
"forms",
"a",
"QR",
"-",
"code",
"image",
"a",
"factor",
"two",
"smaller",
"in",
"x",
"and",
"y",
"then",
"ToString",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/qrcode.go#L554-L589 | train |
skip2/go-qrcode | bitset/bitset.go | New | func New(v ...bool) *Bitset {
b := &Bitset{numBits: 0, bits: make([]byte, 0)}
b.AppendBools(v...)
return b
} | go | func New(v ...bool) *Bitset {
b := &Bitset{numBits: 0, bits: make([]byte, 0)}
b.AppendBools(v...)
return b
} | [
"func",
"New",
"(",
"v",
"...",
"bool",
")",
"*",
"Bitset",
"{",
"b",
":=",
"&",
"Bitset",
"{",
"numBits",
":",
"0",
",",
"bits",
":",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
")",
"}",
"\n",
"b",
".",
"AppendBools",
"(",
"v",
"...",
")",
"... | // New returns an initialised Bitset with optional initial bits v. | [
"New",
"returns",
"an",
"initialised",
"Bitset",
"with",
"optional",
"initial",
"bits",
"v",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/bitset/bitset.go#L43-L48 | train |
skip2/go-qrcode | bitset/bitset.go | Clone | func Clone(from *Bitset) *Bitset {
return &Bitset{numBits: from.numBits, bits: from.bits[:]}
} | go | func Clone(from *Bitset) *Bitset {
return &Bitset{numBits: from.numBits, bits: from.bits[:]}
} | [
"func",
"Clone",
"(",
"from",
"*",
"Bitset",
")",
"*",
"Bitset",
"{",
"return",
"&",
"Bitset",
"{",
"numBits",
":",
"from",
".",
"numBits",
",",
"bits",
":",
"from",
".",
"bits",
"[",
":",
"]",
"}",
"\n",
"}"
] | // Clone returns a copy. | [
"Clone",
"returns",
"a",
"copy",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/bitset/bitset.go#L51-L53 | train |
skip2/go-qrcode | bitset/bitset.go | Substr | func (b *Bitset) Substr(start int, end int) *Bitset {
if start > end || end > b.numBits {
log.Panicf("Out of range start=%d end=%d numBits=%d", start, end, b.numBits)
}
result := New()
result.ensureCapacity(end - start)
for i := start; i < end; i++ {
if b.At(i) {
result.bits[result.numBits/8] |= 0x80 >> uint(result.numBits%8)
}
result.numBits++
}
return result
} | go | func (b *Bitset) Substr(start int, end int) *Bitset {
if start > end || end > b.numBits {
log.Panicf("Out of range start=%d end=%d numBits=%d", start, end, b.numBits)
}
result := New()
result.ensureCapacity(end - start)
for i := start; i < end; i++ {
if b.At(i) {
result.bits[result.numBits/8] |= 0x80 >> uint(result.numBits%8)
}
result.numBits++
}
return result
} | [
"func",
"(",
"b",
"*",
"Bitset",
")",
"Substr",
"(",
"start",
"int",
",",
"end",
"int",
")",
"*",
"Bitset",
"{",
"if",
"start",
">",
"end",
"||",
"end",
">",
"b",
".",
"numBits",
"{",
"log",
".",
"Panicf",
"(",
"\"Out of range start=%d end=%d numBits=%... | // Substr returns a substring, consisting of the bits from indexes start to end. | [
"Substr",
"returns",
"a",
"substring",
"consisting",
"of",
"the",
"bits",
"from",
"indexes",
"start",
"to",
"end",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/bitset/bitset.go#L56-L72 | train |
skip2/go-qrcode | bitset/bitset.go | AppendBytes | func (b *Bitset) AppendBytes(data []byte) {
for _, d := range data {
b.AppendByte(d, 8)
}
} | go | func (b *Bitset) AppendBytes(data []byte) {
for _, d := range data {
b.AppendByte(d, 8)
}
} | [
"func",
"(",
"b",
"*",
"Bitset",
")",
"AppendBytes",
"(",
"data",
"[",
"]",
"byte",
")",
"{",
"for",
"_",
",",
"d",
":=",
"range",
"data",
"{",
"b",
".",
"AppendByte",
"(",
"d",
",",
"8",
")",
"\n",
"}",
"\n",
"}"
] | // AppendBytes appends a list of whole bytes. | [
"AppendBytes",
"appends",
"a",
"list",
"of",
"whole",
"bytes",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/bitset/bitset.go#L99-L103 | train |
skip2/go-qrcode | bitset/bitset.go | AppendByte | func (b *Bitset) AppendByte(value byte, numBits int) {
b.ensureCapacity(numBits)
if numBits > 8 {
log.Panicf("numBits %d out of range 0-8", numBits)
}
for i := numBits - 1; i >= 0; i-- {
if value&(1<<uint(i)) != 0 {
b.bits[b.numBits/8] |= 0x80 >> uint(b.numBits%8)
}
b.numBits++
}
} | go | func (b *Bitset) AppendByte(value byte, numBits int) {
b.ensureCapacity(numBits)
if numBits > 8 {
log.Panicf("numBits %d out of range 0-8", numBits)
}
for i := numBits - 1; i >= 0; i-- {
if value&(1<<uint(i)) != 0 {
b.bits[b.numBits/8] |= 0x80 >> uint(b.numBits%8)
}
b.numBits++
}
} | [
"func",
"(",
"b",
"*",
"Bitset",
")",
"AppendByte",
"(",
"value",
"byte",
",",
"numBits",
"int",
")",
"{",
"b",
".",
"ensureCapacity",
"(",
"numBits",
")",
"\n",
"if",
"numBits",
">",
"8",
"{",
"log",
".",
"Panicf",
"(",
"\"numBits %d out of range 0-8\""... | // AppendByte appends the numBits least significant bits from value. | [
"AppendByte",
"appends",
"the",
"numBits",
"least",
"significant",
"bits",
"from",
"value",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/bitset/bitset.go#L106-L120 | train |
skip2/go-qrcode | bitset/bitset.go | AppendUint32 | func (b *Bitset) AppendUint32(value uint32, numBits int) {
b.ensureCapacity(numBits)
if numBits > 32 {
log.Panicf("numBits %d out of range 0-32", numBits)
}
for i := numBits - 1; i >= 0; i-- {
if value&(1<<uint(i)) != 0 {
b.bits[b.numBits/8] |= 0x80 >> uint(b.numBits%8)
}
b.numBits++
}
} | go | func (b *Bitset) AppendUint32(value uint32, numBits int) {
b.ensureCapacity(numBits)
if numBits > 32 {
log.Panicf("numBits %d out of range 0-32", numBits)
}
for i := numBits - 1; i >= 0; i-- {
if value&(1<<uint(i)) != 0 {
b.bits[b.numBits/8] |= 0x80 >> uint(b.numBits%8)
}
b.numBits++
}
} | [
"func",
"(",
"b",
"*",
"Bitset",
")",
"AppendUint32",
"(",
"value",
"uint32",
",",
"numBits",
"int",
")",
"{",
"b",
".",
"ensureCapacity",
"(",
"numBits",
")",
"\n",
"if",
"numBits",
">",
"32",
"{",
"log",
".",
"Panicf",
"(",
"\"numBits %d out of range 0... | // AppendUint32 appends the numBits least significant bits from value. | [
"AppendUint32",
"appends",
"the",
"numBits",
"least",
"significant",
"bits",
"from",
"value",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/bitset/bitset.go#L123-L137 | train |
skip2/go-qrcode | bitset/bitset.go | ensureCapacity | func (b *Bitset) ensureCapacity(numBits int) {
numBits += b.numBits
newNumBytes := numBits / 8
if numBits%8 != 0 {
newNumBytes++
}
if len(b.bits) >= newNumBytes {
return
}
b.bits = append(b.bits, make([]byte, newNumBytes+2*len(b.bits))...)
} | go | func (b *Bitset) ensureCapacity(numBits int) {
numBits += b.numBits
newNumBytes := numBits / 8
if numBits%8 != 0 {
newNumBytes++
}
if len(b.bits) >= newNumBytes {
return
}
b.bits = append(b.bits, make([]byte, newNumBytes+2*len(b.bits))...)
} | [
"func",
"(",
"b",
"*",
"Bitset",
")",
"ensureCapacity",
"(",
"numBits",
"int",
")",
"{",
"numBits",
"+=",
"b",
".",
"numBits",
"\n",
"newNumBytes",
":=",
"numBits",
"/",
"8",
"\n",
"if",
"numBits",
"%",
"8",
"!=",
"0",
"{",
"newNumBytes",
"++",
"\n",... | // ensureCapacity ensures the Bitset can store an additional |numBits|.
//
// The underlying array is expanded if necessary. To prevent frequent
// reallocation, expanding the underlying array at least doubles its capacity. | [
"ensureCapacity",
"ensures",
"the",
"Bitset",
"can",
"store",
"an",
"additional",
"|numBits|",
".",
"The",
"underlying",
"array",
"is",
"expanded",
"if",
"necessary",
".",
"To",
"prevent",
"frequent",
"reallocation",
"expanding",
"the",
"underlying",
"array",
"at"... | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/bitset/bitset.go#L143-L156 | train |
skip2/go-qrcode | bitset/bitset.go | AppendBools | func (b *Bitset) AppendBools(bits ...bool) {
b.ensureCapacity(len(bits))
for _, v := range bits {
if v {
b.bits[b.numBits/8] |= 0x80 >> uint(b.numBits%8)
}
b.numBits++
}
} | go | func (b *Bitset) AppendBools(bits ...bool) {
b.ensureCapacity(len(bits))
for _, v := range bits {
if v {
b.bits[b.numBits/8] |= 0x80 >> uint(b.numBits%8)
}
b.numBits++
}
} | [
"func",
"(",
"b",
"*",
"Bitset",
")",
"AppendBools",
"(",
"bits",
"...",
"bool",
")",
"{",
"b",
".",
"ensureCapacity",
"(",
"len",
"(",
"bits",
")",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"bits",
"{",
"if",
"v",
"{",
"b",
".",
"bits",
... | // AppendBools appends bits to the Bitset. | [
"AppendBools",
"appends",
"bits",
"to",
"the",
"Bitset",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/bitset/bitset.go#L173-L182 | train |
skip2/go-qrcode | bitset/bitset.go | AppendNumBools | func (b *Bitset) AppendNumBools(num int, value bool) {
for i := 0; i < num; i++ {
b.AppendBools(value)
}
} | go | func (b *Bitset) AppendNumBools(num int, value bool) {
for i := 0; i < num; i++ {
b.AppendBools(value)
}
} | [
"func",
"(",
"b",
"*",
"Bitset",
")",
"AppendNumBools",
"(",
"num",
"int",
",",
"value",
"bool",
")",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"num",
";",
"i",
"++",
"{",
"b",
".",
"AppendBools",
"(",
"value",
")",
"\n",
"}",
"\n",
"}"
] | // AppendNumBools appends num bits of value value. | [
"AppendNumBools",
"appends",
"num",
"bits",
"of",
"value",
"value",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/bitset/bitset.go#L185-L189 | train |
skip2/go-qrcode | bitset/bitset.go | String | func (b *Bitset) String() string {
var bitString string
for i := 0; i < b.numBits; i++ {
if (i % 8) == 0 {
bitString += " "
}
if (b.bits[i/8] & (0x80 >> byte(i%8))) != 0 {
bitString += "1"
} else {
bitString += "0"
}
}
return fmt.Sprintf("numBits=%d, bits=%s", b.numBits, bitString)
} | go | func (b *Bitset) String() string {
var bitString string
for i := 0; i < b.numBits; i++ {
if (i % 8) == 0 {
bitString += " "
}
if (b.bits[i/8] & (0x80 >> byte(i%8))) != 0 {
bitString += "1"
} else {
bitString += "0"
}
}
return fmt.Sprintf("numBits=%d, bits=%s", b.numBits, bitString)
} | [
"func",
"(",
"b",
"*",
"Bitset",
")",
"String",
"(",
")",
"string",
"{",
"var",
"bitString",
"string",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"b",
".",
"numBits",
";",
"i",
"++",
"{",
"if",
"(",
"i",
"%",
"8",
")",
"==",
"0",
"{",
"bit... | // String returns a human readable representation of the Bitset's contents. | [
"String",
"returns",
"a",
"human",
"readable",
"representation",
"of",
"the",
"Bitset",
"s",
"contents",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/bitset/bitset.go#L192-L207 | train |
skip2/go-qrcode | bitset/bitset.go | Bits | func (b *Bitset) Bits() []bool {
result := make([]bool, b.numBits)
var i int
for i = 0; i < b.numBits; i++ {
result[i] = (b.bits[i/8] & (0x80 >> byte(i%8))) != 0
}
return result
} | go | func (b *Bitset) Bits() []bool {
result := make([]bool, b.numBits)
var i int
for i = 0; i < b.numBits; i++ {
result[i] = (b.bits[i/8] & (0x80 >> byte(i%8))) != 0
}
return result
} | [
"func",
"(",
"b",
"*",
"Bitset",
")",
"Bits",
"(",
")",
"[",
"]",
"bool",
"{",
"result",
":=",
"make",
"(",
"[",
"]",
"bool",
",",
"b",
".",
"numBits",
")",
"\n",
"var",
"i",
"int",
"\n",
"for",
"i",
"=",
"0",
";",
"i",
"<",
"b",
".",
"nu... | // Bits returns the contents of the Bitset. | [
"Bits",
"returns",
"the",
"contents",
"of",
"the",
"Bitset",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/bitset/bitset.go#L215-L224 | train |
skip2/go-qrcode | bitset/bitset.go | At | func (b *Bitset) At(index int) bool {
if index >= b.numBits {
log.Panicf("Index %d out of range", index)
}
return (b.bits[index/8] & (0x80 >> byte(index%8))) != 0
} | go | func (b *Bitset) At(index int) bool {
if index >= b.numBits {
log.Panicf("Index %d out of range", index)
}
return (b.bits[index/8] & (0x80 >> byte(index%8))) != 0
} | [
"func",
"(",
"b",
"*",
"Bitset",
")",
"At",
"(",
"index",
"int",
")",
"bool",
"{",
"if",
"index",
">=",
"b",
".",
"numBits",
"{",
"log",
".",
"Panicf",
"(",
"\"Index %d out of range\"",
",",
"index",
")",
"\n",
"}",
"\n",
"return",
"(",
"b",
".",
... | // At returns the value of the bit at |index|. | [
"At",
"returns",
"the",
"value",
"of",
"the",
"bit",
"at",
"|index|",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/bitset/bitset.go#L227-L233 | train |
skip2/go-qrcode | bitset/bitset.go | Equals | func (b *Bitset) Equals(other *Bitset) bool {
if b.numBits != other.numBits {
return false
}
if !bytes.Equal(b.bits[0:b.numBits/8], other.bits[0:b.numBits/8]) {
return false
}
for i := 8 * (b.numBits / 8); i < b.numBits; i++ {
a := (b.bits[i/8] & (0x80 >> byte(i%8)))
b := (other.bits[i/8] & (0x80 >> byte(i%8)))
if a != b {
return false
}
}
return true
} | go | func (b *Bitset) Equals(other *Bitset) bool {
if b.numBits != other.numBits {
return false
}
if !bytes.Equal(b.bits[0:b.numBits/8], other.bits[0:b.numBits/8]) {
return false
}
for i := 8 * (b.numBits / 8); i < b.numBits; i++ {
a := (b.bits[i/8] & (0x80 >> byte(i%8)))
b := (other.bits[i/8] & (0x80 >> byte(i%8)))
if a != b {
return false
}
}
return true
} | [
"func",
"(",
"b",
"*",
"Bitset",
")",
"Equals",
"(",
"other",
"*",
"Bitset",
")",
"bool",
"{",
"if",
"b",
".",
"numBits",
"!=",
"other",
".",
"numBits",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"!",
"bytes",
".",
"Equal",
"(",
"b",
".",
"... | // Equals returns true if the Bitset equals other. | [
"Equals",
"returns",
"true",
"if",
"the",
"Bitset",
"equals",
"other",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/bitset/bitset.go#L236-L255 | train |
skip2/go-qrcode | bitset/bitset.go | ByteAt | func (b *Bitset) ByteAt(index int) byte {
if index < 0 || index >= b.numBits {
log.Panicf("Index %d out of range", index)
}
var result byte
for i := index; i < index+8 && i < b.numBits; i++ {
result <<= 1
if b.At(i) {
result |= 1
}
}
return result
} | go | func (b *Bitset) ByteAt(index int) byte {
if index < 0 || index >= b.numBits {
log.Panicf("Index %d out of range", index)
}
var result byte
for i := index; i < index+8 && i < b.numBits; i++ {
result <<= 1
if b.At(i) {
result |= 1
}
}
return result
} | [
"func",
"(",
"b",
"*",
"Bitset",
")",
"ByteAt",
"(",
"index",
"int",
")",
"byte",
"{",
"if",
"index",
"<",
"0",
"||",
"index",
">=",
"b",
".",
"numBits",
"{",
"log",
".",
"Panicf",
"(",
"\"Index %d out of range\"",
",",
"index",
")",
"\n",
"}",
"\n... | // ByteAt returns a byte consisting of upto 8 bits starting at index. | [
"ByteAt",
"returns",
"a",
"byte",
"consisting",
"of",
"upto",
"8",
"bits",
"starting",
"at",
"index",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/bitset/bitset.go#L258-L273 | train |
skip2/go-qrcode | symbol.go | bitmap | func (m *symbol) bitmap() [][]bool {
module := make([][]bool, len(m.module))
for i := range m.module {
module[i] = m.module[i][:]
}
return module
} | go | func (m *symbol) bitmap() [][]bool {
module := make([][]bool, len(m.module))
for i := range m.module {
module[i] = m.module[i][:]
}
return module
} | [
"func",
"(",
"m",
"*",
"symbol",
")",
"bitmap",
"(",
")",
"[",
"]",
"[",
"]",
"bool",
"{",
"module",
":=",
"make",
"(",
"[",
"]",
"[",
"]",
"bool",
",",
"len",
"(",
"m",
".",
"module",
")",
")",
"\n",
"for",
"i",
":=",
"range",
"m",
".",
... | // bitmap returns the entire symbol, including the quiet zone. | [
"bitmap",
"returns",
"the",
"entire",
"symbol",
"including",
"the",
"quiet",
"zone",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/symbol.go#L109-L117 | train |
skip2/go-qrcode | symbol.go | string | func (m *symbol) string() string {
var result string
for _, row := range m.module {
for _, value := range row {
switch value {
case true:
result += " "
case false:
// Unicode 'FULL BLOCK' (U+2588).
result += "██"
}
}
result += "\n"
}
return result
} | go | func (m *symbol) string() string {
var result string
for _, row := range m.module {
for _, value := range row {
switch value {
case true:
result += " "
case false:
// Unicode 'FULL BLOCK' (U+2588).
result += "██"
}
}
result += "\n"
}
return result
} | [
"func",
"(",
"m",
"*",
"symbol",
")",
"string",
"(",
")",
"string",
"{",
"var",
"result",
"string",
"\n",
"for",
"_",
",",
"row",
":=",
"range",
"m",
".",
"module",
"{",
"for",
"_",
",",
"value",
":=",
"range",
"row",
"{",
"switch",
"value",
"{",... | // string returns a pictorial representation of the symbol, suitable for
// printing in a TTY. | [
"string",
"returns",
"a",
"pictorial",
"representation",
"of",
"the",
"symbol",
"suitable",
"for",
"printing",
"in",
"a",
"TTY",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/symbol.go#L121-L138 | train |
skip2/go-qrcode | symbol.go | penaltyScore | func (m *symbol) penaltyScore() int {
return m.penalty1() + m.penalty2() + m.penalty3() + m.penalty4()
} | go | func (m *symbol) penaltyScore() int {
return m.penalty1() + m.penalty2() + m.penalty3() + m.penalty4()
} | [
"func",
"(",
"m",
"*",
"symbol",
")",
"penaltyScore",
"(",
")",
"int",
"{",
"return",
"m",
".",
"penalty1",
"(",
")",
"+",
"m",
".",
"penalty2",
"(",
")",
"+",
"m",
".",
"penalty3",
"(",
")",
"+",
"m",
".",
"penalty4",
"(",
")",
"\n",
"}"
] | // penaltyScore returns the penalty score of the symbol. The penalty score
// consists of the sum of the four individual penalty types. | [
"penaltyScore",
"returns",
"the",
"penalty",
"score",
"of",
"the",
"symbol",
".",
"The",
"penalty",
"score",
"consists",
"of",
"the",
"sum",
"of",
"the",
"four",
"individual",
"penalty",
"types",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/symbol.go#L151-L153 | train |
skip2/go-qrcode | symbol.go | penalty4 | func (m *symbol) penalty4() int {
numModules := m.symbolSize * m.symbolSize
numDarkModules := 0
for x := 0; x < m.symbolSize; x++ {
for y := 0; y < m.symbolSize; y++ {
if v := m.get(x, y); v {
numDarkModules++
}
}
}
numDarkModuleDeviation := numModules/2 - numDarkModules
if numDarkModuleDeviation < 0 {
numDarkModuleDeviation *= -1
}
return penaltyWeight4 * (numDarkModuleDeviation / (numModules / 20))
} | go | func (m *symbol) penalty4() int {
numModules := m.symbolSize * m.symbolSize
numDarkModules := 0
for x := 0; x < m.symbolSize; x++ {
for y := 0; y < m.symbolSize; y++ {
if v := m.get(x, y); v {
numDarkModules++
}
}
}
numDarkModuleDeviation := numModules/2 - numDarkModules
if numDarkModuleDeviation < 0 {
numDarkModuleDeviation *= -1
}
return penaltyWeight4 * (numDarkModuleDeviation / (numModules / 20))
} | [
"func",
"(",
"m",
"*",
"symbol",
")",
"penalty4",
"(",
")",
"int",
"{",
"numModules",
":=",
"m",
".",
"symbolSize",
"*",
"m",
".",
"symbolSize",
"\n",
"numDarkModules",
":=",
"0",
"\n",
"for",
"x",
":=",
"0",
";",
"x",
"<",
"m",
".",
"symbolSize",
... | // penalty4 returns the penalty score... | [
"penalty4",
"returns",
"the",
"penalty",
"score",
"..."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/symbol.go#L291-L309 | train |
skip2/go-qrcode | reedsolomon/gf_poly.go | gfPolyAdd | func gfPolyAdd(a, b gfPoly) gfPoly {
numATerms := a.numTerms()
numBTerms := b.numTerms()
numTerms := numATerms
if numBTerms > numTerms {
numTerms = numBTerms
}
result := gfPoly{term: make([]gfElement, numTerms)}
for i := 0; i < numTerms; i++ {
switch {
case numATerms > i && numBTerms > i:
result.term[i] = gfAdd(a.term[i], b.term[i])
case numATerms > i:
result.term[i] = a.term[i]
default:
result.term[i] = b.term[i]
}
}
return result.normalised()
} | go | func gfPolyAdd(a, b gfPoly) gfPoly {
numATerms := a.numTerms()
numBTerms := b.numTerms()
numTerms := numATerms
if numBTerms > numTerms {
numTerms = numBTerms
}
result := gfPoly{term: make([]gfElement, numTerms)}
for i := 0; i < numTerms; i++ {
switch {
case numATerms > i && numBTerms > i:
result.term[i] = gfAdd(a.term[i], b.term[i])
case numATerms > i:
result.term[i] = a.term[i]
default:
result.term[i] = b.term[i]
}
}
return result.normalised()
} | [
"func",
"gfPolyAdd",
"(",
"a",
",",
"b",
"gfPoly",
")",
"gfPoly",
"{",
"numATerms",
":=",
"a",
".",
"numTerms",
"(",
")",
"\n",
"numBTerms",
":=",
"b",
".",
"numTerms",
"(",
")",
"\n",
"numTerms",
":=",
"numATerms",
"\n",
"if",
"numBTerms",
">",
"num... | // gfPolyAdd returns a + b. | [
"gfPolyAdd",
"returns",
"a",
"+",
"b",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/reedsolomon/gf_poly.go#L116-L139 | train |
skip2/go-qrcode | reedsolomon/gf_poly.go | equals | func (e gfPoly) equals(other gfPoly) bool {
var minecPoly *gfPoly
var maxecPoly *gfPoly
if e.numTerms() > other.numTerms() {
minecPoly = &other
maxecPoly = &e
} else {
minecPoly = &e
maxecPoly = &other
}
numMinTerms := minecPoly.numTerms()
numMaxTerms := maxecPoly.numTerms()
for i := 0; i < numMinTerms; i++ {
if e.term[i] != other.term[i] {
return false
}
}
for i := numMinTerms; i < numMaxTerms; i++ {
if maxecPoly.term[i] != 0 {
return false
}
}
return true
} | go | func (e gfPoly) equals(other gfPoly) bool {
var minecPoly *gfPoly
var maxecPoly *gfPoly
if e.numTerms() > other.numTerms() {
minecPoly = &other
maxecPoly = &e
} else {
minecPoly = &e
maxecPoly = &other
}
numMinTerms := minecPoly.numTerms()
numMaxTerms := maxecPoly.numTerms()
for i := 0; i < numMinTerms; i++ {
if e.term[i] != other.term[i] {
return false
}
}
for i := numMinTerms; i < numMaxTerms; i++ {
if maxecPoly.term[i] != 0 {
return false
}
}
return true
} | [
"func",
"(",
"e",
"gfPoly",
")",
"equals",
"(",
"other",
"gfPoly",
")",
"bool",
"{",
"var",
"minecPoly",
"*",
"gfPoly",
"\n",
"var",
"maxecPoly",
"*",
"gfPoly",
"\n",
"if",
"e",
".",
"numTerms",
"(",
")",
">",
"other",
".",
"numTerms",
"(",
")",
"{... | // equals returns true if e == other. | [
"equals",
"returns",
"true",
"if",
"e",
"==",
"other",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/reedsolomon/gf_poly.go#L188-L216 | train |
skip2/go-qrcode | encoder.go | newDataEncoder | func newDataEncoder(t dataEncoderType) *dataEncoder {
d := &dataEncoder{}
switch t {
case dataEncoderType1To9:
d = &dataEncoder{
minVersion: 1,
maxVersion: 9,
numericModeIndicator: bitset.New(b0, b0, b0, b1),
alphanumericModeIndicator: bitset.New(b0, b0, b1, b0),
byteModeIndicator: bitset.New(b0, b1, b0, b0),
numNumericCharCountBits: 10,
numAlphanumericCharCountBits: 9,
numByteCharCountBits: 8,
}
case dataEncoderType10To26:
d = &dataEncoder{
minVersion: 10,
maxVersion: 26,
numericModeIndicator: bitset.New(b0, b0, b0, b1),
alphanumericModeIndicator: bitset.New(b0, b0, b1, b0),
byteModeIndicator: bitset.New(b0, b1, b0, b0),
numNumericCharCountBits: 12,
numAlphanumericCharCountBits: 11,
numByteCharCountBits: 16,
}
case dataEncoderType27To40:
d = &dataEncoder{
minVersion: 27,
maxVersion: 40,
numericModeIndicator: bitset.New(b0, b0, b0, b1),
alphanumericModeIndicator: bitset.New(b0, b0, b1, b0),
byteModeIndicator: bitset.New(b0, b1, b0, b0),
numNumericCharCountBits: 14,
numAlphanumericCharCountBits: 13,
numByteCharCountBits: 16,
}
default:
log.Panic("Unknown dataEncoderType")
}
return d
} | go | func newDataEncoder(t dataEncoderType) *dataEncoder {
d := &dataEncoder{}
switch t {
case dataEncoderType1To9:
d = &dataEncoder{
minVersion: 1,
maxVersion: 9,
numericModeIndicator: bitset.New(b0, b0, b0, b1),
alphanumericModeIndicator: bitset.New(b0, b0, b1, b0),
byteModeIndicator: bitset.New(b0, b1, b0, b0),
numNumericCharCountBits: 10,
numAlphanumericCharCountBits: 9,
numByteCharCountBits: 8,
}
case dataEncoderType10To26:
d = &dataEncoder{
minVersion: 10,
maxVersion: 26,
numericModeIndicator: bitset.New(b0, b0, b0, b1),
alphanumericModeIndicator: bitset.New(b0, b0, b1, b0),
byteModeIndicator: bitset.New(b0, b1, b0, b0),
numNumericCharCountBits: 12,
numAlphanumericCharCountBits: 11,
numByteCharCountBits: 16,
}
case dataEncoderType27To40:
d = &dataEncoder{
minVersion: 27,
maxVersion: 40,
numericModeIndicator: bitset.New(b0, b0, b0, b1),
alphanumericModeIndicator: bitset.New(b0, b0, b1, b0),
byteModeIndicator: bitset.New(b0, b1, b0, b0),
numNumericCharCountBits: 14,
numAlphanumericCharCountBits: 13,
numByteCharCountBits: 16,
}
default:
log.Panic("Unknown dataEncoderType")
}
return d
} | [
"func",
"newDataEncoder",
"(",
"t",
"dataEncoderType",
")",
"*",
"dataEncoder",
"{",
"d",
":=",
"&",
"dataEncoder",
"{",
"}",
"\n",
"switch",
"t",
"{",
"case",
"dataEncoderType1To9",
":",
"d",
"=",
"&",
"dataEncoder",
"{",
"minVersion",
":",
"1",
",",
"m... | // newDataEncoder constructs a dataEncoder. | [
"newDataEncoder",
"constructs",
"a",
"dataEncoder",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/encoder.go#L118-L160 | train |
skip2/go-qrcode | encoder.go | encode | func (d *dataEncoder) encode(data []byte) (*bitset.Bitset, error) {
d.data = data
d.actual = nil
d.optimised = nil
if len(data) == 0 {
return nil, errors.New("no data to encode")
}
// Classify data into unoptimised segments.
d.classifyDataModes()
// Optimise segments.
err := d.optimiseDataModes()
if err != nil {
return nil, err
}
// Encode data.
encoded := bitset.New()
for _, s := range d.optimised {
d.encodeDataRaw(s.data, s.dataMode, encoded)
}
return encoded, nil
} | go | func (d *dataEncoder) encode(data []byte) (*bitset.Bitset, error) {
d.data = data
d.actual = nil
d.optimised = nil
if len(data) == 0 {
return nil, errors.New("no data to encode")
}
// Classify data into unoptimised segments.
d.classifyDataModes()
// Optimise segments.
err := d.optimiseDataModes()
if err != nil {
return nil, err
}
// Encode data.
encoded := bitset.New()
for _, s := range d.optimised {
d.encodeDataRaw(s.data, s.dataMode, encoded)
}
return encoded, nil
} | [
"func",
"(",
"d",
"*",
"dataEncoder",
")",
"encode",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"*",
"bitset",
".",
"Bitset",
",",
"error",
")",
"{",
"d",
".",
"data",
"=",
"data",
"\n",
"d",
".",
"actual",
"=",
"nil",
"\n",
"d",
".",
"optimised"... | // encode data as one or more segments and return the encoded data.
//
// The returned data does not include the terminator bit sequence. | [
"encode",
"data",
"as",
"one",
"or",
"more",
"segments",
"and",
"return",
"the",
"encoded",
"data",
".",
"The",
"returned",
"data",
"does",
"not",
"include",
"the",
"terminator",
"bit",
"sequence",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/encoder.go#L165-L190 | train |
skip2/go-qrcode | encoder.go | encodeDataRaw | func (d *dataEncoder) encodeDataRaw(data []byte, dataMode dataMode, encoded *bitset.Bitset) {
modeIndicator := d.modeIndicator(dataMode)
charCountBits := d.charCountBits(dataMode)
// Append mode indicator.
encoded.Append(modeIndicator)
// Append character count.
encoded.AppendUint32(uint32(len(data)), charCountBits)
// Append data.
switch dataMode {
case dataModeNumeric:
for i := 0; i < len(data); i += 3 {
charsRemaining := len(data) - i
var value uint32
bitsUsed := 1
for j := 0; j < charsRemaining && j < 3; j++ {
value *= 10
value += uint32(data[i+j] - 0x30)
bitsUsed += 3
}
encoded.AppendUint32(value, bitsUsed)
}
case dataModeAlphanumeric:
for i := 0; i < len(data); i += 2 {
charsRemaining := len(data) - i
var value uint32
for j := 0; j < charsRemaining && j < 2; j++ {
value *= 45
value += encodeAlphanumericCharacter(data[i+j])
}
bitsUsed := 6
if charsRemaining > 1 {
bitsUsed = 11
}
encoded.AppendUint32(value, bitsUsed)
}
case dataModeByte:
for _, b := range data {
encoded.AppendByte(b, 8)
}
}
} | go | func (d *dataEncoder) encodeDataRaw(data []byte, dataMode dataMode, encoded *bitset.Bitset) {
modeIndicator := d.modeIndicator(dataMode)
charCountBits := d.charCountBits(dataMode)
// Append mode indicator.
encoded.Append(modeIndicator)
// Append character count.
encoded.AppendUint32(uint32(len(data)), charCountBits)
// Append data.
switch dataMode {
case dataModeNumeric:
for i := 0; i < len(data); i += 3 {
charsRemaining := len(data) - i
var value uint32
bitsUsed := 1
for j := 0; j < charsRemaining && j < 3; j++ {
value *= 10
value += uint32(data[i+j] - 0x30)
bitsUsed += 3
}
encoded.AppendUint32(value, bitsUsed)
}
case dataModeAlphanumeric:
for i := 0; i < len(data); i += 2 {
charsRemaining := len(data) - i
var value uint32
for j := 0; j < charsRemaining && j < 2; j++ {
value *= 45
value += encodeAlphanumericCharacter(data[i+j])
}
bitsUsed := 6
if charsRemaining > 1 {
bitsUsed = 11
}
encoded.AppendUint32(value, bitsUsed)
}
case dataModeByte:
for _, b := range data {
encoded.AppendByte(b, 8)
}
}
} | [
"func",
"(",
"d",
"*",
"dataEncoder",
")",
"encodeDataRaw",
"(",
"data",
"[",
"]",
"byte",
",",
"dataMode",
"dataMode",
",",
"encoded",
"*",
"bitset",
".",
"Bitset",
")",
"{",
"modeIndicator",
":=",
"d",
".",
"modeIndicator",
"(",
"dataMode",
")",
"\n",
... | // encodeDataRaw encodes data in dataMode. The encoded data is appended to
// encoded. | [
"encodeDataRaw",
"encodes",
"data",
"in",
"dataMode",
".",
"The",
"encoded",
"data",
"is",
"appended",
"to",
"encoded",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/encoder.go#L291-L339 | train |
skip2/go-qrcode | encoder.go | modeIndicator | func (d *dataEncoder) modeIndicator(dataMode dataMode) *bitset.Bitset {
switch dataMode {
case dataModeNumeric:
return d.numericModeIndicator
case dataModeAlphanumeric:
return d.alphanumericModeIndicator
case dataModeByte:
return d.byteModeIndicator
default:
log.Panic("Unknown data mode")
}
return nil
} | go | func (d *dataEncoder) modeIndicator(dataMode dataMode) *bitset.Bitset {
switch dataMode {
case dataModeNumeric:
return d.numericModeIndicator
case dataModeAlphanumeric:
return d.alphanumericModeIndicator
case dataModeByte:
return d.byteModeIndicator
default:
log.Panic("Unknown data mode")
}
return nil
} | [
"func",
"(",
"d",
"*",
"dataEncoder",
")",
"modeIndicator",
"(",
"dataMode",
"dataMode",
")",
"*",
"bitset",
".",
"Bitset",
"{",
"switch",
"dataMode",
"{",
"case",
"dataModeNumeric",
":",
"return",
"d",
".",
"numericModeIndicator",
"\n",
"case",
"dataModeAlpha... | // modeIndicator returns the segment header bits for a segment of type dataMode. | [
"modeIndicator",
"returns",
"the",
"segment",
"header",
"bits",
"for",
"a",
"segment",
"of",
"type",
"dataMode",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/encoder.go#L342-L355 | train |
skip2/go-qrcode | encoder.go | charCountBits | func (d *dataEncoder) charCountBits(dataMode dataMode) int {
switch dataMode {
case dataModeNumeric:
return d.numNumericCharCountBits
case dataModeAlphanumeric:
return d.numAlphanumericCharCountBits
case dataModeByte:
return d.numByteCharCountBits
default:
log.Panic("Unknown data mode")
}
return 0
} | go | func (d *dataEncoder) charCountBits(dataMode dataMode) int {
switch dataMode {
case dataModeNumeric:
return d.numNumericCharCountBits
case dataModeAlphanumeric:
return d.numAlphanumericCharCountBits
case dataModeByte:
return d.numByteCharCountBits
default:
log.Panic("Unknown data mode")
}
return 0
} | [
"func",
"(",
"d",
"*",
"dataEncoder",
")",
"charCountBits",
"(",
"dataMode",
"dataMode",
")",
"int",
"{",
"switch",
"dataMode",
"{",
"case",
"dataModeNumeric",
":",
"return",
"d",
".",
"numNumericCharCountBits",
"\n",
"case",
"dataModeAlphanumeric",
":",
"return... | // charCountBits returns the number of bits used to encode the length of a data
// segment of type dataMode. | [
"charCountBits",
"returns",
"the",
"number",
"of",
"bits",
"used",
"to",
"encode",
"the",
"length",
"of",
"a",
"data",
"segment",
"of",
"type",
"dataMode",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/encoder.go#L359-L372 | train |
skip2/go-qrcode | version.go | formatInfo | func (v qrCodeVersion) formatInfo(maskPattern int) *bitset.Bitset {
formatID := 0
switch v.level {
case Low:
formatID = 0x08 // 0b01000
case Medium:
formatID = 0x00 // 0b00000
case High:
formatID = 0x18 // 0b11000
case Highest:
formatID = 0x10 // 0b10000
default:
log.Panicf("Invalid level %d", v.level)
}
if maskPattern < 0 || maskPattern > 7 {
log.Panicf("Invalid maskPattern %d", maskPattern)
}
formatID |= maskPattern & 0x7
result := bitset.New()
result.AppendUint32(formatBitSequence[formatID].regular, formatInfoLengthBits)
return result
} | go | func (v qrCodeVersion) formatInfo(maskPattern int) *bitset.Bitset {
formatID := 0
switch v.level {
case Low:
formatID = 0x08 // 0b01000
case Medium:
formatID = 0x00 // 0b00000
case High:
formatID = 0x18 // 0b11000
case Highest:
formatID = 0x10 // 0b10000
default:
log.Panicf("Invalid level %d", v.level)
}
if maskPattern < 0 || maskPattern > 7 {
log.Panicf("Invalid maskPattern %d", maskPattern)
}
formatID |= maskPattern & 0x7
result := bitset.New()
result.AppendUint32(formatBitSequence[formatID].regular, formatInfoLengthBits)
return result
} | [
"func",
"(",
"v",
"qrCodeVersion",
")",
"formatInfo",
"(",
"maskPattern",
"int",
")",
"*",
"bitset",
".",
"Bitset",
"{",
"formatID",
":=",
"0",
"\n",
"switch",
"v",
".",
"level",
"{",
"case",
"Low",
":",
"formatID",
"=",
"0x08",
"\n",
"case",
"Medium",... | // formatInfo returns the 15-bit Format Information value for a QR
// code. | [
"formatInfo",
"returns",
"the",
"15",
"-",
"bit",
"Format",
"Information",
"value",
"for",
"a",
"QR",
"code",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/version.go#L2905-L2932 | train |
skip2/go-qrcode | version.go | versionInfo | func (v qrCodeVersion) versionInfo() *bitset.Bitset {
if v.version < 7 {
return nil
}
result := bitset.New()
result.AppendUint32(versionBitSequence[v.version], 18)
return result
} | go | func (v qrCodeVersion) versionInfo() *bitset.Bitset {
if v.version < 7 {
return nil
}
result := bitset.New()
result.AppendUint32(versionBitSequence[v.version], 18)
return result
} | [
"func",
"(",
"v",
"qrCodeVersion",
")",
"versionInfo",
"(",
")",
"*",
"bitset",
".",
"Bitset",
"{",
"if",
"v",
".",
"version",
"<",
"7",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"result",
":=",
"bitset",
".",
"New",
"(",
")",
"\n",
"result",
".",
"... | // versionInfo returns the 18-bit Version Information value for a QR Code.
//
// Version Information is applicable only to QR Codes versions 7-40 inclusive.
// nil is returned if Version Information is not required. | [
"versionInfo",
"returns",
"the",
"18",
"-",
"bit",
"Version",
"Information",
"value",
"for",
"a",
"QR",
"Code",
".",
"Version",
"Information",
"is",
"applicable",
"only",
"to",
"QR",
"Codes",
"versions",
"7",
"-",
"40",
"inclusive",
".",
"nil",
"is",
"retu... | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/version.go#L2938-L2947 | train |
skip2/go-qrcode | version.go | numDataBits | func (v qrCodeVersion) numDataBits() int {
numDataBits := 0
for _, b := range v.block {
numDataBits += 8 * b.numBlocks * b.numDataCodewords // 8 bits in a byte
}
return numDataBits
} | go | func (v qrCodeVersion) numDataBits() int {
numDataBits := 0
for _, b := range v.block {
numDataBits += 8 * b.numBlocks * b.numDataCodewords // 8 bits in a byte
}
return numDataBits
} | [
"func",
"(",
"v",
"qrCodeVersion",
")",
"numDataBits",
"(",
")",
"int",
"{",
"numDataBits",
":=",
"0",
"\n",
"for",
"_",
",",
"b",
":=",
"range",
"v",
".",
"block",
"{",
"numDataBits",
"+=",
"8",
"*",
"b",
".",
"numBlocks",
"*",
"b",
".",
"numDataC... | // numDataBits returns the data capacity in bits. | [
"numDataBits",
"returns",
"the",
"data",
"capacity",
"in",
"bits",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/version.go#L2950-L2957 | train |
skip2/go-qrcode | version.go | chooseQRCodeVersion | func chooseQRCodeVersion(level RecoveryLevel, encoder *dataEncoder, numDataBits int) *qrCodeVersion {
var chosenVersion *qrCodeVersion
for _, v := range versions {
if v.level != level {
continue
} else if v.version < encoder.minVersion {
continue
} else if v.version > encoder.maxVersion {
break
}
numFreeBits := v.numDataBits() - numDataBits
if numFreeBits >= 0 {
chosenVersion = &v
break
}
}
return chosenVersion
} | go | func chooseQRCodeVersion(level RecoveryLevel, encoder *dataEncoder, numDataBits int) *qrCodeVersion {
var chosenVersion *qrCodeVersion
for _, v := range versions {
if v.level != level {
continue
} else if v.version < encoder.minVersion {
continue
} else if v.version > encoder.maxVersion {
break
}
numFreeBits := v.numDataBits() - numDataBits
if numFreeBits >= 0 {
chosenVersion = &v
break
}
}
return chosenVersion
} | [
"func",
"chooseQRCodeVersion",
"(",
"level",
"RecoveryLevel",
",",
"encoder",
"*",
"dataEncoder",
",",
"numDataBits",
"int",
")",
"*",
"qrCodeVersion",
"{",
"var",
"chosenVersion",
"*",
"qrCodeVersion",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"versions",
"{... | // chooseQRCodeVersion chooses the most suitable QR Code version for a stated
// data length in bits, the error recovery level required, and the data encoder
// used.
//
// The chosen QR Code version is the smallest version able to fit numDataBits
// and the optional terminator bits required by the specified encoder.
//
// On success the chosen QR Code version is returned. | [
"chooseQRCodeVersion",
"chooses",
"the",
"most",
"suitable",
"QR",
"Code",
"version",
"for",
"a",
"stated",
"data",
"length",
"in",
"bits",
"the",
"error",
"recovery",
"level",
"required",
"and",
"the",
"data",
"encoder",
"used",
".",
"The",
"chosen",
"QR",
... | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/version.go#L2967-L2988 | train |
skip2/go-qrcode | version.go | numBlocks | func (v qrCodeVersion) numBlocks() int {
numBlocks := 0
for _, b := range v.block {
numBlocks += b.numBlocks
}
return numBlocks
} | go | func (v qrCodeVersion) numBlocks() int {
numBlocks := 0
for _, b := range v.block {
numBlocks += b.numBlocks
}
return numBlocks
} | [
"func",
"(",
"v",
"qrCodeVersion",
")",
"numBlocks",
"(",
")",
"int",
"{",
"numBlocks",
":=",
"0",
"\n",
"for",
"_",
",",
"b",
":=",
"range",
"v",
".",
"block",
"{",
"numBlocks",
"+=",
"b",
".",
"numBlocks",
"\n",
"}",
"\n",
"return",
"numBlocks",
... | // numBlocks returns the number of blocks. | [
"numBlocks",
"returns",
"the",
"number",
"of",
"blocks",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/version.go#L3006-L3014 | train |
skip2/go-qrcode | version.go | numBitsToPadToCodeword | func (v qrCodeVersion) numBitsToPadToCodeword(numDataBits int) int {
if numDataBits == v.numDataBits() {
return 0
}
return (8 - numDataBits%8) % 8
} | go | func (v qrCodeVersion) numBitsToPadToCodeword(numDataBits int) int {
if numDataBits == v.numDataBits() {
return 0
}
return (8 - numDataBits%8) % 8
} | [
"func",
"(",
"v",
"qrCodeVersion",
")",
"numBitsToPadToCodeword",
"(",
"numDataBits",
"int",
")",
"int",
"{",
"if",
"numDataBits",
"==",
"v",
".",
"numDataBits",
"(",
")",
"{",
"return",
"0",
"\n",
"}",
"\n",
"return",
"(",
"8",
"-",
"numDataBits",
"%",
... | // numBitsToPadToCodeword returns the number of bits required to pad data of
// length numDataBits upto the nearest codeword size. | [
"numBitsToPadToCodeword",
"returns",
"the",
"number",
"of",
"bits",
"required",
"to",
"pad",
"data",
"of",
"length",
"numDataBits",
"upto",
"the",
"nearest",
"codeword",
"size",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/version.go#L3018-L3024 | train |
skip2/go-qrcode | version.go | getQRCodeVersion | func getQRCodeVersion(level RecoveryLevel, version int) *qrCodeVersion {
for _, v := range versions {
if v.level == level && v.version == version {
return &v
}
}
return nil
} | go | func getQRCodeVersion(level RecoveryLevel, version int) *qrCodeVersion {
for _, v := range versions {
if v.level == level && v.version == version {
return &v
}
}
return nil
} | [
"func",
"getQRCodeVersion",
"(",
"level",
"RecoveryLevel",
",",
"version",
"int",
")",
"*",
"qrCodeVersion",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"versions",
"{",
"if",
"v",
".",
"level",
"==",
"level",
"&&",
"v",
".",
"version",
"==",
"version",
... | // getQRCodeVersion returns the QR Code version by version number and recovery
// level. Returns nil if the requested combination is not defined. | [
"getQRCodeVersion",
"returns",
"the",
"QR",
"Code",
"version",
"by",
"version",
"number",
"and",
"recovery",
"level",
".",
"Returns",
"nil",
"if",
"the",
"requested",
"combination",
"is",
"not",
"defined",
"."
] | dc11ecdae0a9889dc81a343585516404e8dc6ead | https://github.com/skip2/go-qrcode/blob/dc11ecdae0a9889dc81a343585516404e8dc6ead/version.go#L3042-L3050 | train |
tidwall/buntdb | buntdb.go | Open | func Open(path string) (*DB, error) {
db := &DB{}
// initialize trees and indexes
db.keys = btree.New(btreeDegrees, nil)
db.exps = btree.New(btreeDegrees, &exctx{db})
db.idxs = make(map[string]*index)
// initialize default configuration
db.config = Config{
SyncPolicy: EverySecond,
AutoShrinkPercentage: 100,
AutoShrinkMinSize: 32 * 1024 * 1024,
}
// turn off persistence for pure in-memory
db.persist = path != ":memory:"
if db.persist {
var err error
// hardcoding 0666 as the default mode.
db.file, err = os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0666)
if err != nil {
return nil, err
}
// load the database from disk
if err := db.load(); err != nil {
// close on error, ignore close error
_ = db.file.Close()
return nil, err
}
}
// start the background manager.
go db.backgroundManager()
return db, nil
} | go | func Open(path string) (*DB, error) {
db := &DB{}
// initialize trees and indexes
db.keys = btree.New(btreeDegrees, nil)
db.exps = btree.New(btreeDegrees, &exctx{db})
db.idxs = make(map[string]*index)
// initialize default configuration
db.config = Config{
SyncPolicy: EverySecond,
AutoShrinkPercentage: 100,
AutoShrinkMinSize: 32 * 1024 * 1024,
}
// turn off persistence for pure in-memory
db.persist = path != ":memory:"
if db.persist {
var err error
// hardcoding 0666 as the default mode.
db.file, err = os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0666)
if err != nil {
return nil, err
}
// load the database from disk
if err := db.load(); err != nil {
// close on error, ignore close error
_ = db.file.Close()
return nil, err
}
}
// start the background manager.
go db.backgroundManager()
return db, nil
} | [
"func",
"Open",
"(",
"path",
"string",
")",
"(",
"*",
"DB",
",",
"error",
")",
"{",
"db",
":=",
"&",
"DB",
"{",
"}",
"\n",
"db",
".",
"keys",
"=",
"btree",
".",
"New",
"(",
"btreeDegrees",
",",
"nil",
")",
"\n",
"db",
".",
"exps",
"=",
"btree... | // Open opens a database at the provided path.
// If the file does not exist then it will be created automatically. | [
"Open",
"opens",
"a",
"database",
"at",
"the",
"provided",
"path",
".",
"If",
"the",
"file",
"does",
"not",
"exist",
"then",
"it",
"will",
"be",
"created",
"automatically",
"."
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L142-L173 | train |
tidwall/buntdb | buntdb.go | match | func (idx *index) match(key string) bool {
if idx.pattern == "*" {
return true
}
if idx.opts.CaseInsensitiveKeyMatching {
for i := 0; i < len(key); i++ {
if key[i] >= 'A' && key[i] <= 'Z' {
key = strings.ToLower(key)
break
}
}
}
return match.Match(key, idx.pattern)
} | go | func (idx *index) match(key string) bool {
if idx.pattern == "*" {
return true
}
if idx.opts.CaseInsensitiveKeyMatching {
for i := 0; i < len(key); i++ {
if key[i] >= 'A' && key[i] <= 'Z' {
key = strings.ToLower(key)
break
}
}
}
return match.Match(key, idx.pattern)
} | [
"func",
"(",
"idx",
"*",
"index",
")",
"match",
"(",
"key",
"string",
")",
"bool",
"{",
"if",
"idx",
".",
"pattern",
"==",
"\"*\"",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"idx",
".",
"opts",
".",
"CaseInsensitiveKeyMatching",
"{",
"for",
"i",
... | // match matches the pattern to the key | [
"match",
"matches",
"the",
"pattern",
"to",
"the",
"key"
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L260-L273 | train |
tidwall/buntdb | buntdb.go | clearCopy | func (idx *index) clearCopy() *index {
// copy the index meta information
nidx := &index{
name: idx.name,
pattern: idx.pattern,
db: idx.db,
less: idx.less,
rect: idx.rect,
opts: idx.opts,
}
// initialize with empty trees
if nidx.less != nil {
nidx.btr = btree.New(btreeDegrees, nidx)
}
if nidx.rect != nil {
nidx.rtr = rtree.New(nidx)
}
return nidx
} | go | func (idx *index) clearCopy() *index {
// copy the index meta information
nidx := &index{
name: idx.name,
pattern: idx.pattern,
db: idx.db,
less: idx.less,
rect: idx.rect,
opts: idx.opts,
}
// initialize with empty trees
if nidx.less != nil {
nidx.btr = btree.New(btreeDegrees, nidx)
}
if nidx.rect != nil {
nidx.rtr = rtree.New(nidx)
}
return nidx
} | [
"func",
"(",
"idx",
"*",
"index",
")",
"clearCopy",
"(",
")",
"*",
"index",
"{",
"nidx",
":=",
"&",
"index",
"{",
"name",
":",
"idx",
".",
"name",
",",
"pattern",
":",
"idx",
".",
"pattern",
",",
"db",
":",
"idx",
".",
"db",
",",
"less",
":",
... | // clearCopy creates a copy of the index, but with an empty dataset. | [
"clearCopy",
"creates",
"a",
"copy",
"of",
"the",
"index",
"but",
"with",
"an",
"empty",
"dataset",
"."
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L276-L294 | train |
tidwall/buntdb | buntdb.go | rebuild | func (idx *index) rebuild() {
// initialize trees
if idx.less != nil {
idx.btr = btree.New(btreeDegrees, idx)
}
if idx.rect != nil {
idx.rtr = rtree.New(idx)
}
// iterate through all keys and fill the index
idx.db.keys.Ascend(func(item btree.Item) bool {
dbi := item.(*dbItem)
if !idx.match(dbi.key) {
// does not match the pattern, conintue
return true
}
if idx.less != nil {
idx.btr.ReplaceOrInsert(dbi)
}
if idx.rect != nil {
idx.rtr.Insert(dbi)
}
return true
})
} | go | func (idx *index) rebuild() {
// initialize trees
if idx.less != nil {
idx.btr = btree.New(btreeDegrees, idx)
}
if idx.rect != nil {
idx.rtr = rtree.New(idx)
}
// iterate through all keys and fill the index
idx.db.keys.Ascend(func(item btree.Item) bool {
dbi := item.(*dbItem)
if !idx.match(dbi.key) {
// does not match the pattern, conintue
return true
}
if idx.less != nil {
idx.btr.ReplaceOrInsert(dbi)
}
if idx.rect != nil {
idx.rtr.Insert(dbi)
}
return true
})
} | [
"func",
"(",
"idx",
"*",
"index",
")",
"rebuild",
"(",
")",
"{",
"if",
"idx",
".",
"less",
"!=",
"nil",
"{",
"idx",
".",
"btr",
"=",
"btree",
".",
"New",
"(",
"btreeDegrees",
",",
"idx",
")",
"\n",
"}",
"\n",
"if",
"idx",
".",
"rect",
"!=",
"... | // rebuild rebuilds the index | [
"rebuild",
"rebuilds",
"the",
"index"
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L297-L320 | train |
tidwall/buntdb | buntdb.go | ReadConfig | func (db *DB) ReadConfig(config *Config) error {
db.mu.RLock()
defer db.mu.RUnlock()
if db.closed {
return ErrDatabaseClosed
}
*config = db.config
return nil
} | go | func (db *DB) ReadConfig(config *Config) error {
db.mu.RLock()
defer db.mu.RUnlock()
if db.closed {
return ErrDatabaseClosed
}
*config = db.config
return nil
} | [
"func",
"(",
"db",
"*",
"DB",
")",
"ReadConfig",
"(",
"config",
"*",
"Config",
")",
"error",
"{",
"db",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"db",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"db",
".",
"closed",
"{",
"return",... | // ReadConfig returns the database configuration. | [
"ReadConfig",
"returns",
"the",
"database",
"configuration",
"."
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L440-L448 | train |
tidwall/buntdb | buntdb.go | SetConfig | func (db *DB) SetConfig(config Config) error {
db.mu.Lock()
defer db.mu.Unlock()
if db.closed {
return ErrDatabaseClosed
}
switch config.SyncPolicy {
default:
return ErrInvalidSyncPolicy
case Never, EverySecond, Always:
}
db.config = config
return nil
} | go | func (db *DB) SetConfig(config Config) error {
db.mu.Lock()
defer db.mu.Unlock()
if db.closed {
return ErrDatabaseClosed
}
switch config.SyncPolicy {
default:
return ErrInvalidSyncPolicy
case Never, EverySecond, Always:
}
db.config = config
return nil
} | [
"func",
"(",
"db",
"*",
"DB",
")",
"SetConfig",
"(",
"config",
"Config",
")",
"error",
"{",
"db",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"db",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"db",
".",
"closed",
"{",
"return",
"ErrDat... | // SetConfig updates the database configuration. | [
"SetConfig",
"updates",
"the",
"database",
"configuration",
"."
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L451-L464 | train |
tidwall/buntdb | buntdb.go | insertIntoDatabase | func (db *DB) insertIntoDatabase(item *dbItem) *dbItem {
var pdbi *dbItem
prev := db.keys.ReplaceOrInsert(item)
if prev != nil {
// A previous item was removed from the keys tree. Let's
// fully delete this item from all indexes.
pdbi = prev.(*dbItem)
if pdbi.opts != nil && pdbi.opts.ex {
// Remove it from the exipres tree.
db.exps.Delete(pdbi)
}
for _, idx := range db.idxs {
if idx.btr != nil {
// Remove it from the btree index.
idx.btr.Delete(pdbi)
}
if idx.rtr != nil {
// Remove it from the rtree index.
idx.rtr.Remove(pdbi)
}
}
}
if item.opts != nil && item.opts.ex {
// The new item has eviction options. Add it to the
// expires tree
db.exps.ReplaceOrInsert(item)
}
for _, idx := range db.idxs {
if !idx.match(item.key) {
continue
}
if idx.btr != nil {
// Add new item to btree index.
idx.btr.ReplaceOrInsert(item)
}
if idx.rtr != nil {
// Add new item to rtree index.
idx.rtr.Insert(item)
}
}
// we must return the previous item to the caller.
return pdbi
} | go | func (db *DB) insertIntoDatabase(item *dbItem) *dbItem {
var pdbi *dbItem
prev := db.keys.ReplaceOrInsert(item)
if prev != nil {
// A previous item was removed from the keys tree. Let's
// fully delete this item from all indexes.
pdbi = prev.(*dbItem)
if pdbi.opts != nil && pdbi.opts.ex {
// Remove it from the exipres tree.
db.exps.Delete(pdbi)
}
for _, idx := range db.idxs {
if idx.btr != nil {
// Remove it from the btree index.
idx.btr.Delete(pdbi)
}
if idx.rtr != nil {
// Remove it from the rtree index.
idx.rtr.Remove(pdbi)
}
}
}
if item.opts != nil && item.opts.ex {
// The new item has eviction options. Add it to the
// expires tree
db.exps.ReplaceOrInsert(item)
}
for _, idx := range db.idxs {
if !idx.match(item.key) {
continue
}
if idx.btr != nil {
// Add new item to btree index.
idx.btr.ReplaceOrInsert(item)
}
if idx.rtr != nil {
// Add new item to rtree index.
idx.rtr.Insert(item)
}
}
// we must return the previous item to the caller.
return pdbi
} | [
"func",
"(",
"db",
"*",
"DB",
")",
"insertIntoDatabase",
"(",
"item",
"*",
"dbItem",
")",
"*",
"dbItem",
"{",
"var",
"pdbi",
"*",
"dbItem",
"\n",
"prev",
":=",
"db",
".",
"keys",
".",
"ReplaceOrInsert",
"(",
"item",
")",
"\n",
"if",
"prev",
"!=",
"... | // insertIntoDatabase performs inserts an item in to the database and updates
// all indexes. If a previous item with the same key already exists, that item
// will be replaced with the new one, and return the previous item. | [
"insertIntoDatabase",
"performs",
"inserts",
"an",
"item",
"in",
"to",
"the",
"database",
"and",
"updates",
"all",
"indexes",
".",
"If",
"a",
"previous",
"item",
"with",
"the",
"same",
"key",
"already",
"exists",
"that",
"item",
"will",
"be",
"replaced",
"wi... | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L469-L511 | train |
tidwall/buntdb | buntdb.go | managed | func (db *DB) managed(writable bool, fn func(tx *Tx) error) (err error) {
var tx *Tx
tx, err = db.Begin(writable)
if err != nil {
return
}
defer func() {
if err != nil {
// The caller returned an error. We must rollback.
_ = tx.Rollback()
return
}
if writable {
// Everything went well. Lets Commit()
err = tx.Commit()
} else {
// read-only transaction can only roll back.
err = tx.Rollback()
}
}()
tx.funcd = true
defer func() {
tx.funcd = false
}()
err = fn(tx)
return
} | go | func (db *DB) managed(writable bool, fn func(tx *Tx) error) (err error) {
var tx *Tx
tx, err = db.Begin(writable)
if err != nil {
return
}
defer func() {
if err != nil {
// The caller returned an error. We must rollback.
_ = tx.Rollback()
return
}
if writable {
// Everything went well. Lets Commit()
err = tx.Commit()
} else {
// read-only transaction can only roll back.
err = tx.Rollback()
}
}()
tx.funcd = true
defer func() {
tx.funcd = false
}()
err = fn(tx)
return
} | [
"func",
"(",
"db",
"*",
"DB",
")",
"managed",
"(",
"writable",
"bool",
",",
"fn",
"func",
"(",
"tx",
"*",
"Tx",
")",
"error",
")",
"(",
"err",
"error",
")",
"{",
"var",
"tx",
"*",
"Tx",
"\n",
"tx",
",",
"err",
"=",
"db",
".",
"Begin",
"(",
... | // managed calls a block of code that is fully contained in a transaction.
// This method is intended to be wrapped by Update and View | [
"managed",
"calls",
"a",
"block",
"of",
"code",
"that",
"is",
"fully",
"contained",
"in",
"a",
"transaction",
".",
"This",
"method",
"is",
"intended",
"to",
"be",
"wrapped",
"by",
"Update",
"and",
"View"
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L937-L963 | train |
tidwall/buntdb | buntdb.go | get | func (db *DB) get(key string) *dbItem {
item := db.keys.Get(&dbItem{key: key})
if item != nil {
return item.(*dbItem)
}
return nil
} | go | func (db *DB) get(key string) *dbItem {
item := db.keys.Get(&dbItem{key: key})
if item != nil {
return item.(*dbItem)
}
return nil
} | [
"func",
"(",
"db",
"*",
"DB",
")",
"get",
"(",
"key",
"string",
")",
"*",
"dbItem",
"{",
"item",
":=",
"db",
".",
"keys",
".",
"Get",
"(",
"&",
"dbItem",
"{",
"key",
":",
"key",
"}",
")",
"\n",
"if",
"item",
"!=",
"nil",
"{",
"return",
"item"... | // get return an item or nil if not found. | [
"get",
"return",
"an",
"item",
"or",
"nil",
"if",
"not",
"found",
"."
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L988-L994 | train |
tidwall/buntdb | buntdb.go | DeleteAll | func (tx *Tx) DeleteAll() error {
if tx.db == nil {
return ErrTxClosed
} else if !tx.writable {
return ErrTxNotWritable
} else if tx.wc.itercount > 0 {
return ErrTxIterating
}
// check to see if we've already deleted everything
if tx.wc.rbkeys == nil {
// we need to backup the live data in case of a rollback.
tx.wc.rbkeys = tx.db.keys
tx.wc.rbexps = tx.db.exps
tx.wc.rbidxs = tx.db.idxs
}
// now reset the live database trees
tx.db.keys = btree.New(btreeDegrees, nil)
tx.db.exps = btree.New(btreeDegrees, &exctx{tx.db})
tx.db.idxs = make(map[string]*index)
// finally re-create the indexes
for name, idx := range tx.wc.rbidxs {
tx.db.idxs[name] = idx.clearCopy()
}
// always clear out the commits
tx.wc.commitItems = make(map[string]*dbItem)
return nil
} | go | func (tx *Tx) DeleteAll() error {
if tx.db == nil {
return ErrTxClosed
} else if !tx.writable {
return ErrTxNotWritable
} else if tx.wc.itercount > 0 {
return ErrTxIterating
}
// check to see if we've already deleted everything
if tx.wc.rbkeys == nil {
// we need to backup the live data in case of a rollback.
tx.wc.rbkeys = tx.db.keys
tx.wc.rbexps = tx.db.exps
tx.wc.rbidxs = tx.db.idxs
}
// now reset the live database trees
tx.db.keys = btree.New(btreeDegrees, nil)
tx.db.exps = btree.New(btreeDegrees, &exctx{tx.db})
tx.db.idxs = make(map[string]*index)
// finally re-create the indexes
for name, idx := range tx.wc.rbidxs {
tx.db.idxs[name] = idx.clearCopy()
}
// always clear out the commits
tx.wc.commitItems = make(map[string]*dbItem)
return nil
} | [
"func",
"(",
"tx",
"*",
"Tx",
")",
"DeleteAll",
"(",
")",
"error",
"{",
"if",
"tx",
".",
"db",
"==",
"nil",
"{",
"return",
"ErrTxClosed",
"\n",
"}",
"else",
"if",
"!",
"tx",
".",
"writable",
"{",
"return",
"ErrTxNotWritable",
"\n",
"}",
"else",
"if... | // DeleteAll deletes all items from the database. | [
"DeleteAll",
"deletes",
"all",
"items",
"from",
"the",
"database",
"."
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L1022-L1053 | train |
tidwall/buntdb | buntdb.go | lock | func (tx *Tx) lock() {
if tx.writable {
tx.db.mu.Lock()
} else {
tx.db.mu.RLock()
}
} | go | func (tx *Tx) lock() {
if tx.writable {
tx.db.mu.Lock()
} else {
tx.db.mu.RLock()
}
} | [
"func",
"(",
"tx",
"*",
"Tx",
")",
"lock",
"(",
")",
"{",
"if",
"tx",
".",
"writable",
"{",
"tx",
".",
"db",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"}",
"else",
"{",
"tx",
".",
"db",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"}",
"\n",
... | // lock locks the database based on the transaction type. | [
"lock",
"locks",
"the",
"database",
"based",
"on",
"the",
"transaction",
"type",
"."
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L1086-L1092 | train |
tidwall/buntdb | buntdb.go | unlock | func (tx *Tx) unlock() {
if tx.writable {
tx.db.mu.Unlock()
} else {
tx.db.mu.RUnlock()
}
} | go | func (tx *Tx) unlock() {
if tx.writable {
tx.db.mu.Unlock()
} else {
tx.db.mu.RUnlock()
}
} | [
"func",
"(",
"tx",
"*",
"Tx",
")",
"unlock",
"(",
")",
"{",
"if",
"tx",
".",
"writable",
"{",
"tx",
".",
"db",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}",
"else",
"{",
"tx",
".",
"db",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"}",
"\... | // unlock unlocks the database based on the transaction type. | [
"unlock",
"unlocks",
"the",
"database",
"based",
"on",
"the",
"transaction",
"type",
"."
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L1095-L1101 | train |
tidwall/buntdb | buntdb.go | writeSetTo | func (dbi *dbItem) writeSetTo(buf []byte) []byte {
if dbi.opts != nil && dbi.opts.ex {
ex := dbi.opts.exat.Sub(time.Now()) / time.Second
buf = appendArray(buf, 5)
buf = appendBulkString(buf, "set")
buf = appendBulkString(buf, dbi.key)
buf = appendBulkString(buf, dbi.val)
buf = appendBulkString(buf, "ex")
buf = appendBulkString(buf, strconv.FormatUint(uint64(ex), 10))
} else {
buf = appendArray(buf, 3)
buf = appendBulkString(buf, "set")
buf = appendBulkString(buf, dbi.key)
buf = appendBulkString(buf, dbi.val)
}
return buf
} | go | func (dbi *dbItem) writeSetTo(buf []byte) []byte {
if dbi.opts != nil && dbi.opts.ex {
ex := dbi.opts.exat.Sub(time.Now()) / time.Second
buf = appendArray(buf, 5)
buf = appendBulkString(buf, "set")
buf = appendBulkString(buf, dbi.key)
buf = appendBulkString(buf, dbi.val)
buf = appendBulkString(buf, "ex")
buf = appendBulkString(buf, strconv.FormatUint(uint64(ex), 10))
} else {
buf = appendArray(buf, 3)
buf = appendBulkString(buf, "set")
buf = appendBulkString(buf, dbi.key)
buf = appendBulkString(buf, dbi.val)
}
return buf
} | [
"func",
"(",
"dbi",
"*",
"dbItem",
")",
"writeSetTo",
"(",
"buf",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"if",
"dbi",
".",
"opts",
"!=",
"nil",
"&&",
"dbi",
".",
"opts",
".",
"ex",
"{",
"ex",
":=",
"dbi",
".",
"opts",
".",
"exat",
".",... | // writeSetTo writes an item as a single SET record to the a bufio Writer. | [
"writeSetTo",
"writes",
"an",
"item",
"as",
"a",
"single",
"SET",
"record",
"to",
"the",
"a",
"bufio",
"Writer",
"."
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L1228-L1244 | train |
tidwall/buntdb | buntdb.go | writeDeleteTo | func (dbi *dbItem) writeDeleteTo(buf []byte) []byte {
buf = appendArray(buf, 2)
buf = appendBulkString(buf, "del")
buf = appendBulkString(buf, dbi.key)
return buf
} | go | func (dbi *dbItem) writeDeleteTo(buf []byte) []byte {
buf = appendArray(buf, 2)
buf = appendBulkString(buf, "del")
buf = appendBulkString(buf, dbi.key)
return buf
} | [
"func",
"(",
"dbi",
"*",
"dbItem",
")",
"writeDeleteTo",
"(",
"buf",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"buf",
"=",
"appendArray",
"(",
"buf",
",",
"2",
")",
"\n",
"buf",
"=",
"appendBulkString",
"(",
"buf",
",",
"\"del\"",
")",
"\n",
... | // writeSetTo writes an item as a single DEL record to the a bufio Writer. | [
"writeSetTo",
"writes",
"an",
"item",
"as",
"a",
"single",
"DEL",
"record",
"to",
"the",
"a",
"bufio",
"Writer",
"."
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L1247-L1252 | train |
tidwall/buntdb | buntdb.go | expired | func (dbi *dbItem) expired() bool {
return dbi.opts != nil && dbi.opts.ex && time.Now().After(dbi.opts.exat)
} | go | func (dbi *dbItem) expired() bool {
return dbi.opts != nil && dbi.opts.ex && time.Now().After(dbi.opts.exat)
} | [
"func",
"(",
"dbi",
"*",
"dbItem",
")",
"expired",
"(",
")",
"bool",
"{",
"return",
"dbi",
".",
"opts",
"!=",
"nil",
"&&",
"dbi",
".",
"opts",
".",
"ex",
"&&",
"time",
".",
"Now",
"(",
")",
".",
"After",
"(",
"dbi",
".",
"opts",
".",
"exat",
... | // expired evaluates id the item has expired. This will always return false when
// the item does not have `opts.ex` set to true. | [
"expired",
"evaluates",
"id",
"the",
"item",
"has",
"expired",
".",
"This",
"will",
"always",
"return",
"false",
"when",
"the",
"item",
"does",
"not",
"have",
"opts",
".",
"ex",
"set",
"to",
"true",
"."
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L1256-L1258 | train |
tidwall/buntdb | buntdb.go | expiresAt | func (dbi *dbItem) expiresAt() time.Time {
if dbi.opts == nil || !dbi.opts.ex {
return maxTime
}
return dbi.opts.exat
} | go | func (dbi *dbItem) expiresAt() time.Time {
if dbi.opts == nil || !dbi.opts.ex {
return maxTime
}
return dbi.opts.exat
} | [
"func",
"(",
"dbi",
"*",
"dbItem",
")",
"expiresAt",
"(",
")",
"time",
".",
"Time",
"{",
"if",
"dbi",
".",
"opts",
"==",
"nil",
"||",
"!",
"dbi",
".",
"opts",
".",
"ex",
"{",
"return",
"maxTime",
"\n",
"}",
"\n",
"return",
"dbi",
".",
"opts",
"... | // expiresAt will return the time when the item will expire. When an item does
// not expire `maxTime` is used. | [
"expiresAt",
"will",
"return",
"the",
"time",
"when",
"the",
"item",
"will",
"expire",
".",
"When",
"an",
"item",
"does",
"not",
"expire",
"maxTime",
"is",
"used",
"."
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L1267-L1272 | train |
tidwall/buntdb | buntdb.go | Less | func (dbi *dbItem) Less(item btree.Item, ctx interface{}) bool {
dbi2 := item.(*dbItem)
switch ctx := ctx.(type) {
case *exctx:
// The expires b-tree formula
if dbi2.expiresAt().After(dbi.expiresAt()) {
return true
}
if dbi.expiresAt().After(dbi2.expiresAt()) {
return false
}
case *index:
if ctx.less != nil {
// Using an index
if ctx.less(dbi.val, dbi2.val) {
return true
}
if ctx.less(dbi2.val, dbi.val) {
return false
}
}
}
// Always fall back to the key comparison. This creates absolute uniqueness.
if dbi.keyless {
return false
} else if dbi2.keyless {
return true
}
return dbi.key < dbi2.key
} | go | func (dbi *dbItem) Less(item btree.Item, ctx interface{}) bool {
dbi2 := item.(*dbItem)
switch ctx := ctx.(type) {
case *exctx:
// The expires b-tree formula
if dbi2.expiresAt().After(dbi.expiresAt()) {
return true
}
if dbi.expiresAt().After(dbi2.expiresAt()) {
return false
}
case *index:
if ctx.less != nil {
// Using an index
if ctx.less(dbi.val, dbi2.val) {
return true
}
if ctx.less(dbi2.val, dbi.val) {
return false
}
}
}
// Always fall back to the key comparison. This creates absolute uniqueness.
if dbi.keyless {
return false
} else if dbi2.keyless {
return true
}
return dbi.key < dbi2.key
} | [
"func",
"(",
"dbi",
"*",
"dbItem",
")",
"Less",
"(",
"item",
"btree",
".",
"Item",
",",
"ctx",
"interface",
"{",
"}",
")",
"bool",
"{",
"dbi2",
":=",
"item",
".",
"(",
"*",
"dbItem",
")",
"\n",
"switch",
"ctx",
":=",
"ctx",
".",
"(",
"type",
")... | // Less determines if a b-tree item is less than another. This is required
// for ordering, inserting, and deleting items from a b-tree. It's important
// to note that the ctx parameter is used to help with determine which
// formula to use on an item. Each b-tree should use a different ctx when
// sharing the same item. | [
"Less",
"determines",
"if",
"a",
"b",
"-",
"tree",
"item",
"is",
"less",
"than",
"another",
".",
"This",
"is",
"required",
"for",
"ordering",
"inserting",
"and",
"deleting",
"items",
"from",
"a",
"b",
"-",
"tree",
".",
"It",
"s",
"important",
"to",
"no... | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L1279-L1308 | train |
tidwall/buntdb | buntdb.go | Rect | func (dbi *dbItem) Rect(ctx interface{}) (min, max []float64) {
switch ctx := ctx.(type) {
case *index:
return ctx.rect(dbi.val)
}
return nil, nil
} | go | func (dbi *dbItem) Rect(ctx interface{}) (min, max []float64) {
switch ctx := ctx.(type) {
case *index:
return ctx.rect(dbi.val)
}
return nil, nil
} | [
"func",
"(",
"dbi",
"*",
"dbItem",
")",
"Rect",
"(",
"ctx",
"interface",
"{",
"}",
")",
"(",
"min",
",",
"max",
"[",
"]",
"float64",
")",
"{",
"switch",
"ctx",
":=",
"ctx",
".",
"(",
"type",
")",
"{",
"case",
"*",
"index",
":",
"return",
"ctx",... | // Rect converts a string to a rectangle.
// An invalid rectangle will cause a panic. | [
"Rect",
"converts",
"a",
"string",
"to",
"a",
"rectangle",
".",
"An",
"invalid",
"rectangle",
"will",
"cause",
"a",
"panic",
"."
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L1312-L1318 | train |
tidwall/buntdb | buntdb.go | GetLess | func (tx *Tx) GetLess(index string) (func(a, b string) bool, error) {
if tx.db == nil {
return nil, ErrTxClosed
}
idx, ok := tx.db.idxs[index]
if !ok || idx.less == nil {
return nil, ErrNotFound
}
return idx.less, nil
} | go | func (tx *Tx) GetLess(index string) (func(a, b string) bool, error) {
if tx.db == nil {
return nil, ErrTxClosed
}
idx, ok := tx.db.idxs[index]
if !ok || idx.less == nil {
return nil, ErrNotFound
}
return idx.less, nil
} | [
"func",
"(",
"tx",
"*",
"Tx",
")",
"GetLess",
"(",
"index",
"string",
")",
"(",
"func",
"(",
"a",
",",
"b",
"string",
")",
"bool",
",",
"error",
")",
"{",
"if",
"tx",
".",
"db",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrTxClosed",
"\n",
"}",
... | // GetLess returns the less function for an index. This is handy for
// doing ad-hoc compares inside a transaction.
// Returns ErrNotFound if the index is not found or there is no less
// function bound to the index | [
"GetLess",
"returns",
"the",
"less",
"function",
"for",
"an",
"index",
".",
"This",
"is",
"handy",
"for",
"doing",
"ad",
"-",
"hoc",
"compares",
"inside",
"a",
"transaction",
".",
"Returns",
"ErrNotFound",
"if",
"the",
"index",
"is",
"not",
"found",
"or",
... | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L1334-L1343 | train |
tidwall/buntdb | buntdb.go | GetRect | func (tx *Tx) GetRect(index string) (func(s string) (min, max []float64),
error) {
if tx.db == nil {
return nil, ErrTxClosed
}
idx, ok := tx.db.idxs[index]
if !ok || idx.rect == nil {
return nil, ErrNotFound
}
return idx.rect, nil
} | go | func (tx *Tx) GetRect(index string) (func(s string) (min, max []float64),
error) {
if tx.db == nil {
return nil, ErrTxClosed
}
idx, ok := tx.db.idxs[index]
if !ok || idx.rect == nil {
return nil, ErrNotFound
}
return idx.rect, nil
} | [
"func",
"(",
"tx",
"*",
"Tx",
")",
"GetRect",
"(",
"index",
"string",
")",
"(",
"func",
"(",
"s",
"string",
")",
"(",
"min",
",",
"max",
"[",
"]",
"float64",
")",
",",
"error",
")",
"{",
"if",
"tx",
".",
"db",
"==",
"nil",
"{",
"return",
"nil... | // GetRect returns the rect function for an index. This is handy for
// doing ad-hoc searches inside a transaction.
// Returns ErrNotFound if the index is not found or there is no rect
// function bound to the index | [
"GetRect",
"returns",
"the",
"rect",
"function",
"for",
"an",
"index",
".",
"This",
"is",
"handy",
"for",
"doing",
"ad",
"-",
"hoc",
"searches",
"inside",
"a",
"transaction",
".",
"Returns",
"ErrNotFound",
"if",
"the",
"index",
"is",
"not",
"found",
"or",
... | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L1349-L1359 | train |
tidwall/buntdb | buntdb.go | Get | func (tx *Tx) Get(key string, ignoreExpired ...bool) (val string, err error) {
if tx.db == nil {
return "", ErrTxClosed
}
var ignore bool
if len(ignoreExpired) != 0 {
ignore = ignoreExpired[0]
}
item := tx.db.get(key)
if item == nil || (item.expired() && !ignore) {
// The item does not exists or has expired. Let's assume that
// the caller is only interested in items that have not expired.
return "", ErrNotFound
}
return item.val, nil
} | go | func (tx *Tx) Get(key string, ignoreExpired ...bool) (val string, err error) {
if tx.db == nil {
return "", ErrTxClosed
}
var ignore bool
if len(ignoreExpired) != 0 {
ignore = ignoreExpired[0]
}
item := tx.db.get(key)
if item == nil || (item.expired() && !ignore) {
// The item does not exists or has expired. Let's assume that
// the caller is only interested in items that have not expired.
return "", ErrNotFound
}
return item.val, nil
} | [
"func",
"(",
"tx",
"*",
"Tx",
")",
"Get",
"(",
"key",
"string",
",",
"ignoreExpired",
"...",
"bool",
")",
"(",
"val",
"string",
",",
"err",
"error",
")",
"{",
"if",
"tx",
".",
"db",
"==",
"nil",
"{",
"return",
"\"\"",
",",
"ErrTxClosed",
"\n",
"}... | // Get returns a value for a key. If the item does not exist or if the item
// has expired then ErrNotFound is returned. If ignoreExpired is true, then
// the found value will be returned even if it is expired. | [
"Get",
"returns",
"a",
"value",
"for",
"a",
"key",
".",
"If",
"the",
"item",
"does",
"not",
"exist",
"or",
"if",
"the",
"item",
"has",
"expired",
"then",
"ErrNotFound",
"is",
"returned",
".",
"If",
"ignoreExpired",
"is",
"true",
"then",
"the",
"found",
... | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L1424-L1439 | train |
tidwall/buntdb | buntdb.go | TTL | func (tx *Tx) TTL(key string) (time.Duration, error) {
if tx.db == nil {
return 0, ErrTxClosed
}
item := tx.db.get(key)
if item == nil {
return 0, ErrNotFound
} else if item.opts == nil || !item.opts.ex {
return -1, nil
}
dur := item.opts.exat.Sub(time.Now())
if dur < 0 {
return 0, ErrNotFound
}
return dur, nil
} | go | func (tx *Tx) TTL(key string) (time.Duration, error) {
if tx.db == nil {
return 0, ErrTxClosed
}
item := tx.db.get(key)
if item == nil {
return 0, ErrNotFound
} else if item.opts == nil || !item.opts.ex {
return -1, nil
}
dur := item.opts.exat.Sub(time.Now())
if dur < 0 {
return 0, ErrNotFound
}
return dur, nil
} | [
"func",
"(",
"tx",
"*",
"Tx",
")",
"TTL",
"(",
"key",
"string",
")",
"(",
"time",
".",
"Duration",
",",
"error",
")",
"{",
"if",
"tx",
".",
"db",
"==",
"nil",
"{",
"return",
"0",
",",
"ErrTxClosed",
"\n",
"}",
"\n",
"item",
":=",
"tx",
".",
"... | // TTL returns the remaining time-to-live for an item.
// A negative duration will be returned for items that do not have an
// expiration. | [
"TTL",
"returns",
"the",
"remaining",
"time",
"-",
"to",
"-",
"live",
"for",
"an",
"item",
".",
"A",
"negative",
"duration",
"will",
"be",
"returned",
"for",
"items",
"that",
"do",
"not",
"have",
"an",
"expiration",
"."
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L1480-L1495 | train |
tidwall/buntdb | buntdb.go | scan | func (tx *Tx) scan(desc, gt, lt bool, index, start, stop string,
iterator func(key, value string) bool) error {
if tx.db == nil {
return ErrTxClosed
}
// wrap a btree specific iterator around the user-defined iterator.
iter := func(item btree.Item) bool {
dbi := item.(*dbItem)
return iterator(dbi.key, dbi.val)
}
var tr *btree.BTree
if index == "" {
// empty index means we will use the keys tree.
tr = tx.db.keys
} else {
idx := tx.db.idxs[index]
if idx == nil {
// index was not found. return error
return ErrNotFound
}
tr = idx.btr
if tr == nil {
return nil
}
}
// create some limit items
var itemA, itemB *dbItem
if gt || lt {
if index == "" {
itemA = &dbItem{key: start}
itemB = &dbItem{key: stop}
} else {
itemA = &dbItem{val: start}
itemB = &dbItem{val: stop}
if desc {
itemA.keyless = true
itemB.keyless = true
}
}
}
// execute the scan on the underlying tree.
if tx.wc != nil {
tx.wc.itercount++
defer func() {
tx.wc.itercount--
}()
}
if desc {
if gt {
if lt {
tr.DescendRange(itemA, itemB, iter)
} else {
tr.DescendGreaterThan(itemA, iter)
}
} else if lt {
tr.DescendLessOrEqual(itemA, iter)
} else {
tr.Descend(iter)
}
} else {
if gt {
if lt {
tr.AscendRange(itemA, itemB, iter)
} else {
tr.AscendGreaterOrEqual(itemA, iter)
}
} else if lt {
tr.AscendLessThan(itemA, iter)
} else {
tr.Ascend(iter)
}
}
return nil
} | go | func (tx *Tx) scan(desc, gt, lt bool, index, start, stop string,
iterator func(key, value string) bool) error {
if tx.db == nil {
return ErrTxClosed
}
// wrap a btree specific iterator around the user-defined iterator.
iter := func(item btree.Item) bool {
dbi := item.(*dbItem)
return iterator(dbi.key, dbi.val)
}
var tr *btree.BTree
if index == "" {
// empty index means we will use the keys tree.
tr = tx.db.keys
} else {
idx := tx.db.idxs[index]
if idx == nil {
// index was not found. return error
return ErrNotFound
}
tr = idx.btr
if tr == nil {
return nil
}
}
// create some limit items
var itemA, itemB *dbItem
if gt || lt {
if index == "" {
itemA = &dbItem{key: start}
itemB = &dbItem{key: stop}
} else {
itemA = &dbItem{val: start}
itemB = &dbItem{val: stop}
if desc {
itemA.keyless = true
itemB.keyless = true
}
}
}
// execute the scan on the underlying tree.
if tx.wc != nil {
tx.wc.itercount++
defer func() {
tx.wc.itercount--
}()
}
if desc {
if gt {
if lt {
tr.DescendRange(itemA, itemB, iter)
} else {
tr.DescendGreaterThan(itemA, iter)
}
} else if lt {
tr.DescendLessOrEqual(itemA, iter)
} else {
tr.Descend(iter)
}
} else {
if gt {
if lt {
tr.AscendRange(itemA, itemB, iter)
} else {
tr.AscendGreaterOrEqual(itemA, iter)
}
} else if lt {
tr.AscendLessThan(itemA, iter)
} else {
tr.Ascend(iter)
}
}
return nil
} | [
"func",
"(",
"tx",
"*",
"Tx",
")",
"scan",
"(",
"desc",
",",
"gt",
",",
"lt",
"bool",
",",
"index",
",",
"start",
",",
"stop",
"string",
",",
"iterator",
"func",
"(",
"key",
",",
"value",
"string",
")",
"bool",
")",
"error",
"{",
"if",
"tx",
".... | // scan iterates through a specified index and calls user-defined iterator
// function for each item encountered.
// The desc param indicates that the iterator should descend.
// The gt param indicates that there is a greaterThan limit.
// The lt param indicates that there is a lessThan limit.
// The index param tells the scanner to use the specified index tree. An
// empty string for the index means to scan the keys, not the values.
// The start and stop params are the greaterThan, lessThan limits. For
// descending order, these will be lessThan, greaterThan.
// An error will be returned if the tx is closed or the index is not found. | [
"scan",
"iterates",
"through",
"a",
"specified",
"index",
"and",
"calls",
"user",
"-",
"defined",
"iterator",
"function",
"for",
"each",
"item",
"encountered",
".",
"The",
"desc",
"param",
"indicates",
"that",
"the",
"iterator",
"should",
"descend",
".",
"The"... | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L1507-L1580 | train |
tidwall/buntdb | buntdb.go | AscendKeys | func (tx *Tx) AscendKeys(pattern string,
iterator func(key, value string) bool) error {
if pattern == "" {
return nil
}
if pattern[0] == '*' {
if pattern == "*" {
return tx.Ascend("", iterator)
}
return tx.Ascend("", func(key, value string) bool {
if match.Match(key, pattern) {
if !iterator(key, value) {
return false
}
}
return true
})
}
min, max := match.Allowable(pattern)
return tx.AscendGreaterOrEqual("", min, func(key, value string) bool {
if key > max {
return false
}
if match.Match(key, pattern) {
if !iterator(key, value) {
return false
}
}
return true
})
} | go | func (tx *Tx) AscendKeys(pattern string,
iterator func(key, value string) bool) error {
if pattern == "" {
return nil
}
if pattern[0] == '*' {
if pattern == "*" {
return tx.Ascend("", iterator)
}
return tx.Ascend("", func(key, value string) bool {
if match.Match(key, pattern) {
if !iterator(key, value) {
return false
}
}
return true
})
}
min, max := match.Allowable(pattern)
return tx.AscendGreaterOrEqual("", min, func(key, value string) bool {
if key > max {
return false
}
if match.Match(key, pattern) {
if !iterator(key, value) {
return false
}
}
return true
})
} | [
"func",
"(",
"tx",
"*",
"Tx",
")",
"AscendKeys",
"(",
"pattern",
"string",
",",
"iterator",
"func",
"(",
"key",
",",
"value",
"string",
")",
"bool",
")",
"error",
"{",
"if",
"pattern",
"==",
"\"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"pat... | // AscendKeys allows for iterating through keys based on the specified pattern. | [
"AscendKeys",
"allows",
"for",
"iterating",
"through",
"keys",
"based",
"on",
"the",
"specified",
"pattern",
"."
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L1590-L1620 | train |
tidwall/buntdb | buntdb.go | DescendKeys | func (tx *Tx) DescendKeys(pattern string,
iterator func(key, value string) bool) error {
if pattern == "" {
return nil
}
if pattern[0] == '*' {
if pattern == "*" {
return tx.Descend("", iterator)
}
return tx.Descend("", func(key, value string) bool {
if match.Match(key, pattern) {
if !iterator(key, value) {
return false
}
}
return true
})
}
min, max := match.Allowable(pattern)
return tx.DescendLessOrEqual("", max, func(key, value string) bool {
if key < min {
return false
}
if match.Match(key, pattern) {
if !iterator(key, value) {
return false
}
}
return true
})
} | go | func (tx *Tx) DescendKeys(pattern string,
iterator func(key, value string) bool) error {
if pattern == "" {
return nil
}
if pattern[0] == '*' {
if pattern == "*" {
return tx.Descend("", iterator)
}
return tx.Descend("", func(key, value string) bool {
if match.Match(key, pattern) {
if !iterator(key, value) {
return false
}
}
return true
})
}
min, max := match.Allowable(pattern)
return tx.DescendLessOrEqual("", max, func(key, value string) bool {
if key < min {
return false
}
if match.Match(key, pattern) {
if !iterator(key, value) {
return false
}
}
return true
})
} | [
"func",
"(",
"tx",
"*",
"Tx",
")",
"DescendKeys",
"(",
"pattern",
"string",
",",
"iterator",
"func",
"(",
"key",
",",
"value",
"string",
")",
"bool",
")",
"error",
"{",
"if",
"pattern",
"==",
"\"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"pa... | // DescendKeys allows for iterating through keys based on the specified pattern. | [
"DescendKeys",
"allows",
"for",
"iterating",
"through",
"keys",
"based",
"on",
"the",
"specified",
"pattern",
"."
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L1623-L1653 | train |
tidwall/buntdb | buntdb.go | Len | func (tx *Tx) Len() (int, error) {
if tx.db == nil {
return 0, ErrTxClosed
}
return tx.db.keys.Len(), nil
} | go | func (tx *Tx) Len() (int, error) {
if tx.db == nil {
return 0, ErrTxClosed
}
return tx.db.keys.Len(), nil
} | [
"func",
"(",
"tx",
"*",
"Tx",
")",
"Len",
"(",
")",
"(",
"int",
",",
"error",
")",
"{",
"if",
"tx",
".",
"db",
"==",
"nil",
"{",
"return",
"0",
",",
"ErrTxClosed",
"\n",
"}",
"\n",
"return",
"tx",
".",
"db",
".",
"keys",
".",
"Len",
"(",
")... | // Len returns the number of items in the database | [
"Len",
"returns",
"the",
"number",
"of",
"items",
"in",
"the",
"database"
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L1892-L1897 | train |
tidwall/buntdb | buntdb.go | CreateIndexOptions | func (tx *Tx) CreateIndexOptions(name, pattern string,
opts *IndexOptions,
less ...func(a, b string) bool) error {
return tx.createIndex(name, pattern, less, nil, opts)
} | go | func (tx *Tx) CreateIndexOptions(name, pattern string,
opts *IndexOptions,
less ...func(a, b string) bool) error {
return tx.createIndex(name, pattern, less, nil, opts)
} | [
"func",
"(",
"tx",
"*",
"Tx",
")",
"CreateIndexOptions",
"(",
"name",
",",
"pattern",
"string",
",",
"opts",
"*",
"IndexOptions",
",",
"less",
"...",
"func",
"(",
"a",
",",
"b",
"string",
")",
"bool",
")",
"error",
"{",
"return",
"tx",
".",
"createIn... | // CreateIndexOptions is the same as CreateIndex except that it allows
// for additional options. | [
"CreateIndexOptions",
"is",
"the",
"same",
"as",
"CreateIndex",
"except",
"that",
"it",
"allows",
"for",
"additional",
"options",
"."
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L1929-L1933 | train |
tidwall/buntdb | buntdb.go | CreateSpatialIndexOptions | func (tx *Tx) CreateSpatialIndexOptions(name, pattern string,
opts *IndexOptions,
rect func(item string) (min, max []float64)) error {
return tx.createIndex(name, pattern, nil, rect, nil)
} | go | func (tx *Tx) CreateSpatialIndexOptions(name, pattern string,
opts *IndexOptions,
rect func(item string) (min, max []float64)) error {
return tx.createIndex(name, pattern, nil, rect, nil)
} | [
"func",
"(",
"tx",
"*",
"Tx",
")",
"CreateSpatialIndexOptions",
"(",
"name",
",",
"pattern",
"string",
",",
"opts",
"*",
"IndexOptions",
",",
"rect",
"func",
"(",
"item",
"string",
")",
"(",
"min",
",",
"max",
"[",
"]",
"float64",
")",
")",
"error",
... | // CreateSpatialIndexOptions is the same as CreateSpatialIndex except that
// it allows for additional options. | [
"CreateSpatialIndexOptions",
"is",
"the",
"same",
"as",
"CreateSpatialIndex",
"except",
"that",
"it",
"allows",
"for",
"additional",
"options",
"."
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L1956-L1960 | train |
tidwall/buntdb | buntdb.go | DropIndex | func (tx *Tx) DropIndex(name string) error {
if tx.db == nil {
return ErrTxClosed
} else if !tx.writable {
return ErrTxNotWritable
} else if tx.wc.itercount > 0 {
return ErrTxIterating
}
if name == "" {
// cannot drop the default "keys" index
return ErrInvalidOperation
}
idx, ok := tx.db.idxs[name]
if !ok {
return ErrNotFound
}
// delete from the map.
// this is all that is needed to delete an index.
delete(tx.db.idxs, name)
if tx.wc.rbkeys == nil {
// store the index in the rollback map.
if _, ok := tx.wc.rollbackIndexes[name]; !ok {
// we use a non-nil copy of the index without the data to indicate that the
// index should be rebuilt upon rollback.
tx.wc.rollbackIndexes[name] = idx.clearCopy()
}
}
return nil
} | go | func (tx *Tx) DropIndex(name string) error {
if tx.db == nil {
return ErrTxClosed
} else if !tx.writable {
return ErrTxNotWritable
} else if tx.wc.itercount > 0 {
return ErrTxIterating
}
if name == "" {
// cannot drop the default "keys" index
return ErrInvalidOperation
}
idx, ok := tx.db.idxs[name]
if !ok {
return ErrNotFound
}
// delete from the map.
// this is all that is needed to delete an index.
delete(tx.db.idxs, name)
if tx.wc.rbkeys == nil {
// store the index in the rollback map.
if _, ok := tx.wc.rollbackIndexes[name]; !ok {
// we use a non-nil copy of the index without the data to indicate that the
// index should be rebuilt upon rollback.
tx.wc.rollbackIndexes[name] = idx.clearCopy()
}
}
return nil
} | [
"func",
"(",
"tx",
"*",
"Tx",
")",
"DropIndex",
"(",
"name",
"string",
")",
"error",
"{",
"if",
"tx",
".",
"db",
"==",
"nil",
"{",
"return",
"ErrTxClosed",
"\n",
"}",
"else",
"if",
"!",
"tx",
".",
"writable",
"{",
"return",
"ErrTxNotWritable",
"\n",
... | // DropIndex removes an index. | [
"DropIndex",
"removes",
"an",
"index",
"."
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L2037-L2065 | train |
tidwall/buntdb | buntdb.go | Indexes | func (tx *Tx) Indexes() ([]string, error) {
if tx.db == nil {
return nil, ErrTxClosed
}
names := make([]string, 0, len(tx.db.idxs))
for name := range tx.db.idxs {
names = append(names, name)
}
sort.Strings(names)
return names, nil
} | go | func (tx *Tx) Indexes() ([]string, error) {
if tx.db == nil {
return nil, ErrTxClosed
}
names := make([]string, 0, len(tx.db.idxs))
for name := range tx.db.idxs {
names = append(names, name)
}
sort.Strings(names)
return names, nil
} | [
"func",
"(",
"tx",
"*",
"Tx",
")",
"Indexes",
"(",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"if",
"tx",
".",
"db",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrTxClosed",
"\n",
"}",
"\n",
"names",
":=",
"make",
"(",
"[",
"]",
"str... | // Indexes returns a list of index names. | [
"Indexes",
"returns",
"a",
"list",
"of",
"index",
"names",
"."
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L2068-L2078 | train |
tidwall/buntdb | buntdb.go | IndexInt | func IndexInt(a, b string) bool {
ia, _ := strconv.ParseInt(a, 10, 64)
ib, _ := strconv.ParseInt(b, 10, 64)
return ia < ib
} | go | func IndexInt(a, b string) bool {
ia, _ := strconv.ParseInt(a, 10, 64)
ib, _ := strconv.ParseInt(b, 10, 64)
return ia < ib
} | [
"func",
"IndexInt",
"(",
"a",
",",
"b",
"string",
")",
"bool",
"{",
"ia",
",",
"_",
":=",
"strconv",
".",
"ParseInt",
"(",
"a",
",",
"10",
",",
"64",
")",
"\n",
"ib",
",",
"_",
":=",
"strconv",
".",
"ParseInt",
"(",
"b",
",",
"10",
",",
"64",... | // IndexInt is a helper function that returns true if 'a' is less than 'b'. | [
"IndexInt",
"is",
"a",
"helper",
"function",
"that",
"returns",
"true",
"if",
"a",
"is",
"less",
"than",
"b",
"."
] | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L2149-L2153 | train |
tidwall/buntdb | buntdb.go | IndexJSON | func IndexJSON(path string) func(a, b string) bool {
return func(a, b string) bool {
return gjson.Get(a, path).Less(gjson.Get(b, path), false)
}
} | go | func IndexJSON(path string) func(a, b string) bool {
return func(a, b string) bool {
return gjson.Get(a, path).Less(gjson.Get(b, path), false)
}
} | [
"func",
"IndexJSON",
"(",
"path",
"string",
")",
"func",
"(",
"a",
",",
"b",
"string",
")",
"bool",
"{",
"return",
"func",
"(",
"a",
",",
"b",
"string",
")",
"bool",
"{",
"return",
"gjson",
".",
"Get",
"(",
"a",
",",
"path",
")",
".",
"Less",
"... | // IndexJSON provides for the ability to create an index on any JSON field.
// When the field is a string, the comparison will be case-insensitive.
// It returns a helper function used by CreateIndex. | [
"IndexJSON",
"provides",
"for",
"the",
"ability",
"to",
"create",
"an",
"index",
"on",
"any",
"JSON",
"field",
".",
"When",
"the",
"field",
"is",
"a",
"string",
"the",
"comparison",
"will",
"be",
"case",
"-",
"insensitive",
".",
"It",
"returns",
"a",
"he... | 6249481c29c2cd96f53b691b74ac1893f72774c2 | https://github.com/tidwall/buntdb/blob/6249481c29c2cd96f53b691b74ac1893f72774c2/buntdb.go#L2176-L2180 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.