repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
BurntSushi/toml
decode.go
DecodeReader
func DecodeReader(r io.Reader, v interface{}) (MetaData, error) { bs, err := ioutil.ReadAll(r) if err != nil { return MetaData{}, err } return Decode(string(bs), v) }
go
func DecodeReader(r io.Reader, v interface{}) (MetaData, error) { bs, err := ioutil.ReadAll(r) if err != nil { return MetaData{}, err } return Decode(string(bs), v) }
[ "func", "DecodeReader", "(", "r", "io", ".", "Reader", ",", "v", "interface", "{", "}", ")", "(", "MetaData", ",", "error", ")", "{", "bs", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", ...
// DecodeReader is just like Decode, except it will consume all bytes // from the reader and decode it for you.
[ "DecodeReader", "is", "just", "like", "Decode", "except", "it", "will", "consume", "all", "bytes", "from", "the", "reader", "and", "decode", "it", "for", "you", "." ]
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/decode.go#L138-L144
train
BurntSushi/toml
decode.go
unify
func (md *MetaData) unify(data interface{}, rv reflect.Value) error { // Special case. Look for a `Primitive` value. if rv.Type() == reflect.TypeOf((*Primitive)(nil)).Elem() { // Save the undecoded data and the key context into the primitive // value. context := make(Key, len(md.context)) copy(context, md.context) rv.Set(reflect.ValueOf(Primitive{ undecoded: data, context: context, })) return nil } // Special case. Unmarshaler Interface support. if rv.CanAddr() { if v, ok := rv.Addr().Interface().(Unmarshaler); ok { return v.UnmarshalTOML(data) } } // Special case. Handle time.Time values specifically. // TODO: Remove this code when we decide to drop support for Go 1.1. // This isn't necessary in Go 1.2 because time.Time satisfies the encoding // interfaces. if rv.Type().AssignableTo(rvalue(time.Time{}).Type()) { return md.unifyDatetime(data, rv) } // Special case. Look for a value satisfying the TextUnmarshaler interface. if v, ok := rv.Interface().(TextUnmarshaler); ok { return md.unifyText(data, v) } // BUG(burntsushi) // The behavior here is incorrect whenever a Go type satisfies the // encoding.TextUnmarshaler interface but also corresponds to a TOML // hash or array. In particular, the unmarshaler should only be applied // to primitive TOML values. But at this point, it will be applied to // all kinds of values and produce an incorrect error whenever those values // are hashes or arrays (including arrays of tables). k := rv.Kind() // laziness if k >= reflect.Int && k <= reflect.Uint64 { return md.unifyInt(data, rv) } switch k { case reflect.Ptr: elem := reflect.New(rv.Type().Elem()) err := md.unify(data, reflect.Indirect(elem)) if err != nil { return err } rv.Set(elem) return nil case reflect.Struct: return md.unifyStruct(data, rv) case reflect.Map: return md.unifyMap(data, rv) case reflect.Array: return md.unifyArray(data, rv) case reflect.Slice: return md.unifySlice(data, rv) case reflect.String: return md.unifyString(data, rv) case reflect.Bool: return md.unifyBool(data, rv) case reflect.Interface: // we only support empty interfaces. if rv.NumMethod() > 0 { return e("unsupported type %s", rv.Type()) } return md.unifyAnything(data, rv) case reflect.Float32: fallthrough case reflect.Float64: return md.unifyFloat64(data, rv) } return e("unsupported type %s", rv.Kind()) }
go
func (md *MetaData) unify(data interface{}, rv reflect.Value) error { // Special case. Look for a `Primitive` value. if rv.Type() == reflect.TypeOf((*Primitive)(nil)).Elem() { // Save the undecoded data and the key context into the primitive // value. context := make(Key, len(md.context)) copy(context, md.context) rv.Set(reflect.ValueOf(Primitive{ undecoded: data, context: context, })) return nil } // Special case. Unmarshaler Interface support. if rv.CanAddr() { if v, ok := rv.Addr().Interface().(Unmarshaler); ok { return v.UnmarshalTOML(data) } } // Special case. Handle time.Time values specifically. // TODO: Remove this code when we decide to drop support for Go 1.1. // This isn't necessary in Go 1.2 because time.Time satisfies the encoding // interfaces. if rv.Type().AssignableTo(rvalue(time.Time{}).Type()) { return md.unifyDatetime(data, rv) } // Special case. Look for a value satisfying the TextUnmarshaler interface. if v, ok := rv.Interface().(TextUnmarshaler); ok { return md.unifyText(data, v) } // BUG(burntsushi) // The behavior here is incorrect whenever a Go type satisfies the // encoding.TextUnmarshaler interface but also corresponds to a TOML // hash or array. In particular, the unmarshaler should only be applied // to primitive TOML values. But at this point, it will be applied to // all kinds of values and produce an incorrect error whenever those values // are hashes or arrays (including arrays of tables). k := rv.Kind() // laziness if k >= reflect.Int && k <= reflect.Uint64 { return md.unifyInt(data, rv) } switch k { case reflect.Ptr: elem := reflect.New(rv.Type().Elem()) err := md.unify(data, reflect.Indirect(elem)) if err != nil { return err } rv.Set(elem) return nil case reflect.Struct: return md.unifyStruct(data, rv) case reflect.Map: return md.unifyMap(data, rv) case reflect.Array: return md.unifyArray(data, rv) case reflect.Slice: return md.unifySlice(data, rv) case reflect.String: return md.unifyString(data, rv) case reflect.Bool: return md.unifyBool(data, rv) case reflect.Interface: // we only support empty interfaces. if rv.NumMethod() > 0 { return e("unsupported type %s", rv.Type()) } return md.unifyAnything(data, rv) case reflect.Float32: fallthrough case reflect.Float64: return md.unifyFloat64(data, rv) } return e("unsupported type %s", rv.Kind()) }
[ "func", "(", "md", "*", "MetaData", ")", "unify", "(", "data", "interface", "{", "}", ",", "rv", "reflect", ".", "Value", ")", "error", "{", "// Special case. Look for a `Primitive` value.", "if", "rv", ".", "Type", "(", ")", "==", "reflect", ".", "TypeOf"...
// unify performs a sort of type unification based on the structure of `rv`, // which is the client representation. // // Any type mismatch produces an error. Finding a type that we don't know // how to handle produces an unsupported type error.
[ "unify", "performs", "a", "sort", "of", "type", "unification", "based", "on", "the", "structure", "of", "rv", "which", "is", "the", "client", "representation", ".", "Any", "type", "mismatch", "produces", "an", "error", ".", "Finding", "a", "type", "that", ...
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/decode.go#L151-L232
train
BurntSushi/toml
parse.go
numUnderscoresOK
func numUnderscoresOK(s string) bool { accept := false for _, r := range s { if r == '_' { if !accept { return false } accept = false continue } accept = true } return accept }
go
func numUnderscoresOK(s string) bool { accept := false for _, r := range s { if r == '_' { if !accept { return false } accept = false continue } accept = true } return accept }
[ "func", "numUnderscoresOK", "(", "s", "string", ")", "bool", "{", "accept", ":=", "false", "\n", "for", "_", ",", "r", ":=", "range", "s", "{", "if", "r", "==", "'_'", "{", "if", "!", "accept", "{", "return", "false", "\n", "}", "\n", "accept", "...
// numUnderscoresOK checks whether each underscore in s is surrounded by // characters that are not underscores.
[ "numUnderscoresOK", "checks", "whether", "each", "underscore", "in", "s", "is", "surrounded", "by", "characters", "that", "are", "not", "underscores", "." ]
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/parse.go#L314-L327
train
BurntSushi/toml
parse.go
numPeriodsOK
func numPeriodsOK(s string) bool { period := false for _, r := range s { if period && !isDigit(r) { return false } period = r == '.' } return !period }
go
func numPeriodsOK(s string) bool { period := false for _, r := range s { if period && !isDigit(r) { return false } period = r == '.' } return !period }
[ "func", "numPeriodsOK", "(", "s", "string", ")", "bool", "{", "period", ":=", "false", "\n", "for", "_", ",", "r", ":=", "range", "s", "{", "if", "period", "&&", "!", "isDigit", "(", "r", ")", "{", "return", "false", "\n", "}", "\n", "period", "=...
// numPeriodsOK checks whether every period in s is followed by a digit.
[ "numPeriodsOK", "checks", "whether", "every", "period", "in", "s", "is", "followed", "by", "a", "digit", "." ]
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/parse.go#L330-L339
train
BurntSushi/toml
parse.go
establishContext
func (p *parser) establishContext(key Key, array bool) { var ok bool // Always start at the top level and drill down for our context. hashContext := p.mapping keyContext := make(Key, 0) // We only need implicit hashes for key[0:-1] for _, k := range key[0 : len(key)-1] { _, ok = hashContext[k] keyContext = append(keyContext, k) // No key? Make an implicit hash and move on. if !ok { p.addImplicit(keyContext) hashContext[k] = make(map[string]interface{}) } // If the hash context is actually an array of tables, then set // the hash context to the last element in that array. // // Otherwise, it better be a table, since this MUST be a key group (by // virtue of it not being the last element in a key). switch t := hashContext[k].(type) { case []map[string]interface{}: hashContext = t[len(t)-1] case map[string]interface{}: hashContext = t default: p.panicf("Key '%s' was already created as a hash.", keyContext) } } p.context = keyContext if array { // If this is the first element for this array, then allocate a new // list of tables for it. k := key[len(key)-1] if _, ok := hashContext[k]; !ok { hashContext[k] = make([]map[string]interface{}, 0, 5) } // Add a new table. But make sure the key hasn't already been used // for something else. if hash, ok := hashContext[k].([]map[string]interface{}); ok { hashContext[k] = append(hash, make(map[string]interface{})) } else { p.panicf("Key '%s' was already created and cannot be used as "+ "an array.", keyContext) } } else { p.setValue(key[len(key)-1], make(map[string]interface{})) } p.context = append(p.context, key[len(key)-1]) }
go
func (p *parser) establishContext(key Key, array bool) { var ok bool // Always start at the top level and drill down for our context. hashContext := p.mapping keyContext := make(Key, 0) // We only need implicit hashes for key[0:-1] for _, k := range key[0 : len(key)-1] { _, ok = hashContext[k] keyContext = append(keyContext, k) // No key? Make an implicit hash and move on. if !ok { p.addImplicit(keyContext) hashContext[k] = make(map[string]interface{}) } // If the hash context is actually an array of tables, then set // the hash context to the last element in that array. // // Otherwise, it better be a table, since this MUST be a key group (by // virtue of it not being the last element in a key). switch t := hashContext[k].(type) { case []map[string]interface{}: hashContext = t[len(t)-1] case map[string]interface{}: hashContext = t default: p.panicf("Key '%s' was already created as a hash.", keyContext) } } p.context = keyContext if array { // If this is the first element for this array, then allocate a new // list of tables for it. k := key[len(key)-1] if _, ok := hashContext[k]; !ok { hashContext[k] = make([]map[string]interface{}, 0, 5) } // Add a new table. But make sure the key hasn't already been used // for something else. if hash, ok := hashContext[k].([]map[string]interface{}); ok { hashContext[k] = append(hash, make(map[string]interface{})) } else { p.panicf("Key '%s' was already created and cannot be used as "+ "an array.", keyContext) } } else { p.setValue(key[len(key)-1], make(map[string]interface{})) } p.context = append(p.context, key[len(key)-1]) }
[ "func", "(", "p", "*", "parser", ")", "establishContext", "(", "key", "Key", ",", "array", "bool", ")", "{", "var", "ok", "bool", "\n\n", "// Always start at the top level and drill down for our context.", "hashContext", ":=", "p", ".", "mapping", "\n", "keyContex...
// establishContext sets the current context of the parser, // where the context is either a hash or an array of hashes. Which one is // set depends on the value of the `array` parameter. // // Establishing the context also makes sure that the key isn't a duplicate, and // will create implicit hashes automatically.
[ "establishContext", "sets", "the", "current", "context", "of", "the", "parser", "where", "the", "context", "is", "either", "a", "hash", "or", "an", "array", "of", "hashes", ".", "Which", "one", "is", "set", "depends", "on", "the", "value", "of", "the", "...
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/parse.go#L347-L401
train
BurntSushi/toml
parse.go
setValue
func (p *parser) setValue(key string, value interface{}) { var tmpHash interface{} var ok bool hash := p.mapping keyContext := make(Key, 0) for _, k := range p.context { keyContext = append(keyContext, k) if tmpHash, ok = hash[k]; !ok { p.bug("Context for key '%s' has not been established.", keyContext) } switch t := tmpHash.(type) { case []map[string]interface{}: // The context is a table of hashes. Pick the most recent table // defined as the current hash. hash = t[len(t)-1] case map[string]interface{}: hash = t default: p.bug("Expected hash to have type 'map[string]interface{}', but "+ "it has '%T' instead.", tmpHash) } } keyContext = append(keyContext, key) if _, ok := hash[key]; ok { // Typically, if the given key has already been set, then we have // to raise an error since duplicate keys are disallowed. However, // it's possible that a key was previously defined implicitly. In this // case, it is allowed to be redefined concretely. (See the // `tests/valid/implicit-and-explicit-after.toml` test in `toml-test`.) // // But we have to make sure to stop marking it as an implicit. (So that // another redefinition provokes an error.) // // Note that since it has already been defined (as a hash), we don't // want to overwrite it. So our business is done. if p.isImplicit(keyContext) { p.removeImplicit(keyContext) return } // Otherwise, we have a concrete key trying to override a previous // key, which is *always* wrong. p.panicf("Key '%s' has already been defined.", keyContext) } hash[key] = value }
go
func (p *parser) setValue(key string, value interface{}) { var tmpHash interface{} var ok bool hash := p.mapping keyContext := make(Key, 0) for _, k := range p.context { keyContext = append(keyContext, k) if tmpHash, ok = hash[k]; !ok { p.bug("Context for key '%s' has not been established.", keyContext) } switch t := tmpHash.(type) { case []map[string]interface{}: // The context is a table of hashes. Pick the most recent table // defined as the current hash. hash = t[len(t)-1] case map[string]interface{}: hash = t default: p.bug("Expected hash to have type 'map[string]interface{}', but "+ "it has '%T' instead.", tmpHash) } } keyContext = append(keyContext, key) if _, ok := hash[key]; ok { // Typically, if the given key has already been set, then we have // to raise an error since duplicate keys are disallowed. However, // it's possible that a key was previously defined implicitly. In this // case, it is allowed to be redefined concretely. (See the // `tests/valid/implicit-and-explicit-after.toml` test in `toml-test`.) // // But we have to make sure to stop marking it as an implicit. (So that // another redefinition provokes an error.) // // Note that since it has already been defined (as a hash), we don't // want to overwrite it. So our business is done. if p.isImplicit(keyContext) { p.removeImplicit(keyContext) return } // Otherwise, we have a concrete key trying to override a previous // key, which is *always* wrong. p.panicf("Key '%s' has already been defined.", keyContext) } hash[key] = value }
[ "func", "(", "p", "*", "parser", ")", "setValue", "(", "key", "string", ",", "value", "interface", "{", "}", ")", "{", "var", "tmpHash", "interface", "{", "}", "\n", "var", "ok", "bool", "\n\n", "hash", ":=", "p", ".", "mapping", "\n", "keyContext", ...
// setValue sets the given key to the given value in the current context. // It will make sure that the key hasn't already been defined, account for // implicit key groups.
[ "setValue", "sets", "the", "given", "key", "to", "the", "given", "value", "in", "the", "current", "context", ".", "It", "will", "make", "sure", "that", "the", "key", "hasn", "t", "already", "been", "defined", "account", "for", "implicit", "key", "groups", ...
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/parse.go#L406-L453
train
BurntSushi/toml
parse.go
addImplicit
func (p *parser) addImplicit(key Key) { p.implicits[key.String()] = true }
go
func (p *parser) addImplicit(key Key) { p.implicits[key.String()] = true }
[ "func", "(", "p", "*", "parser", ")", "addImplicit", "(", "key", "Key", ")", "{", "p", ".", "implicits", "[", "key", ".", "String", "(", ")", "]", "=", "true", "\n", "}" ]
// addImplicit sets the given Key as having been created implicitly.
[ "addImplicit", "sets", "the", "given", "Key", "as", "having", "been", "created", "implicitly", "." ]
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/parse.go#L472-L474
train
BurntSushi/toml
parse.go
removeImplicit
func (p *parser) removeImplicit(key Key) { p.implicits[key.String()] = false }
go
func (p *parser) removeImplicit(key Key) { p.implicits[key.String()] = false }
[ "func", "(", "p", "*", "parser", ")", "removeImplicit", "(", "key", "Key", ")", "{", "p", ".", "implicits", "[", "key", ".", "String", "(", ")", "]", "=", "false", "\n", "}" ]
// removeImplicit stops tagging the given key as having been implicitly // created.
[ "removeImplicit", "stops", "tagging", "the", "given", "key", "as", "having", "been", "implicitly", "created", "." ]
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/parse.go#L478-L480
train
BurntSushi/toml
parse.go
isImplicit
func (p *parser) isImplicit(key Key) bool { return p.implicits[key.String()] }
go
func (p *parser) isImplicit(key Key) bool { return p.implicits[key.String()] }
[ "func", "(", "p", "*", "parser", ")", "isImplicit", "(", "key", "Key", ")", "bool", "{", "return", "p", ".", "implicits", "[", "key", ".", "String", "(", ")", "]", "\n", "}" ]
// isImplicit returns true if the key group pointed to by the key was created // implicitly.
[ "isImplicit", "returns", "true", "if", "the", "key", "group", "pointed", "to", "by", "the", "key", "was", "created", "implicitly", "." ]
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/parse.go#L484-L486
train
BurntSushi/toml
parse.go
current
func (p *parser) current() string { if len(p.currentKey) == 0 { return p.context.String() } if len(p.context) == 0 { return p.currentKey } return fmt.Sprintf("%s.%s", p.context, p.currentKey) }
go
func (p *parser) current() string { if len(p.currentKey) == 0 { return p.context.String() } if len(p.context) == 0 { return p.currentKey } return fmt.Sprintf("%s.%s", p.context, p.currentKey) }
[ "func", "(", "p", "*", "parser", ")", "current", "(", ")", "string", "{", "if", "len", "(", "p", ".", "currentKey", ")", "==", "0", "{", "return", "p", ".", "context", ".", "String", "(", ")", "\n", "}", "\n", "if", "len", "(", "p", ".", "con...
// current returns the full key name of the current context.
[ "current", "returns", "the", "full", "key", "name", "of", "the", "current", "context", "." ]
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/parse.go#L489-L497
train
BurntSushi/toml
type_check.go
typeOfArray
func (p *parser) typeOfArray(types []tomlType) tomlType { // Empty arrays are cool. if len(types) == 0 { return tomlArray } theType := types[0] for _, t := range types[1:] { if !typeEqual(theType, t) { p.panicf("Array contains values of type '%s' and '%s', but "+ "arrays must be homogeneous.", theType, t) } } return tomlArray }
go
func (p *parser) typeOfArray(types []tomlType) tomlType { // Empty arrays are cool. if len(types) == 0 { return tomlArray } theType := types[0] for _, t := range types[1:] { if !typeEqual(theType, t) { p.panicf("Array contains values of type '%s' and '%s', but "+ "arrays must be homogeneous.", theType, t) } } return tomlArray }
[ "func", "(", "p", "*", "parser", ")", "typeOfArray", "(", "types", "[", "]", "tomlType", ")", "tomlType", "{", "// Empty arrays are cool.", "if", "len", "(", "types", ")", "==", "0", "{", "return", "tomlArray", "\n", "}", "\n\n", "theType", ":=", "types"...
// typeOfArray returns a tomlType for an array given a list of types of its // values. // // In the current spec, if an array is homogeneous, then its type is always // "Array". If the array is not homogeneous, an error is generated.
[ "typeOfArray", "returns", "a", "tomlType", "for", "an", "array", "given", "a", "list", "of", "types", "of", "its", "values", ".", "In", "the", "current", "spec", "if", "an", "array", "is", "homogeneous", "then", "its", "type", "is", "always", "Array", "....
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/type_check.go#L77-L91
train
BurntSushi/toml
decode_meta.go
Type
func (md *MetaData) Type(key ...string) string { fullkey := strings.Join(key, ".") if typ, ok := md.types[fullkey]; ok { return typ.typeString() } return "" }
go
func (md *MetaData) Type(key ...string) string { fullkey := strings.Join(key, ".") if typ, ok := md.types[fullkey]; ok { return typ.typeString() } return "" }
[ "func", "(", "md", "*", "MetaData", ")", "Type", "(", "key", "...", "string", ")", "string", "{", "fullkey", ":=", "strings", ".", "Join", "(", "key", ",", "\"", "\"", ")", "\n", "if", "typ", ",", "ok", ":=", "md", ".", "types", "[", "fullkey", ...
// Type returns a string representation of the type of the key specified. // // Type will return the empty string if given an empty key or a key that // does not exist. Keys are case sensitive.
[ "Type", "returns", "a", "string", "representation", "of", "the", "type", "of", "the", "key", "specified", ".", "Type", "will", "return", "the", "empty", "string", "if", "given", "an", "empty", "key", "or", "a", "key", "that", "does", "not", "exist", ".",...
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/decode_meta.go#L46-L52
train
BurntSushi/toml
decode_meta.go
Undecoded
func (md *MetaData) Undecoded() []Key { undecoded := make([]Key, 0, len(md.keys)) for _, key := range md.keys { if !md.decoded[key.String()] { undecoded = append(undecoded, key) } } return undecoded }
go
func (md *MetaData) Undecoded() []Key { undecoded := make([]Key, 0, len(md.keys)) for _, key := range md.keys { if !md.decoded[key.String()] { undecoded = append(undecoded, key) } } return undecoded }
[ "func", "(", "md", "*", "MetaData", ")", "Undecoded", "(", ")", "[", "]", "Key", "{", "undecoded", ":=", "make", "(", "[", "]", "Key", ",", "0", ",", "len", "(", "md", ".", "keys", ")", ")", "\n", "for", "_", ",", "key", ":=", "range", "md", ...
// Undecoded returns all keys that have not been decoded in the order in which // they appear in the original TOML document. // // This includes keys that haven't been decoded because of a Primitive value. // Once the Primitive value is decoded, the keys will be considered decoded. // // Also note that decoding into an empty interface will result in no decoding, // and so no keys will be considered decoded. // // In this sense, the Undecoded keys correspond to keys in the TOML document // that do not have a concrete type in your representation.
[ "Undecoded", "returns", "all", "keys", "that", "have", "not", "been", "decoded", "in", "the", "order", "in", "which", "they", "appear", "in", "the", "original", "TOML", "document", ".", "This", "includes", "keys", "that", "haven", "t", "been", "decoded", "...
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/decode_meta.go#L113-L121
train
BurntSushi/toml
lex.go
backup
func (lx *lexer) backup() { if lx.atEOF { lx.atEOF = false return } if lx.nprev < 1 { panic("backed up too far") } w := lx.prevWidths[0] lx.prevWidths[0] = lx.prevWidths[1] lx.prevWidths[1] = lx.prevWidths[2] lx.nprev-- lx.pos -= w if lx.pos < len(lx.input) && lx.input[lx.pos] == '\n' { lx.line-- } }
go
func (lx *lexer) backup() { if lx.atEOF { lx.atEOF = false return } if lx.nprev < 1 { panic("backed up too far") } w := lx.prevWidths[0] lx.prevWidths[0] = lx.prevWidths[1] lx.prevWidths[1] = lx.prevWidths[2] lx.nprev-- lx.pos -= w if lx.pos < len(lx.input) && lx.input[lx.pos] == '\n' { lx.line-- } }
[ "func", "(", "lx", "*", "lexer", ")", "backup", "(", ")", "{", "if", "lx", ".", "atEOF", "{", "lx", ".", "atEOF", "=", "false", "\n", "return", "\n", "}", "\n", "if", "lx", ".", "nprev", "<", "1", "{", "panic", "(", "\"", "\"", ")", "\n", "...
// backup steps back one rune. Can be called only twice between calls to next.
[ "backup", "steps", "back", "one", "rune", ".", "Can", "be", "called", "only", "twice", "between", "calls", "to", "next", "." ]
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/lex.go#L167-L183
train
BurntSushi/toml
lex.go
accept
func (lx *lexer) accept(valid rune) bool { if lx.next() == valid { return true } lx.backup() return false }
go
func (lx *lexer) accept(valid rune) bool { if lx.next() == valid { return true } lx.backup() return false }
[ "func", "(", "lx", "*", "lexer", ")", "accept", "(", "valid", "rune", ")", "bool", "{", "if", "lx", ".", "next", "(", ")", "==", "valid", "{", "return", "true", "\n", "}", "\n", "lx", ".", "backup", "(", ")", "\n", "return", "false", "\n", "}" ...
// accept consumes the next rune if it's equal to `valid`.
[ "accept", "consumes", "the", "next", "rune", "if", "it", "s", "equal", "to", "valid", "." ]
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/lex.go#L186-L192
train
BurntSushi/toml
lex.go
skip
func (lx *lexer) skip(pred func(rune) bool) { for { r := lx.next() if pred(r) { continue } lx.backup() lx.ignore() return } }
go
func (lx *lexer) skip(pred func(rune) bool) { for { r := lx.next() if pred(r) { continue } lx.backup() lx.ignore() return } }
[ "func", "(", "lx", "*", "lexer", ")", "skip", "(", "pred", "func", "(", "rune", ")", "bool", ")", "{", "for", "{", "r", ":=", "lx", ".", "next", "(", ")", "\n", "if", "pred", "(", "r", ")", "{", "continue", "\n", "}", "\n", "lx", ".", "back...
// skip ignores all input that matches the given predicate.
[ "skip", "ignores", "all", "input", "that", "matches", "the", "given", "predicate", "." ]
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/lex.go#L202-L212
train
BurntSushi/toml
lex.go
lexTop
func lexTop(lx *lexer) stateFn { r := lx.next() if isWhitespace(r) || isNL(r) { return lexSkip(lx, lexTop) } switch r { case commentStart: lx.push(lexTop) return lexCommentStart case tableStart: return lexTableStart case eof: if lx.pos > lx.start { return lx.errorf("unexpected EOF") } lx.emit(itemEOF) return nil } // At this point, the only valid item can be a key, so we back up // and let the key lexer do the rest. lx.backup() lx.push(lexTopEnd) return lexKeyStart }
go
func lexTop(lx *lexer) stateFn { r := lx.next() if isWhitespace(r) || isNL(r) { return lexSkip(lx, lexTop) } switch r { case commentStart: lx.push(lexTop) return lexCommentStart case tableStart: return lexTableStart case eof: if lx.pos > lx.start { return lx.errorf("unexpected EOF") } lx.emit(itemEOF) return nil } // At this point, the only valid item can be a key, so we back up // and let the key lexer do the rest. lx.backup() lx.push(lexTopEnd) return lexKeyStart }
[ "func", "lexTop", "(", "lx", "*", "lexer", ")", "stateFn", "{", "r", ":=", "lx", ".", "next", "(", ")", "\n", "if", "isWhitespace", "(", "r", ")", "||", "isNL", "(", "r", ")", "{", "return", "lexSkip", "(", "lx", ",", "lexTop", ")", "\n", "}", ...
// lexTop consumes elements at the top level of TOML data.
[ "lexTop", "consumes", "elements", "at", "the", "top", "level", "of", "TOML", "data", "." ]
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/lex.go#L227-L251
train
BurntSushi/toml
lex.go
lexBareTableName
func lexBareTableName(lx *lexer) stateFn { r := lx.next() if isBareKeyChar(r) { return lexBareTableName } lx.backup() lx.emit(itemText) return lexTableNameEnd }
go
func lexBareTableName(lx *lexer) stateFn { r := lx.next() if isBareKeyChar(r) { return lexBareTableName } lx.backup() lx.emit(itemText) return lexTableNameEnd }
[ "func", "lexBareTableName", "(", "lx", "*", "lexer", ")", "stateFn", "{", "r", ":=", "lx", ".", "next", "(", ")", "\n", "if", "isBareKeyChar", "(", "r", ")", "{", "return", "lexBareTableName", "\n", "}", "\n", "lx", ".", "backup", "(", ")", "\n", "...
// lexBareTableName lexes the name of a table. It assumes that at least one // valid character for the table has already been read.
[ "lexBareTableName", "lexes", "the", "name", "of", "a", "table", ".", "It", "assumes", "that", "at", "least", "one", "valid", "character", "for", "the", "table", "has", "already", "been", "read", "." ]
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/lex.go#L327-L335
train
BurntSushi/toml
lex.go
lexTableNameEnd
func lexTableNameEnd(lx *lexer) stateFn { lx.skip(isWhitespace) switch r := lx.next(); { case isWhitespace(r): return lexTableNameEnd case r == tableSep: lx.ignore() return lexTableNameStart case r == tableEnd: return lx.pop() default: return lx.errorf("expected '.' or ']' to end table name, "+ "but got %q instead", r) } }
go
func lexTableNameEnd(lx *lexer) stateFn { lx.skip(isWhitespace) switch r := lx.next(); { case isWhitespace(r): return lexTableNameEnd case r == tableSep: lx.ignore() return lexTableNameStart case r == tableEnd: return lx.pop() default: return lx.errorf("expected '.' or ']' to end table name, "+ "but got %q instead", r) } }
[ "func", "lexTableNameEnd", "(", "lx", "*", "lexer", ")", "stateFn", "{", "lx", ".", "skip", "(", "isWhitespace", ")", "\n", "switch", "r", ":=", "lx", ".", "next", "(", ")", ";", "{", "case", "isWhitespace", "(", "r", ")", ":", "return", "lexTableNam...
// lexTableNameEnd reads the end of a piece of a table name, optionally // consuming whitespace.
[ "lexTableNameEnd", "reads", "the", "end", "of", "a", "piece", "of", "a", "table", "name", "optionally", "consuming", "whitespace", "." ]
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/lex.go#L339-L353
train
BurntSushi/toml
lex.go
lexKeyStart
func lexKeyStart(lx *lexer) stateFn { r := lx.peek() switch { case r == keySep: return lx.errorf("unexpected key separator %q", keySep) case isWhitespace(r) || isNL(r): lx.next() return lexSkip(lx, lexKeyStart) case r == stringStart || r == rawStringStart: lx.ignore() lx.emit(itemKeyStart) lx.push(lexKeyEnd) return lexValue // reuse string lexing default: lx.ignore() lx.emit(itemKeyStart) return lexBareKey } }
go
func lexKeyStart(lx *lexer) stateFn { r := lx.peek() switch { case r == keySep: return lx.errorf("unexpected key separator %q", keySep) case isWhitespace(r) || isNL(r): lx.next() return lexSkip(lx, lexKeyStart) case r == stringStart || r == rawStringStart: lx.ignore() lx.emit(itemKeyStart) lx.push(lexKeyEnd) return lexValue // reuse string lexing default: lx.ignore() lx.emit(itemKeyStart) return lexBareKey } }
[ "func", "lexKeyStart", "(", "lx", "*", "lexer", ")", "stateFn", "{", "r", ":=", "lx", ".", "peek", "(", ")", "\n", "switch", "{", "case", "r", "==", "keySep", ":", "return", "lx", ".", "errorf", "(", "\"", "\"", ",", "keySep", ")", "\n", "case", ...
// lexKeyStart consumes a key name up until the first non-whitespace character. // lexKeyStart will ignore whitespace.
[ "lexKeyStart", "consumes", "a", "key", "name", "up", "until", "the", "first", "non", "-", "whitespace", "character", ".", "lexKeyStart", "will", "ignore", "whitespace", "." ]
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/lex.go#L357-L375
train
BurntSushi/toml
lex.go
lexArrayValue
func lexArrayValue(lx *lexer) stateFn { r := lx.next() switch { case isWhitespace(r) || isNL(r): return lexSkip(lx, lexArrayValue) case r == commentStart: lx.push(lexArrayValue) return lexCommentStart case r == comma: return lx.errorf("unexpected comma") case r == arrayEnd: // NOTE(caleb): The spec isn't clear about whether you can have // a trailing comma or not, so we'll allow it. return lexArrayEnd } lx.backup() lx.push(lexArrayValueEnd) return lexValue }
go
func lexArrayValue(lx *lexer) stateFn { r := lx.next() switch { case isWhitespace(r) || isNL(r): return lexSkip(lx, lexArrayValue) case r == commentStart: lx.push(lexArrayValue) return lexCommentStart case r == comma: return lx.errorf("unexpected comma") case r == arrayEnd: // NOTE(caleb): The spec isn't clear about whether you can have // a trailing comma or not, so we'll allow it. return lexArrayEnd } lx.backup() lx.push(lexArrayValueEnd) return lexValue }
[ "func", "lexArrayValue", "(", "lx", "*", "lexer", ")", "stateFn", "{", "r", ":=", "lx", ".", "next", "(", ")", "\n", "switch", "{", "case", "isWhitespace", "(", "r", ")", "||", "isNL", "(", "r", ")", ":", "return", "lexSkip", "(", "lx", ",", "lex...
// lexArrayValue consumes one value in an array. It assumes that '[' or ',' // have already been consumed. All whitespace and newlines are ignored.
[ "lexArrayValue", "consumes", "one", "value", "in", "an", "array", ".", "It", "assumes", "that", "[", "or", "have", "already", "been", "consumed", ".", "All", "whitespace", "and", "newlines", "are", "ignored", "." ]
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/lex.go#L471-L490
train
BurntSushi/toml
lex.go
lexInlineTableEnd
func lexInlineTableEnd(lx *lexer) stateFn { lx.ignore() lx.emit(itemInlineTableEnd) return lx.pop() }
go
func lexInlineTableEnd(lx *lexer) stateFn { lx.ignore() lx.emit(itemInlineTableEnd) return lx.pop() }
[ "func", "lexInlineTableEnd", "(", "lx", "*", "lexer", ")", "stateFn", "{", "lx", ".", "ignore", "(", ")", "\n", "lx", ".", "emit", "(", "itemInlineTableEnd", ")", "\n", "return", "lx", ".", "pop", "(", ")", "\n", "}" ]
// lexInlineTableEnd finishes the lexing of an inline table. // It assumes that a '}' has just been consumed.
[ "lexInlineTableEnd", "finishes", "the", "lexing", "of", "an", "inline", "table", ".", "It", "assumes", "that", "a", "}", "has", "just", "been", "consumed", "." ]
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/lex.go#L570-L574
train
BurntSushi/toml
lex.go
lexMultilineString
func lexMultilineString(lx *lexer) stateFn { switch lx.next() { case eof: return lx.errorf("unexpected EOF") case '\\': return lexMultilineStringEscape case stringEnd: if lx.accept(stringEnd) { if lx.accept(stringEnd) { lx.backup() lx.backup() lx.backup() lx.emit(itemMultilineString) lx.next() lx.next() lx.next() lx.ignore() return lx.pop() } lx.backup() } } return lexMultilineString }
go
func lexMultilineString(lx *lexer) stateFn { switch lx.next() { case eof: return lx.errorf("unexpected EOF") case '\\': return lexMultilineStringEscape case stringEnd: if lx.accept(stringEnd) { if lx.accept(stringEnd) { lx.backup() lx.backup() lx.backup() lx.emit(itemMultilineString) lx.next() lx.next() lx.next() lx.ignore() return lx.pop() } lx.backup() } } return lexMultilineString }
[ "func", "lexMultilineString", "(", "lx", "*", "lexer", ")", "stateFn", "{", "switch", "lx", ".", "next", "(", ")", "{", "case", "eof", ":", "return", "lx", ".", "errorf", "(", "\"", "\"", ")", "\n", "case", "'\\\\'", ":", "return", "lexMultilineStringE...
// lexMultilineString consumes the inner contents of a string. It assumes that // the beginning '"""' has already been consumed and ignored.
[ "lexMultilineString", "consumes", "the", "inner", "contents", "of", "a", "string", ".", "It", "assumes", "that", "the", "beginning", "has", "already", "been", "consumed", "and", "ignored", "." ]
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/lex.go#L600-L623
train
BurntSushi/toml
lex.go
lexRawString
func lexRawString(lx *lexer) stateFn { r := lx.next() switch { case r == eof: return lx.errorf("unexpected EOF") case isNL(r): return lx.errorf("strings cannot contain newlines") case r == rawStringEnd: lx.backup() lx.emit(itemRawString) lx.next() lx.ignore() return lx.pop() } return lexRawString }
go
func lexRawString(lx *lexer) stateFn { r := lx.next() switch { case r == eof: return lx.errorf("unexpected EOF") case isNL(r): return lx.errorf("strings cannot contain newlines") case r == rawStringEnd: lx.backup() lx.emit(itemRawString) lx.next() lx.ignore() return lx.pop() } return lexRawString }
[ "func", "lexRawString", "(", "lx", "*", "lexer", ")", "stateFn", "{", "r", ":=", "lx", ".", "next", "(", ")", "\n", "switch", "{", "case", "r", "==", "eof", ":", "return", "lx", ".", "errorf", "(", "\"", "\"", ")", "\n", "case", "isNL", "(", "r...
// lexRawString consumes a raw string. Nothing can be escaped in such a string. // It assumes that the beginning "'" has already been consumed and ignored.
[ "lexRawString", "consumes", "a", "raw", "string", ".", "Nothing", "can", "be", "escaped", "in", "such", "a", "string", ".", "It", "assumes", "that", "the", "beginning", "has", "already", "been", "consumed", "and", "ignored", "." ]
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/lex.go#L627-L642
train
BurntSushi/toml
lex.go
lexMultilineRawString
func lexMultilineRawString(lx *lexer) stateFn { switch lx.next() { case eof: return lx.errorf("unexpected EOF") case rawStringEnd: if lx.accept(rawStringEnd) { if lx.accept(rawStringEnd) { lx.backup() lx.backup() lx.backup() lx.emit(itemRawMultilineString) lx.next() lx.next() lx.next() lx.ignore() return lx.pop() } lx.backup() } } return lexMultilineRawString }
go
func lexMultilineRawString(lx *lexer) stateFn { switch lx.next() { case eof: return lx.errorf("unexpected EOF") case rawStringEnd: if lx.accept(rawStringEnd) { if lx.accept(rawStringEnd) { lx.backup() lx.backup() lx.backup() lx.emit(itemRawMultilineString) lx.next() lx.next() lx.next() lx.ignore() return lx.pop() } lx.backup() } } return lexMultilineRawString }
[ "func", "lexMultilineRawString", "(", "lx", "*", "lexer", ")", "stateFn", "{", "switch", "lx", ".", "next", "(", ")", "{", "case", "eof", ":", "return", "lx", ".", "errorf", "(", "\"", "\"", ")", "\n", "case", "rawStringEnd", ":", "if", "lx", ".", ...
// lexMultilineRawString consumes a raw string. Nothing can be escaped in such // a string. It assumes that the beginning "'''" has already been consumed and // ignored.
[ "lexMultilineRawString", "consumes", "a", "raw", "string", ".", "Nothing", "can", "be", "escaped", "in", "such", "a", "string", ".", "It", "assumes", "that", "the", "beginning", "has", "already", "been", "consumed", "and", "ignored", "." ]
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/lex.go#L647-L668
train
BurntSushi/toml
lex.go
lexMultilineStringEscape
func lexMultilineStringEscape(lx *lexer) stateFn { // Handle the special case first: if isNL(lx.next()) { return lexMultilineString } lx.backup() lx.push(lexMultilineString) return lexStringEscape(lx) }
go
func lexMultilineStringEscape(lx *lexer) stateFn { // Handle the special case first: if isNL(lx.next()) { return lexMultilineString } lx.backup() lx.push(lexMultilineString) return lexStringEscape(lx) }
[ "func", "lexMultilineStringEscape", "(", "lx", "*", "lexer", ")", "stateFn", "{", "// Handle the special case first:", "if", "isNL", "(", "lx", ".", "next", "(", ")", ")", "{", "return", "lexMultilineString", "\n", "}", "\n", "lx", ".", "backup", "(", ")", ...
// lexMultilineStringEscape consumes an escaped character. It assumes that the // preceding '\\' has already been consumed.
[ "lexMultilineStringEscape", "consumes", "an", "escaped", "character", ".", "It", "assumes", "that", "the", "preceding", "\\\\", "has", "already", "been", "consumed", "." ]
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/lex.go#L672-L680
train
BurntSushi/toml
lex.go
lexNumberOrDate
func lexNumberOrDate(lx *lexer) stateFn { r := lx.next() if isDigit(r) { return lexNumberOrDate } switch r { case '-': return lexDatetime case '_': return lexNumber case '.', 'e', 'E': return lexFloat } lx.backup() lx.emit(itemInteger) return lx.pop() }
go
func lexNumberOrDate(lx *lexer) stateFn { r := lx.next() if isDigit(r) { return lexNumberOrDate } switch r { case '-': return lexDatetime case '_': return lexNumber case '.', 'e', 'E': return lexFloat } lx.backup() lx.emit(itemInteger) return lx.pop() }
[ "func", "lexNumberOrDate", "(", "lx", "*", "lexer", ")", "stateFn", "{", "r", ":=", "lx", ".", "next", "(", ")", "\n", "if", "isDigit", "(", "r", ")", "{", "return", "lexNumberOrDate", "\n", "}", "\n", "switch", "r", "{", "case", "'-'", ":", "retur...
// lexNumberOrDate consumes either an integer, float or datetime.
[ "lexNumberOrDate", "consumes", "either", "an", "integer", "float", "or", "datetime", "." ]
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/lex.go#L751-L768
train
BurntSushi/toml
lex.go
lexDatetime
func lexDatetime(lx *lexer) stateFn { r := lx.next() if isDigit(r) { return lexDatetime } switch r { case '-', 'T', ':', '.', 'Z', '+': return lexDatetime } lx.backup() lx.emit(itemDatetime) return lx.pop() }
go
func lexDatetime(lx *lexer) stateFn { r := lx.next() if isDigit(r) { return lexDatetime } switch r { case '-', 'T', ':', '.', 'Z', '+': return lexDatetime } lx.backup() lx.emit(itemDatetime) return lx.pop() }
[ "func", "lexDatetime", "(", "lx", "*", "lexer", ")", "stateFn", "{", "r", ":=", "lx", ".", "next", "(", ")", "\n", "if", "isDigit", "(", "r", ")", "{", "return", "lexDatetime", "\n", "}", "\n", "switch", "r", "{", "case", "'-'", ",", "'T'", ",", ...
// lexDatetime consumes a Datetime, to a first approximation. // The parser validates that it matches one of the accepted formats.
[ "lexDatetime", "consumes", "a", "Datetime", "to", "a", "first", "approximation", ".", "The", "parser", "validates", "that", "it", "matches", "one", "of", "the", "accepted", "formats", "." ]
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/lex.go#L772-L785
train
BurntSushi/toml
encode.go
NewEncoder
func NewEncoder(w io.Writer) *Encoder { return &Encoder{ w: bufio.NewWriter(w), Indent: " ", } }
go
func NewEncoder(w io.Writer) *Encoder { return &Encoder{ w: bufio.NewWriter(w), Indent: " ", } }
[ "func", "NewEncoder", "(", "w", "io", ".", "Writer", ")", "*", "Encoder", "{", "return", "&", "Encoder", "{", "w", ":", "bufio", ".", "NewWriter", "(", "w", ")", ",", "Indent", ":", "\"", "\"", ",", "}", "\n", "}" ]
// NewEncoder returns a TOML encoder that encodes Go values to the io.Writer // given. By default, a single indentation level is 2 spaces.
[ "NewEncoder", "returns", "a", "TOML", "encoder", "that", "encodes", "Go", "values", "to", "the", "io", ".", "Writer", "given", ".", "By", "default", "a", "single", "indentation", "level", "is", "2", "spaces", "." ]
3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005
https://github.com/BurntSushi/toml/blob/3012a1dbe2e4bd1391d42b32f0577cb7bbc7f005/encode.go#L56-L61
train
bluele/gcache
lru.go
evict
func (c *LRUCache) evict(count int) { for i := 0; i < count; i++ { ent := c.evictList.Back() if ent == nil { return } else { c.removeElement(ent) } } }
go
func (c *LRUCache) evict(count int) { for i := 0; i < count; i++ { ent := c.evictList.Back() if ent == nil { return } else { c.removeElement(ent) } } }
[ "func", "(", "c", "*", "LRUCache", ")", "evict", "(", "count", "int", ")", "{", "for", "i", ":=", "0", ";", "i", "<", "count", ";", "i", "++", "{", "ent", ":=", "c", ".", "evictList", ".", "Back", "(", ")", "\n", "if", "ent", "==", "nil", "...
// evict removes the oldest item from the cache.
[ "evict", "removes", "the", "oldest", "item", "from", "the", "cache", "." ]
79ae3b2d8680cbc7ad3dba9db66b8a648575221c
https://github.com/bluele/gcache/blob/79ae3b2d8680cbc7ad3dba9db66b8a648575221c/lru.go#L174-L183
train
bluele/gcache
arc.go
Has
func (c *ARC) Has(key interface{}) bool { c.mu.RLock() defer c.mu.RUnlock() now := time.Now() return c.has(key, &now) }
go
func (c *ARC) Has(key interface{}) bool { c.mu.RLock() defer c.mu.RUnlock() now := time.Now() return c.has(key, &now) }
[ "func", "(", "c", "*", "ARC", ")", "Has", "(", "key", "interface", "{", "}", ")", "bool", "{", "c", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "RUnlock", "(", ")", "\n", "now", ":=", "time", ".", "Now", "(", ")",...
// Has checks if key exists in cache
[ "Has", "checks", "if", "key", "exists", "in", "cache" ]
79ae3b2d8680cbc7ad3dba9db66b8a648575221c
https://github.com/bluele/gcache/blob/79ae3b2d8680cbc7ad3dba9db66b8a648575221c/arc.go#L267-L272
train
bluele/gcache
arc.go
Keys
func (c *ARC) Keys() []interface{} { keys := []interface{}{} for _, k := range c.keys() { _, err := c.GetIFPresent(k) if err == nil { keys = append(keys, k) } } return keys }
go
func (c *ARC) Keys() []interface{} { keys := []interface{}{} for _, k := range c.keys() { _, err := c.GetIFPresent(k) if err == nil { keys = append(keys, k) } } return keys }
[ "func", "(", "c", "*", "ARC", ")", "Keys", "(", ")", "[", "]", "interface", "{", "}", "{", "keys", ":=", "[", "]", "interface", "{", "}", "{", "}", "\n", "for", "_", ",", "k", ":=", "range", "c", ".", "keys", "(", ")", "{", "_", ",", "err...
// Keys returns a slice of the keys in the cache.
[ "Keys", "returns", "a", "slice", "of", "the", "keys", "in", "the", "cache", "." ]
79ae3b2d8680cbc7ad3dba9db66b8a648575221c
https://github.com/bluele/gcache/blob/79ae3b2d8680cbc7ad3dba9db66b8a648575221c/arc.go#L329-L338
train
bluele/gcache
arc.go
GetALL
func (c *ARC) GetALL() map[interface{}]interface{} { m := make(map[interface{}]interface{}) for _, k := range c.keys() { v, err := c.GetIFPresent(k) if err == nil { m[k] = v } } return m }
go
func (c *ARC) GetALL() map[interface{}]interface{} { m := make(map[interface{}]interface{}) for _, k := range c.keys() { v, err := c.GetIFPresent(k) if err == nil { m[k] = v } } return m }
[ "func", "(", "c", "*", "ARC", ")", "GetALL", "(", ")", "map", "[", "interface", "{", "}", "]", "interface", "{", "}", "{", "m", ":=", "make", "(", "map", "[", "interface", "{", "}", "]", "interface", "{", "}", ")", "\n", "for", "_", ",", "k",...
// GetALL returns all key-value pairs in the cache.
[ "GetALL", "returns", "all", "key", "-", "value", "pairs", "in", "the", "cache", "." ]
79ae3b2d8680cbc7ad3dba9db66b8a648575221c
https://github.com/bluele/gcache/blob/79ae3b2d8680cbc7ad3dba9db66b8a648575221c/arc.go#L341-L350
train
bluele/gcache
lfu.go
Set
func (c *LFUCache) Set(key, value interface{}) error { c.mu.Lock() defer c.mu.Unlock() _, err := c.set(key, value) return err }
go
func (c *LFUCache) Set(key, value interface{}) error { c.mu.Lock() defer c.mu.Unlock() _, err := c.set(key, value) return err }
[ "func", "(", "c", "*", "LFUCache", ")", "Set", "(", "key", ",", "value", "interface", "{", "}", ")", "error", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "_", ",", "err", ":=", "...
// Set a new key-value pair
[ "Set", "a", "new", "key", "-", "value", "pair" ]
79ae3b2d8680cbc7ad3dba9db66b8a648575221c
https://github.com/bluele/gcache/blob/79ae3b2d8680cbc7ad3dba9db66b8a648575221c/lfu.go#L34-L39
train
bluele/gcache
lfu.go
SetWithExpire
func (c *LFUCache) SetWithExpire(key, value interface{}, expiration time.Duration) error { c.mu.Lock() defer c.mu.Unlock() item, err := c.set(key, value) if err != nil { return err } t := c.clock.Now().Add(expiration) item.(*lfuItem).expiration = &t return nil }
go
func (c *LFUCache) SetWithExpire(key, value interface{}, expiration time.Duration) error { c.mu.Lock() defer c.mu.Unlock() item, err := c.set(key, value) if err != nil { return err } t := c.clock.Now().Add(expiration) item.(*lfuItem).expiration = &t return nil }
[ "func", "(", "c", "*", "LFUCache", ")", "SetWithExpire", "(", "key", ",", "value", "interface", "{", "}", ",", "expiration", "time", ".", "Duration", ")", "error", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "U...
// Set a new key-value pair with an expiration time
[ "Set", "a", "new", "key", "-", "value", "pair", "with", "an", "expiration", "time" ]
79ae3b2d8680cbc7ad3dba9db66b8a648575221c
https://github.com/bluele/gcache/blob/79ae3b2d8680cbc7ad3dba9db66b8a648575221c/lfu.go#L42-L53
train
bluele/gcache
lfu.go
Get
func (c *LFUCache) Get(key interface{}) (interface{}, error) { v, err := c.get(key, false) if err == KeyNotFoundError { return c.getWithLoader(key, true) } return v, err }
go
func (c *LFUCache) Get(key interface{}) (interface{}, error) { v, err := c.get(key, false) if err == KeyNotFoundError { return c.getWithLoader(key, true) } return v, err }
[ "func", "(", "c", "*", "LFUCache", ")", "Get", "(", "key", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "v", ",", "err", ":=", "c", ".", "get", "(", "key", ",", "false", ")", "\n", "if", "err", "==", "KeyNot...
// Get a value from cache pool using key if it exists. // If it dose not exists key and has LoaderFunc, // generate a value using `LoaderFunc` method returns value.
[ "Get", "a", "value", "from", "cache", "pool", "using", "key", "if", "it", "exists", ".", "If", "it", "dose", "not", "exists", "key", "and", "has", "LoaderFunc", "generate", "a", "value", "using", "LoaderFunc", "method", "returns", "value", "." ]
79ae3b2d8680cbc7ad3dba9db66b8a648575221c
https://github.com/bluele/gcache/blob/79ae3b2d8680cbc7ad3dba9db66b8a648575221c/lfu.go#L102-L108
train
bluele/gcache
lfu.go
evict
func (c *LFUCache) evict(count int) { entry := c.freqList.Front() for i := 0; i < count; { if entry == nil { return } else { for item, _ := range entry.Value.(*freqEntry).items { if i >= count { return } c.removeItem(item) i++ } entry = entry.Next() } } }
go
func (c *LFUCache) evict(count int) { entry := c.freqList.Front() for i := 0; i < count; { if entry == nil { return } else { for item, _ := range entry.Value.(*freqEntry).items { if i >= count { return } c.removeItem(item) i++ } entry = entry.Next() } } }
[ "func", "(", "c", "*", "LFUCache", ")", "evict", "(", "count", "int", ")", "{", "entry", ":=", "c", ".", "freqList", ".", "Front", "(", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "count", ";", "{", "if", "entry", "==", "nil", "{", "retu...
// evict removes the least frequence item from the cache.
[ "evict", "removes", "the", "least", "frequence", "item", "from", "the", "cache", "." ]
79ae3b2d8680cbc7ad3dba9db66b8a648575221c
https://github.com/bluele/gcache/blob/79ae3b2d8680cbc7ad3dba9db66b8a648575221c/lfu.go#L198-L214
train
bluele/gcache
stats.go
HitRate
func (st *stats) HitRate() float64 { hc, mc := st.HitCount(), st.MissCount() total := hc + mc if total == 0 { return 0.0 } return float64(hc) / float64(total) }
go
func (st *stats) HitRate() float64 { hc, mc := st.HitCount(), st.MissCount() total := hc + mc if total == 0 { return 0.0 } return float64(hc) / float64(total) }
[ "func", "(", "st", "*", "stats", ")", "HitRate", "(", ")", "float64", "{", "hc", ",", "mc", ":=", "st", ".", "HitCount", "(", ")", ",", "st", ".", "MissCount", "(", ")", "\n", "total", ":=", "hc", "+", "mc", "\n", "if", "total", "==", "0", "{...
// HitRate returns rate for cache hitting
[ "HitRate", "returns", "rate", "for", "cache", "hitting" ]
79ae3b2d8680cbc7ad3dba9db66b8a648575221c
https://github.com/bluele/gcache/blob/79ae3b2d8680cbc7ad3dba9db66b8a648575221c/stats.go#L46-L53
train
bluele/gcache
cache.go
load
func (c *baseCache) load(key interface{}, cb func(interface{}, *time.Duration, error) (interface{}, error), isWait bool) (interface{}, bool, error) { v, called, err := c.loadGroup.Do(key, func() (v interface{}, e error) { defer func() { if r := recover(); r != nil { e = fmt.Errorf("Loader panics: %v", r) } }() return cb(c.loaderExpireFunc(key)) }, isWait) if err != nil { return nil, called, err } return v, called, nil }
go
func (c *baseCache) load(key interface{}, cb func(interface{}, *time.Duration, error) (interface{}, error), isWait bool) (interface{}, bool, error) { v, called, err := c.loadGroup.Do(key, func() (v interface{}, e error) { defer func() { if r := recover(); r != nil { e = fmt.Errorf("Loader panics: %v", r) } }() return cb(c.loaderExpireFunc(key)) }, isWait) if err != nil { return nil, called, err } return v, called, nil }
[ "func", "(", "c", "*", "baseCache", ")", "load", "(", "key", "interface", "{", "}", ",", "cb", "func", "(", "interface", "{", "}", ",", "*", "time", ".", "Duration", ",", "error", ")", "(", "interface", "{", "}", ",", "error", ")", ",", "isWait",...
// load a new value using by specified key.
[ "load", "a", "new", "value", "using", "by", "specified", "key", "." ]
79ae3b2d8680cbc7ad3dba9db66b8a648575221c
https://github.com/bluele/gcache/blob/79ae3b2d8680cbc7ad3dba9db66b8a648575221c/cache.go#L192-L205
train
bitly/oauth2_proxy
options.go
secretBytes
func secretBytes(secret string) []byte { b, err := base64.URLEncoding.DecodeString(addPadding(secret)) if err == nil { return []byte(addPadding(string(b))) } return []byte(secret) }
go
func secretBytes(secret string) []byte { b, err := base64.URLEncoding.DecodeString(addPadding(secret)) if err == nil { return []byte(addPadding(string(b))) } return []byte(secret) }
[ "func", "secretBytes", "(", "secret", "string", ")", "[", "]", "byte", "{", "b", ",", "err", ":=", "base64", ".", "URLEncoding", ".", "DecodeString", "(", "addPadding", "(", "secret", ")", ")", "\n", "if", "err", "==", "nil", "{", "return", "[", "]",...
// secretBytes attempts to base64 decode the secret, if that fails it treats the secret as binary
[ "secretBytes", "attempts", "to", "base64", "decode", "the", "secret", "if", "that", "fails", "it", "treats", "the", "secret", "as", "binary" ]
fa2771998a98a5bfdfa3c3503757668ac4f1c8ec
https://github.com/bitly/oauth2_proxy/blob/fa2771998a98a5bfdfa3c3503757668ac4f1c8ec/options.go#L329-L335
train
bitly/oauth2_proxy
providers/internal_util.go
stripParam
func stripParam(param, endpoint string) string { u, err := url.Parse(endpoint) if err != nil { log.Printf("error attempting to strip %s: %s", param, err) return endpoint } if u.RawQuery != "" { values, err := url.ParseQuery(u.RawQuery) if err != nil { log.Printf("error attempting to strip %s: %s", param, err) return u.String() } if val := values.Get(param); val != "" { values.Set(param, val[:(len(val)/2)]+"...") u.RawQuery = values.Encode() return u.String() } } return endpoint }
go
func stripParam(param, endpoint string) string { u, err := url.Parse(endpoint) if err != nil { log.Printf("error attempting to strip %s: %s", param, err) return endpoint } if u.RawQuery != "" { values, err := url.ParseQuery(u.RawQuery) if err != nil { log.Printf("error attempting to strip %s: %s", param, err) return u.String() } if val := values.Get(param); val != "" { values.Set(param, val[:(len(val)/2)]+"...") u.RawQuery = values.Encode() return u.String() } } return endpoint }
[ "func", "stripParam", "(", "param", ",", "endpoint", "string", ")", "string", "{", "u", ",", "err", ":=", "url", ".", "Parse", "(", "endpoint", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "param", ",", "e...
// stripParam generalizes the obfuscation of a particular // query parameter - typically 'access_token' or 'client_secret' // The parameter's second half is replaced by '...' and returned // as part of the encoded query parameters. // If the target parameter isn't found, the endpoint is returned // unmodified.
[ "stripParam", "generalizes", "the", "obfuscation", "of", "a", "particular", "query", "parameter", "-", "typically", "access_token", "or", "client_secret", "The", "parameter", "s", "second", "half", "is", "replaced", "by", "...", "and", "returned", "as", "part", ...
fa2771998a98a5bfdfa3c3503757668ac4f1c8ec
https://github.com/bitly/oauth2_proxy/blob/fa2771998a98a5bfdfa3c3503757668ac4f1c8ec/providers/internal_util.go#L24-L46
train
bitly/oauth2_proxy
providers/internal_util.go
validateToken
func validateToken(p Provider, access_token string, header http.Header) bool { if access_token == "" || p.Data().ValidateURL == nil { return false } endpoint := p.Data().ValidateURL.String() if len(header) == 0 { params := url.Values{"access_token": {access_token}} endpoint = endpoint + "?" + params.Encode() } resp, err := api.RequestUnparsedResponse(endpoint, header) if err != nil { log.Printf("GET %s", stripToken(endpoint)) log.Printf("token validation request failed: %s", err) return false } body, _ := ioutil.ReadAll(resp.Body) resp.Body.Close() log.Printf("%d GET %s %s", resp.StatusCode, stripToken(endpoint), body) if resp.StatusCode == 200 { return true } log.Printf("token validation request failed: status %d - %s", resp.StatusCode, body) return false }
go
func validateToken(p Provider, access_token string, header http.Header) bool { if access_token == "" || p.Data().ValidateURL == nil { return false } endpoint := p.Data().ValidateURL.String() if len(header) == 0 { params := url.Values{"access_token": {access_token}} endpoint = endpoint + "?" + params.Encode() } resp, err := api.RequestUnparsedResponse(endpoint, header) if err != nil { log.Printf("GET %s", stripToken(endpoint)) log.Printf("token validation request failed: %s", err) return false } body, _ := ioutil.ReadAll(resp.Body) resp.Body.Close() log.Printf("%d GET %s %s", resp.StatusCode, stripToken(endpoint), body) if resp.StatusCode == 200 { return true } log.Printf("token validation request failed: status %d - %s", resp.StatusCode, body) return false }
[ "func", "validateToken", "(", "p", "Provider", ",", "access_token", "string", ",", "header", "http", ".", "Header", ")", "bool", "{", "if", "access_token", "==", "\"", "\"", "||", "p", ".", "Data", "(", ")", ".", "ValidateURL", "==", "nil", "{", "retur...
// validateToken returns true if token is valid
[ "validateToken", "returns", "true", "if", "token", "is", "valid" ]
fa2771998a98a5bfdfa3c3503757668ac4f1c8ec
https://github.com/bitly/oauth2_proxy/blob/fa2771998a98a5bfdfa3c3503757668ac4f1c8ec/providers/internal_util.go#L49-L74
train
bitly/oauth2_proxy
logging_handler.go
writeLogLine
func (h loggingHandler) writeLogLine(username, upstream string, req *http.Request, url url.URL, ts time.Time, status int, size int) { if username == "" { username = "-" } if upstream == "" { upstream = "-" } if url.User != nil && username == "-" { if name := url.User.Username(); name != "" { username = name } } client := req.Header.Get("X-Real-IP") if client == "" { client = req.RemoteAddr } if c, _, err := net.SplitHostPort(client); err == nil { client = c } duration := float64(time.Now().Sub(ts)) / float64(time.Second) h.logTemplate.Execute(h.writer, logMessageData{ Client: client, Host: req.Host, Protocol: req.Proto, RequestDuration: fmt.Sprintf("%0.3f", duration), RequestMethod: req.Method, RequestURI: fmt.Sprintf("%q", url.RequestURI()), ResponseSize: fmt.Sprintf("%d", size), StatusCode: fmt.Sprintf("%d", status), Timestamp: ts.Format("02/Jan/2006:15:04:05 -0700"), Upstream: upstream, UserAgent: fmt.Sprintf("%q", req.UserAgent()), Username: username, }) h.writer.Write([]byte("\n")) }
go
func (h loggingHandler) writeLogLine(username, upstream string, req *http.Request, url url.URL, ts time.Time, status int, size int) { if username == "" { username = "-" } if upstream == "" { upstream = "-" } if url.User != nil && username == "-" { if name := url.User.Username(); name != "" { username = name } } client := req.Header.Get("X-Real-IP") if client == "" { client = req.RemoteAddr } if c, _, err := net.SplitHostPort(client); err == nil { client = c } duration := float64(time.Now().Sub(ts)) / float64(time.Second) h.logTemplate.Execute(h.writer, logMessageData{ Client: client, Host: req.Host, Protocol: req.Proto, RequestDuration: fmt.Sprintf("%0.3f", duration), RequestMethod: req.Method, RequestURI: fmt.Sprintf("%q", url.RequestURI()), ResponseSize: fmt.Sprintf("%d", size), StatusCode: fmt.Sprintf("%d", status), Timestamp: ts.Format("02/Jan/2006:15:04:05 -0700"), Upstream: upstream, UserAgent: fmt.Sprintf("%q", req.UserAgent()), Username: username, }) h.writer.Write([]byte("\n")) }
[ "func", "(", "h", "loggingHandler", ")", "writeLogLine", "(", "username", ",", "upstream", "string", ",", "req", "*", "http", ".", "Request", ",", "url", "url", ".", "URL", ",", "ts", "time", ".", "Time", ",", "status", "int", ",", "size", "int", ")"...
// Log entry for req similar to Apache Common Log Format. // ts is the timestamp with which the entry should be logged. // status, size are used to provide the response HTTP status and size.
[ "Log", "entry", "for", "req", "similar", "to", "Apache", "Common", "Log", "Format", ".", "ts", "is", "the", "timestamp", "with", "which", "the", "entry", "should", "be", "logged", ".", "status", "size", "are", "used", "to", "provide", "the", "response", ...
fa2771998a98a5bfdfa3c3503757668ac4f1c8ec
https://github.com/bitly/oauth2_proxy/blob/fa2771998a98a5bfdfa3c3503757668ac4f1c8ec/logging_handler.go#L120-L160
train
bitly/oauth2_proxy
cookie/cookies.go
SignedValue
func SignedValue(seed string, key string, value string, now time.Time) string { encodedValue := base64.URLEncoding.EncodeToString([]byte(value)) timeStr := fmt.Sprintf("%d", now.Unix()) sig := cookieSignature(seed, key, encodedValue, timeStr) cookieVal := fmt.Sprintf("%s|%s|%s", encodedValue, timeStr, sig) return cookieVal }
go
func SignedValue(seed string, key string, value string, now time.Time) string { encodedValue := base64.URLEncoding.EncodeToString([]byte(value)) timeStr := fmt.Sprintf("%d", now.Unix()) sig := cookieSignature(seed, key, encodedValue, timeStr) cookieVal := fmt.Sprintf("%s|%s|%s", encodedValue, timeStr, sig) return cookieVal }
[ "func", "SignedValue", "(", "seed", "string", ",", "key", "string", ",", "value", "string", ",", "now", "time", ".", "Time", ")", "string", "{", "encodedValue", ":=", "base64", ".", "URLEncoding", ".", "EncodeToString", "(", "[", "]", "byte", "(", "value...
// SignedValue returns a cookie that is signed and can later be checked with Validate
[ "SignedValue", "returns", "a", "cookie", "that", "is", "signed", "and", "can", "later", "be", "checked", "with", "Validate" ]
fa2771998a98a5bfdfa3c3503757668ac4f1c8ec
https://github.com/bitly/oauth2_proxy/blob/fa2771998a98a5bfdfa3c3503757668ac4f1c8ec/cookie/cookies.go#L53-L59
train
bitly/oauth2_proxy
cookie/cookies.go
NewCipher
func NewCipher(secret []byte) (*Cipher, error) { c, err := aes.NewCipher(secret) if err != nil { return nil, err } return &Cipher{Block: c}, err }
go
func NewCipher(secret []byte) (*Cipher, error) { c, err := aes.NewCipher(secret) if err != nil { return nil, err } return &Cipher{Block: c}, err }
[ "func", "NewCipher", "(", "secret", "[", "]", "byte", ")", "(", "*", "Cipher", ",", "error", ")", "{", "c", ",", "err", ":=", "aes", ".", "NewCipher", "(", "secret", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "...
// NewCipher returns a new aes Cipher for encrypting cookie values
[ "NewCipher", "returns", "a", "new", "aes", "Cipher", "for", "encrypting", "cookie", "values" ]
fa2771998a98a5bfdfa3c3503757668ac4f1c8ec
https://github.com/bitly/oauth2_proxy/blob/fa2771998a98a5bfdfa3c3503757668ac4f1c8ec/cookie/cookies.go#L88-L94
train
bitly/oauth2_proxy
cookie/cookies.go
Encrypt
func (c *Cipher) Encrypt(value string) (string, error) { ciphertext := make([]byte, aes.BlockSize+len(value)) iv := ciphertext[:aes.BlockSize] if _, err := io.ReadFull(rand.Reader, iv); err != nil { return "", fmt.Errorf("failed to create initialization vector %s", err) } stream := cipher.NewCFBEncrypter(c.Block, iv) stream.XORKeyStream(ciphertext[aes.BlockSize:], []byte(value)) return base64.StdEncoding.EncodeToString(ciphertext), nil }
go
func (c *Cipher) Encrypt(value string) (string, error) { ciphertext := make([]byte, aes.BlockSize+len(value)) iv := ciphertext[:aes.BlockSize] if _, err := io.ReadFull(rand.Reader, iv); err != nil { return "", fmt.Errorf("failed to create initialization vector %s", err) } stream := cipher.NewCFBEncrypter(c.Block, iv) stream.XORKeyStream(ciphertext[aes.BlockSize:], []byte(value)) return base64.StdEncoding.EncodeToString(ciphertext), nil }
[ "func", "(", "c", "*", "Cipher", ")", "Encrypt", "(", "value", "string", ")", "(", "string", ",", "error", ")", "{", "ciphertext", ":=", "make", "(", "[", "]", "byte", ",", "aes", ".", "BlockSize", "+", "len", "(", "value", ")", ")", "\n", "iv", ...
// Encrypt a value for use in a cookie
[ "Encrypt", "a", "value", "for", "use", "in", "a", "cookie" ]
fa2771998a98a5bfdfa3c3503757668ac4f1c8ec
https://github.com/bitly/oauth2_proxy/blob/fa2771998a98a5bfdfa3c3503757668ac4f1c8ec/cookie/cookies.go#L97-L107
train
bitly/oauth2_proxy
cookie/cookies.go
Decrypt
func (c *Cipher) Decrypt(s string) (string, error) { encrypted, err := base64.StdEncoding.DecodeString(s) if err != nil { return "", fmt.Errorf("failed to decrypt cookie value %s", err) } if len(encrypted) < aes.BlockSize { return "", fmt.Errorf("encrypted cookie value should be "+ "at least %d bytes, but is only %d bytes", aes.BlockSize, len(encrypted)) } iv := encrypted[:aes.BlockSize] encrypted = encrypted[aes.BlockSize:] stream := cipher.NewCFBDecrypter(c.Block, iv) stream.XORKeyStream(encrypted, encrypted) return string(encrypted), nil }
go
func (c *Cipher) Decrypt(s string) (string, error) { encrypted, err := base64.StdEncoding.DecodeString(s) if err != nil { return "", fmt.Errorf("failed to decrypt cookie value %s", err) } if len(encrypted) < aes.BlockSize { return "", fmt.Errorf("encrypted cookie value should be "+ "at least %d bytes, but is only %d bytes", aes.BlockSize, len(encrypted)) } iv := encrypted[:aes.BlockSize] encrypted = encrypted[aes.BlockSize:] stream := cipher.NewCFBDecrypter(c.Block, iv) stream.XORKeyStream(encrypted, encrypted) return string(encrypted), nil }
[ "func", "(", "c", "*", "Cipher", ")", "Decrypt", "(", "s", "string", ")", "(", "string", ",", "error", ")", "{", "encrypted", ",", "err", ":=", "base64", ".", "StdEncoding", ".", "DecodeString", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", ...
// Decrypt a value from a cookie to it's original string
[ "Decrypt", "a", "value", "from", "a", "cookie", "to", "it", "s", "original", "string" ]
fa2771998a98a5bfdfa3c3503757668ac4f1c8ec
https://github.com/bitly/oauth2_proxy/blob/fa2771998a98a5bfdfa3c3503757668ac4f1c8ec/cookie/cookies.go#L110-L128
train
bitly/oauth2_proxy
providers/provider_default.go
GetLoginURL
func (p *ProviderData) GetLoginURL(redirectURI, state string) string { var a url.URL a = *p.LoginURL params, _ := url.ParseQuery(a.RawQuery) params.Set("redirect_uri", redirectURI) params.Set("approval_prompt", p.ApprovalPrompt) params.Add("scope", p.Scope) params.Set("client_id", p.ClientID) params.Set("response_type", "code") params.Add("state", state) a.RawQuery = params.Encode() return a.String() }
go
func (p *ProviderData) GetLoginURL(redirectURI, state string) string { var a url.URL a = *p.LoginURL params, _ := url.ParseQuery(a.RawQuery) params.Set("redirect_uri", redirectURI) params.Set("approval_prompt", p.ApprovalPrompt) params.Add("scope", p.Scope) params.Set("client_id", p.ClientID) params.Set("response_type", "code") params.Add("state", state) a.RawQuery = params.Encode() return a.String() }
[ "func", "(", "p", "*", "ProviderData", ")", "GetLoginURL", "(", "redirectURI", ",", "state", "string", ")", "string", "{", "var", "a", "url", ".", "URL", "\n", "a", "=", "*", "p", ".", "LoginURL", "\n", "params", ",", "_", ":=", "url", ".", "ParseQ...
// GetLoginURL with typical oauth parameters
[ "GetLoginURL", "with", "typical", "oauth", "parameters" ]
fa2771998a98a5bfdfa3c3503757668ac4f1c8ec
https://github.com/bitly/oauth2_proxy/blob/fa2771998a98a5bfdfa3c3503757668ac4f1c8ec/providers/provider_default.go#L81-L93
train
bitly/oauth2_proxy
providers/provider_default.go
CookieForSession
func (p *ProviderData) CookieForSession(s *SessionState, c *cookie.Cipher) (string, error) { return s.EncodeSessionState(c) }
go
func (p *ProviderData) CookieForSession(s *SessionState, c *cookie.Cipher) (string, error) { return s.EncodeSessionState(c) }
[ "func", "(", "p", "*", "ProviderData", ")", "CookieForSession", "(", "s", "*", "SessionState", ",", "c", "*", "cookie", ".", "Cipher", ")", "(", "string", ",", "error", ")", "{", "return", "s", ".", "EncodeSessionState", "(", "c", ")", "\n", "}" ]
// CookieForSession serializes a session state for storage in a cookie
[ "CookieForSession", "serializes", "a", "session", "state", "for", "storage", "in", "a", "cookie" ]
fa2771998a98a5bfdfa3c3503757668ac4f1c8ec
https://github.com/bitly/oauth2_proxy/blob/fa2771998a98a5bfdfa3c3503757668ac4f1c8ec/providers/provider_default.go#L96-L98
train
bitly/oauth2_proxy
providers/provider_default.go
SessionFromCookie
func (p *ProviderData) SessionFromCookie(v string, c *cookie.Cipher) (s *SessionState, err error) { return DecodeSessionState(v, c) }
go
func (p *ProviderData) SessionFromCookie(v string, c *cookie.Cipher) (s *SessionState, err error) { return DecodeSessionState(v, c) }
[ "func", "(", "p", "*", "ProviderData", ")", "SessionFromCookie", "(", "v", "string", ",", "c", "*", "cookie", ".", "Cipher", ")", "(", "s", "*", "SessionState", ",", "err", "error", ")", "{", "return", "DecodeSessionState", "(", "v", ",", "c", ")", "...
// SessionFromCookie deserializes a session from a cookie value
[ "SessionFromCookie", "deserializes", "a", "session", "from", "a", "cookie", "value" ]
fa2771998a98a5bfdfa3c3503757668ac4f1c8ec
https://github.com/bitly/oauth2_proxy/blob/fa2771998a98a5bfdfa3c3503757668ac4f1c8ec/providers/provider_default.go#L101-L103
train
mattn/go-sqlite3
_example/custom_func/main.go
xor
func xor(xs ...int64) int64 { var ret int64 for _, x := range xs { ret ^= x } return ret }
go
func xor(xs ...int64) int64 { var ret int64 for _, x := range xs { ret ^= x } return ret }
[ "func", "xor", "(", "xs", "...", "int64", ")", "int64", "{", "var", "ret", "int64", "\n", "for", "_", ",", "x", ":=", "range", "xs", "{", "ret", "^=", "x", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// Computes the bitwise exclusive-or of all its arguments
[ "Computes", "the", "bitwise", "exclusive", "-", "or", "of", "all", "its", "arguments" ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/_example/custom_func/main.go#L19-L25
train
mattn/go-sqlite3
sqlite3_trace.go
popTraceMapping
func popTraceMapping(connHandle uintptr) (TraceConfig, bool) { traceMapLock.Lock() defer traceMapLock.Unlock() entryCopy, found := traceMap[connHandle] if found { delete(traceMap, connHandle) fmt.Printf("Pop handle 0x%x: deleted trace config %v.\n", connHandle, entryCopy.config) } return entryCopy.config, found }
go
func popTraceMapping(connHandle uintptr) (TraceConfig, bool) { traceMapLock.Lock() defer traceMapLock.Unlock() entryCopy, found := traceMap[connHandle] if found { delete(traceMap, connHandle) fmt.Printf("Pop handle 0x%x: deleted trace config %v.\n", connHandle, entryCopy.config) } return entryCopy.config, found }
[ "func", "popTraceMapping", "(", "connHandle", "uintptr", ")", "(", "TraceConfig", ",", "bool", ")", "{", "traceMapLock", ".", "Lock", "(", ")", "\n", "defer", "traceMapLock", ".", "Unlock", "(", ")", "\n\n", "entryCopy", ",", "found", ":=", "traceMap", "["...
// 'pop' = get and delete from map before returning the value to the caller
[ "pop", "=", "get", "and", "delete", "from", "map", "before", "returning", "the", "value", "to", "the", "caller" ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3_trace.go#L229-L239
train
mattn/go-sqlite3
backup.go
Backup
func (c *SQLiteConn) Backup(dest string, conn *SQLiteConn, src string) (*SQLiteBackup, error) { destptr := C.CString(dest) defer C.free(unsafe.Pointer(destptr)) srcptr := C.CString(src) defer C.free(unsafe.Pointer(srcptr)) if b := C.sqlite3_backup_init(c.db, destptr, conn.db, srcptr); b != nil { bb := &SQLiteBackup{b: b} runtime.SetFinalizer(bb, (*SQLiteBackup).Finish) return bb, nil } return nil, c.lastError() }
go
func (c *SQLiteConn) Backup(dest string, conn *SQLiteConn, src string) (*SQLiteBackup, error) { destptr := C.CString(dest) defer C.free(unsafe.Pointer(destptr)) srcptr := C.CString(src) defer C.free(unsafe.Pointer(srcptr)) if b := C.sqlite3_backup_init(c.db, destptr, conn.db, srcptr); b != nil { bb := &SQLiteBackup{b: b} runtime.SetFinalizer(bb, (*SQLiteBackup).Finish) return bb, nil } return nil, c.lastError() }
[ "func", "(", "c", "*", "SQLiteConn", ")", "Backup", "(", "dest", "string", ",", "conn", "*", "SQLiteConn", ",", "src", "string", ")", "(", "*", "SQLiteBackup", ",", "error", ")", "{", "destptr", ":=", "C", ".", "CString", "(", "dest", ")", "\n", "d...
// Backup make backup from src to dest.
[ "Backup", "make", "backup", "from", "src", "to", "dest", "." ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/backup.go#L28-L40
train
mattn/go-sqlite3
backup.go
Close
func (b *SQLiteBackup) Close() error { ret := C.sqlite3_backup_finish(b.b) // sqlite3_backup_finish() never fails, it just returns the // error code from previous operations, so clean up before // checking and returning an error b.b = nil runtime.SetFinalizer(b, nil) if ret != 0 { return Error{Code: ErrNo(ret)} } return nil }
go
func (b *SQLiteBackup) Close() error { ret := C.sqlite3_backup_finish(b.b) // sqlite3_backup_finish() never fails, it just returns the // error code from previous operations, so clean up before // checking and returning an error b.b = nil runtime.SetFinalizer(b, nil) if ret != 0 { return Error{Code: ErrNo(ret)} } return nil }
[ "func", "(", "b", "*", "SQLiteBackup", ")", "Close", "(", ")", "error", "{", "ret", ":=", "C", ".", "sqlite3_backup_finish", "(", "b", ".", "b", ")", "\n\n", "// sqlite3_backup_finish() never fails, it just returns the", "// error code from previous operations, so clean...
// Close close backup.
[ "Close", "close", "backup", "." ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/backup.go#L72-L85
train
mattn/go-sqlite3
sqlite3_context.go
ResultBool
func (c *SQLiteContext) ResultBool(b bool) { if b { c.ResultInt(1) } else { c.ResultInt(0) } }
go
func (c *SQLiteContext) ResultBool(b bool) { if b { c.ResultInt(1) } else { c.ResultInt(0) } }
[ "func", "(", "c", "*", "SQLiteContext", ")", "ResultBool", "(", "b", "bool", ")", "{", "if", "b", "{", "c", ".", "ResultInt", "(", "1", ")", "\n", "}", "else", "{", "c", ".", "ResultInt", "(", "0", ")", "\n", "}", "\n", "}" ]
// ResultBool sets the result of an SQL function.
[ "ResultBool", "sets", "the", "result", "of", "an", "SQL", "function", "." ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3_context.go#L41-L47
train
mattn/go-sqlite3
error.go
Extend
func (err ErrNo) Extend(by int) ErrNoExtended { return ErrNoExtended(int(err) | (by << 8)) }
go
func (err ErrNo) Extend(by int) ErrNoExtended { return ErrNoExtended(int(err) | (by << 8)) }
[ "func", "(", "err", "ErrNo", ")", "Extend", "(", "by", "int", ")", "ErrNoExtended", "{", "return", "ErrNoExtended", "(", "int", "(", "err", ")", "|", "(", "by", "<<", "8", ")", ")", "\n", "}" ]
// Extend return extended errno.
[ "Extend", "return", "extended", "errno", "." ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/error.go#L65-L67
train
mattn/go-sqlite3
error.go
Error
func (err ErrNoExtended) Error() string { return Error{Code: ErrNo(C.int(err) & ErrNoMask), ExtendedCode: err}.Error() }
go
func (err ErrNoExtended) Error() string { return Error{Code: ErrNo(C.int(err) & ErrNoMask), ExtendedCode: err}.Error() }
[ "func", "(", "err", "ErrNoExtended", ")", "Error", "(", ")", "string", "{", "return", "Error", "{", "Code", ":", "ErrNo", "(", "C", ".", "int", "(", "err", ")", "&", "ErrNoMask", ")", ",", "ExtendedCode", ":", "err", "}", ".", "Error", "(", ")", ...
// Error return error message that is extended code.
[ "Error", "return", "error", "message", "that", "is", "extended", "code", "." ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/error.go#L70-L72
train
mattn/go-sqlite3
sqlite3_opt_vtable.go
mPrintf
func mPrintf(format, arg string) *C.char { cf := C.CString(format) defer C.free(unsafe.Pointer(cf)) ca := C.CString(arg) defer C.free(unsafe.Pointer(ca)) return C._sqlite3_mprintf(cf, ca) }
go
func mPrintf(format, arg string) *C.char { cf := C.CString(format) defer C.free(unsafe.Pointer(cf)) ca := C.CString(arg) defer C.free(unsafe.Pointer(ca)) return C._sqlite3_mprintf(cf, ca) }
[ "func", "mPrintf", "(", "format", ",", "arg", "string", ")", "*", "C", ".", "char", "{", "cf", ":=", "C", ".", "CString", "(", "format", ")", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "cf", ")", ")", "\n", "ca", ":=",...
// mPrintf is a utility wrapper around sqlite3_mprintf
[ "mPrintf", "is", "a", "utility", "wrapper", "around", "sqlite3_mprintf" ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3_opt_vtable.go#L340-L346
train
mattn/go-sqlite3
sqlite3.go
Version
func Version() (libVersion string, libVersionNumber int, sourceID string) { libVersion = C.GoString(C.sqlite3_libversion()) libVersionNumber = int(C.sqlite3_libversion_number()) sourceID = C.GoString(C.sqlite3_sourceid()) return libVersion, libVersionNumber, sourceID }
go
func Version() (libVersion string, libVersionNumber int, sourceID string) { libVersion = C.GoString(C.sqlite3_libversion()) libVersionNumber = int(C.sqlite3_libversion_number()) sourceID = C.GoString(C.sqlite3_sourceid()) return libVersion, libVersionNumber, sourceID }
[ "func", "Version", "(", ")", "(", "libVersion", "string", ",", "libVersionNumber", "int", ",", "sourceID", "string", ")", "{", "libVersion", "=", "C", ".", "GoString", "(", "C", ".", "sqlite3_libversion", "(", ")", ")", "\n", "libVersionNumber", "=", "int"...
// Version returns SQLite library version information.
[ "Version", "returns", "SQLite", "library", "version", "information", "." ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3.go#L234-L239
train
mattn/go-sqlite3
sqlite3.go
Commit
func (tx *SQLiteTx) Commit() error { _, err := tx.c.exec(context.Background(), "COMMIT", nil) if err != nil && err.(Error).Code == C.SQLITE_BUSY { // sqlite3 will leave the transaction open in this scenario. // However, database/sql considers the transaction complete once we // return from Commit() - we must clean up to honour its semantics. tx.c.exec(context.Background(), "ROLLBACK", nil) } return err }
go
func (tx *SQLiteTx) Commit() error { _, err := tx.c.exec(context.Background(), "COMMIT", nil) if err != nil && err.(Error).Code == C.SQLITE_BUSY { // sqlite3 will leave the transaction open in this scenario. // However, database/sql considers the transaction complete once we // return from Commit() - we must clean up to honour its semantics. tx.c.exec(context.Background(), "ROLLBACK", nil) } return err }
[ "func", "(", "tx", "*", "SQLiteTx", ")", "Commit", "(", ")", "error", "{", "_", ",", "err", ":=", "tx", ".", "c", ".", "exec", "(", "context", ".", "Background", "(", ")", ",", "\"", "\"", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "&&"...
// Commit transaction.
[ "Commit", "transaction", "." ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3.go#L436-L445
train
mattn/go-sqlite3
sqlite3.go
Rollback
func (tx *SQLiteTx) Rollback() error { _, err := tx.c.exec(context.Background(), "ROLLBACK", nil) return err }
go
func (tx *SQLiteTx) Rollback() error { _, err := tx.c.exec(context.Background(), "ROLLBACK", nil) return err }
[ "func", "(", "tx", "*", "SQLiteTx", ")", "Rollback", "(", ")", "error", "{", "_", ",", "err", ":=", "tx", ".", "c", ".", "exec", "(", "context", ".", "Background", "(", ")", ",", "\"", "\"", ",", "nil", ")", "\n", "return", "err", "\n", "}" ]
// Rollback transaction.
[ "Rollback", "transaction", "." ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3.go#L448-L451
train
mattn/go-sqlite3
sqlite3.go
AutoCommit
func (c *SQLiteConn) AutoCommit() bool { c.mu.Lock() defer c.mu.Unlock() return int(C.sqlite3_get_autocommit(c.db)) != 0 }
go
func (c *SQLiteConn) AutoCommit() bool { c.mu.Lock() defer c.mu.Unlock() return int(C.sqlite3_get_autocommit(c.db)) != 0 }
[ "func", "(", "c", "*", "SQLiteConn", ")", "AutoCommit", "(", ")", "bool", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "int", "(", "C", ".", "sqlite3_get_autocommit", "(", "c"...
// AutoCommit return which currently auto commit or not.
[ "AutoCommit", "return", "which", "currently", "auto", "commit", "or", "not", "." ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3.go#L742-L746
train
mattn/go-sqlite3
sqlite3.go
Query
func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, error) { list := make([]namedValue, len(args)) for i, v := range args { list[i] = namedValue{ Ordinal: i + 1, Value: v, } } return c.query(context.Background(), query, list) }
go
func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, error) { list := make([]namedValue, len(args)) for i, v := range args { list[i] = namedValue{ Ordinal: i + 1, Value: v, } } return c.query(context.Background(), query, list) }
[ "func", "(", "c", "*", "SQLiteConn", ")", "Query", "(", "query", "string", ",", "args", "[", "]", "driver", ".", "Value", ")", "(", "driver", ".", "Rows", ",", "error", ")", "{", "list", ":=", "make", "(", "[", "]", "namedValue", ",", "len", "(",...
// Query implements Queryer.
[ "Query", "implements", "Queryer", "." ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3.go#L817-L826
train
mattn/go-sqlite3
sqlite3.go
Begin
func (c *SQLiteConn) Begin() (driver.Tx, error) { return c.begin(context.Background()) }
go
func (c *SQLiteConn) Begin() (driver.Tx, error) { return c.begin(context.Background()) }
[ "func", "(", "c", "*", "SQLiteConn", ")", "Begin", "(", ")", "(", "driver", ".", "Tx", ",", "error", ")", "{", "return", "c", ".", "begin", "(", "context", ".", "Background", "(", ")", ")", "\n", "}" ]
// Begin transaction.
[ "Begin", "transaction", "." ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3.go#L861-L863
train
mattn/go-sqlite3
sqlite3.go
Close
func (c *SQLiteConn) Close() error { rv := C.sqlite3_close_v2(c.db) if rv != C.SQLITE_OK { return c.lastError() } deleteHandles(c) c.mu.Lock() c.db = nil c.mu.Unlock() runtime.SetFinalizer(c, nil) return nil }
go
func (c *SQLiteConn) Close() error { rv := C.sqlite3_close_v2(c.db) if rv != C.SQLITE_OK { return c.lastError() } deleteHandles(c) c.mu.Lock() c.db = nil c.mu.Unlock() runtime.SetFinalizer(c, nil) return nil }
[ "func", "(", "c", "*", "SQLiteConn", ")", "Close", "(", ")", "error", "{", "rv", ":=", "C", ".", "sqlite3_close_v2", "(", "c", ".", "db", ")", "\n", "if", "rv", "!=", "C", ".", "SQLITE_OK", "{", "return", "c", ".", "lastError", "(", ")", "\n", ...
// Close the connection.
[ "Close", "the", "connection", "." ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3.go#L1650-L1661
train
mattn/go-sqlite3
sqlite3.go
Prepare
func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error) { return c.prepare(context.Background(), query) }
go
func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error) { return c.prepare(context.Background(), query) }
[ "func", "(", "c", "*", "SQLiteConn", ")", "Prepare", "(", "query", "string", ")", "(", "driver", ".", "Stmt", ",", "error", ")", "{", "return", "c", ".", "prepare", "(", "context", ".", "Background", "(", ")", ",", "query", ")", "\n", "}" ]
// Prepare the query string. Return a new statement.
[ "Prepare", "the", "query", "string", ".", "Return", "a", "new", "statement", "." ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3.go#L1673-L1675
train
mattn/go-sqlite3
sqlite3.go
Close
func (s *SQLiteStmt) Close() error { s.mu.Lock() defer s.mu.Unlock() if s.closed { return nil } s.closed = true if !s.c.dbConnOpen() { return errors.New("sqlite statement with already closed database connection") } rv := C.sqlite3_finalize(s.s) s.s = nil if rv != C.SQLITE_OK { return s.c.lastError() } runtime.SetFinalizer(s, nil) return nil }
go
func (s *SQLiteStmt) Close() error { s.mu.Lock() defer s.mu.Unlock() if s.closed { return nil } s.closed = true if !s.c.dbConnOpen() { return errors.New("sqlite statement with already closed database connection") } rv := C.sqlite3_finalize(s.s) s.s = nil if rv != C.SQLITE_OK { return s.c.lastError() } runtime.SetFinalizer(s, nil) return nil }
[ "func", "(", "s", "*", "SQLiteStmt", ")", "Close", "(", ")", "error", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "s", ".", "closed", "{", "return", "nil", "\n", "}", "\n", ...
// Close the statement.
[ "Close", "the", "statement", "." ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3.go#L1737-L1754
train
mattn/go-sqlite3
sqlite3.go
Query
func (s *SQLiteStmt) Query(args []driver.Value) (driver.Rows, error) { list := make([]namedValue, len(args)) for i, v := range args { list[i] = namedValue{ Ordinal: i + 1, Value: v, } } return s.query(context.Background(), list) }
go
func (s *SQLiteStmt) Query(args []driver.Value) (driver.Rows, error) { list := make([]namedValue, len(args)) for i, v := range args { list[i] = namedValue{ Ordinal: i + 1, Value: v, } } return s.query(context.Background(), list) }
[ "func", "(", "s", "*", "SQLiteStmt", ")", "Query", "(", "args", "[", "]", "driver", ".", "Value", ")", "(", "driver", ".", "Rows", ",", "error", ")", "{", "list", ":=", "make", "(", "[", "]", "namedValue", ",", "len", "(", "args", ")", ")", "\n...
// Query the statement with arguments. Return records.
[ "Query", "the", "statement", "with", "arguments", ".", "Return", "records", "." ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3.go#L1826-L1835
train
mattn/go-sqlite3
sqlite3.go
Exec
func (s *SQLiteStmt) Exec(args []driver.Value) (driver.Result, error) { list := make([]namedValue, len(args)) for i, v := range args { list[i] = namedValue{ Ordinal: i + 1, Value: v, } } return s.exec(context.Background(), list) }
go
func (s *SQLiteStmt) Exec(args []driver.Value) (driver.Result, error) { list := make([]namedValue, len(args)) for i, v := range args { list[i] = namedValue{ Ordinal: i + 1, Value: v, } } return s.exec(context.Background(), list) }
[ "func", "(", "s", "*", "SQLiteStmt", ")", "Exec", "(", "args", "[", "]", "driver", ".", "Value", ")", "(", "driver", ".", "Result", ",", "error", ")", "{", "list", ":=", "make", "(", "[", "]", "namedValue", ",", "len", "(", "args", ")", ")", "\...
// Exec execute the statement with arguments. Return result object.
[ "Exec", "execute", "the", "statement", "with", "arguments", ".", "Return", "result", "object", "." ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3.go#L1881-L1890
train
mattn/go-sqlite3
sqlite3.go
Close
func (rc *SQLiteRows) Close() error { rc.s.mu.Lock() if rc.s.closed || rc.closed { rc.s.mu.Unlock() return nil } rc.closed = true if rc.done != nil { close(rc.done) } if rc.cls { rc.s.mu.Unlock() return rc.s.Close() } rv := C.sqlite3_reset(rc.s.s) if rv != C.SQLITE_OK { rc.s.mu.Unlock() return rc.s.c.lastError() } rc.s.mu.Unlock() return nil }
go
func (rc *SQLiteRows) Close() error { rc.s.mu.Lock() if rc.s.closed || rc.closed { rc.s.mu.Unlock() return nil } rc.closed = true if rc.done != nil { close(rc.done) } if rc.cls { rc.s.mu.Unlock() return rc.s.Close() } rv := C.sqlite3_reset(rc.s.s) if rv != C.SQLITE_OK { rc.s.mu.Unlock() return rc.s.c.lastError() } rc.s.mu.Unlock() return nil }
[ "func", "(", "rc", "*", "SQLiteRows", ")", "Close", "(", ")", "error", "{", "rc", ".", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "rc", ".", "s", ".", "closed", "||", "rc", ".", "closed", "{", "rc", ".", "s", ".", "mu", ".", "Unlock...
// Close the rows.
[ "Close", "the", "rows", "." ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3.go#L1928-L1949
train
mattn/go-sqlite3
sqlite3.go
Columns
func (rc *SQLiteRows) Columns() []string { rc.s.mu.Lock() defer rc.s.mu.Unlock() if rc.s.s != nil && rc.nc != len(rc.cols) { rc.cols = make([]string, rc.nc) for i := 0; i < rc.nc; i++ { rc.cols[i] = C.GoString(C.sqlite3_column_name(rc.s.s, C.int(i))) } } return rc.cols }
go
func (rc *SQLiteRows) Columns() []string { rc.s.mu.Lock() defer rc.s.mu.Unlock() if rc.s.s != nil && rc.nc != len(rc.cols) { rc.cols = make([]string, rc.nc) for i := 0; i < rc.nc; i++ { rc.cols[i] = C.GoString(C.sqlite3_column_name(rc.s.s, C.int(i))) } } return rc.cols }
[ "func", "(", "rc", "*", "SQLiteRows", ")", "Columns", "(", ")", "[", "]", "string", "{", "rc", ".", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "rc", ".", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "rc", ".", "s", ".", ...
// Columns return column names.
[ "Columns", "return", "column", "names", "." ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3.go#L1952-L1962
train
mattn/go-sqlite3
sqlite3.go
DeclTypes
func (rc *SQLiteRows) DeclTypes() []string { rc.s.mu.Lock() defer rc.s.mu.Unlock() return rc.declTypes() }
go
func (rc *SQLiteRows) DeclTypes() []string { rc.s.mu.Lock() defer rc.s.mu.Unlock() return rc.declTypes() }
[ "func", "(", "rc", "*", "SQLiteRows", ")", "DeclTypes", "(", ")", "[", "]", "string", "{", "rc", ".", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "rc", ".", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "rc", ".", "declTy...
// DeclTypes return column types.
[ "DeclTypes", "return", "column", "types", "." ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3.go#L1975-L1979
train
mattn/go-sqlite3
sqlite3_func_crypt.go
CryptEncoderSSHA1
func CryptEncoderSSHA1(salt string) func(pass []byte, hash interface{}) []byte { return func(pass []byte, hash interface{}) []byte { s := []byte(salt) p := append(pass, s...) h := sha1.Sum(p) return h[:] } }
go
func CryptEncoderSSHA1(salt string) func(pass []byte, hash interface{}) []byte { return func(pass []byte, hash interface{}) []byte { s := []byte(salt) p := append(pass, s...) h := sha1.Sum(p) return h[:] } }
[ "func", "CryptEncoderSSHA1", "(", "salt", "string", ")", "func", "(", "pass", "[", "]", "byte", ",", "hash", "interface", "{", "}", ")", "[", "]", "byte", "{", "return", "func", "(", "pass", "[", "]", "byte", ",", "hash", "interface", "{", "}", ")"...
// CryptEncoderSSHA1 encodes a password with SHA1 with the // configured salt.
[ "CryptEncoderSSHA1", "encodes", "a", "password", "with", "SHA1", "with", "the", "configured", "salt", "." ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3_func_crypt.go#L60-L67
train
mattn/go-sqlite3
sqlite3_func_crypt.go
CryptEncoderSHA256
func CryptEncoderSHA256(pass []byte, hash interface{}) []byte { h := sha256.Sum256(pass) return h[:] }
go
func CryptEncoderSHA256(pass []byte, hash interface{}) []byte { h := sha256.Sum256(pass) return h[:] }
[ "func", "CryptEncoderSHA256", "(", "pass", "[", "]", "byte", ",", "hash", "interface", "{", "}", ")", "[", "]", "byte", "{", "h", ":=", "sha256", ".", "Sum256", "(", "pass", ")", "\n", "return", "h", "[", ":", "]", "\n", "}" ]
// CryptEncoderSHA256 encodes a password with SHA256
[ "CryptEncoderSHA256", "encodes", "a", "password", "with", "SHA256" ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3_func_crypt.go#L70-L73
train
mattn/go-sqlite3
sqlite3_func_crypt.go
CryptEncoderSSHA256
func CryptEncoderSSHA256(salt string) func(pass []byte, hash interface{}) []byte { return func(pass []byte, hash interface{}) []byte { s := []byte(salt) p := append(pass, s...) h := sha256.Sum256(p) return h[:] } }
go
func CryptEncoderSSHA256(salt string) func(pass []byte, hash interface{}) []byte { return func(pass []byte, hash interface{}) []byte { s := []byte(salt) p := append(pass, s...) h := sha256.Sum256(p) return h[:] } }
[ "func", "CryptEncoderSSHA256", "(", "salt", "string", ")", "func", "(", "pass", "[", "]", "byte", ",", "hash", "interface", "{", "}", ")", "[", "]", "byte", "{", "return", "func", "(", "pass", "[", "]", "byte", ",", "hash", "interface", "{", "}", "...
// CryptEncoderSSHA256 encodes a password with SHA256 // with the configured salt
[ "CryptEncoderSSHA256", "encodes", "a", "password", "with", "SHA256", "with", "the", "configured", "salt" ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3_func_crypt.go#L77-L84
train
mattn/go-sqlite3
sqlite3_func_crypt.go
CryptEncoderSHA384
func CryptEncoderSHA384(pass []byte, hash interface{}) []byte { h := sha512.Sum384(pass) return h[:] }
go
func CryptEncoderSHA384(pass []byte, hash interface{}) []byte { h := sha512.Sum384(pass) return h[:] }
[ "func", "CryptEncoderSHA384", "(", "pass", "[", "]", "byte", ",", "hash", "interface", "{", "}", ")", "[", "]", "byte", "{", "h", ":=", "sha512", ".", "Sum384", "(", "pass", ")", "\n", "return", "h", "[", ":", "]", "\n", "}" ]
// CryptEncoderSHA384 encodes a password with SHA384
[ "CryptEncoderSHA384", "encodes", "a", "password", "with", "SHA384" ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3_func_crypt.go#L87-L90
train
mattn/go-sqlite3
sqlite3_func_crypt.go
CryptEncoderSSHA384
func CryptEncoderSSHA384(salt string) func(pass []byte, hash interface{}) []byte { return func(pass []byte, hash interface{}) []byte { s := []byte(salt) p := append(pass, s...) h := sha512.Sum384(p) return h[:] } }
go
func CryptEncoderSSHA384(salt string) func(pass []byte, hash interface{}) []byte { return func(pass []byte, hash interface{}) []byte { s := []byte(salt) p := append(pass, s...) h := sha512.Sum384(p) return h[:] } }
[ "func", "CryptEncoderSSHA384", "(", "salt", "string", ")", "func", "(", "pass", "[", "]", "byte", ",", "hash", "interface", "{", "}", ")", "[", "]", "byte", "{", "return", "func", "(", "pass", "[", "]", "byte", ",", "hash", "interface", "{", "}", "...
// CryptEncoderSSHA384 encodes a password with SHA384 // with the configured salt
[ "CryptEncoderSSHA384", "encodes", "a", "password", "with", "SHA384", "with", "the", "configured", "salt" ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3_func_crypt.go#L94-L101
train
mattn/go-sqlite3
sqlite3_func_crypt.go
CryptEncoderSHA512
func CryptEncoderSHA512(pass []byte, hash interface{}) []byte { h := sha512.Sum512(pass) return h[:] }
go
func CryptEncoderSHA512(pass []byte, hash interface{}) []byte { h := sha512.Sum512(pass) return h[:] }
[ "func", "CryptEncoderSHA512", "(", "pass", "[", "]", "byte", ",", "hash", "interface", "{", "}", ")", "[", "]", "byte", "{", "h", ":=", "sha512", ".", "Sum512", "(", "pass", ")", "\n", "return", "h", "[", ":", "]", "\n", "}" ]
// CryptEncoderSHA512 encodes a password with SHA512
[ "CryptEncoderSHA512", "encodes", "a", "password", "with", "SHA512" ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3_func_crypt.go#L104-L107
train
mattn/go-sqlite3
sqlite3_func_crypt.go
CryptEncoderSSHA512
func CryptEncoderSSHA512(salt string) func(pass []byte, hash interface{}) []byte { return func(pass []byte, hash interface{}) []byte { s := []byte(salt) p := append(pass, s...) h := sha512.Sum512(p) return h[:] } }
go
func CryptEncoderSSHA512(salt string) func(pass []byte, hash interface{}) []byte { return func(pass []byte, hash interface{}) []byte { s := []byte(salt) p := append(pass, s...) h := sha512.Sum512(p) return h[:] } }
[ "func", "CryptEncoderSSHA512", "(", "salt", "string", ")", "func", "(", "pass", "[", "]", "byte", ",", "hash", "interface", "{", "}", ")", "[", "]", "byte", "{", "return", "func", "(", "pass", "[", "]", "byte", ",", "hash", "interface", "{", "}", "...
// CryptEncoderSSHA512 encodes a password with SHA512 // with the configured salt
[ "CryptEncoderSSHA512", "encodes", "a", "password", "with", "SHA512", "with", "the", "configured", "salt" ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3_func_crypt.go#L111-L118
train
mattn/go-sqlite3
sqlite3_go18.go
Ping
func (c *SQLiteConn) Ping(ctx context.Context) error { if c.db == nil { return errors.New("Connection was closed") } return nil }
go
func (c *SQLiteConn) Ping(ctx context.Context) error { if c.db == nil { return errors.New("Connection was closed") } return nil }
[ "func", "(", "c", "*", "SQLiteConn", ")", "Ping", "(", "ctx", "context", ".", "Context", ")", "error", "{", "if", "c", ".", "db", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}...
// Ping implement Pinger.
[ "Ping", "implement", "Pinger", "." ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3_go18.go#L19-L24
train
mattn/go-sqlite3
sqlite3_go18.go
PrepareContext
func (c *SQLiteConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { return c.prepare(ctx, query) }
go
func (c *SQLiteConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { return c.prepare(ctx, query) }
[ "func", "(", "c", "*", "SQLiteConn", ")", "PrepareContext", "(", "ctx", "context", ".", "Context", ",", "query", "string", ")", "(", "driver", ".", "Stmt", ",", "error", ")", "{", "return", "c", ".", "prepare", "(", "ctx", ",", "query", ")", "\n", ...
// PrepareContext implement ConnPrepareContext.
[ "PrepareContext", "implement", "ConnPrepareContext", "." ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3_go18.go#L45-L47
train
mattn/go-sqlite3
sqlite3_go18.go
BeginTx
func (c *SQLiteConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { return c.begin(ctx) }
go
func (c *SQLiteConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { return c.begin(ctx) }
[ "func", "(", "c", "*", "SQLiteConn", ")", "BeginTx", "(", "ctx", "context", ".", "Context", ",", "opts", "driver", ".", "TxOptions", ")", "(", "driver", ".", "Tx", ",", "error", ")", "{", "return", "c", ".", "begin", "(", "ctx", ")", "\n", "}" ]
// BeginTx implement ConnBeginTx.
[ "BeginTx", "implement", "ConnBeginTx", "." ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3_go18.go#L50-L52
train
mattn/go-sqlite3
sqlite3_load_extension.go
LoadExtension
func (c *SQLiteConn) LoadExtension(lib string, entry string) error { rv := C.sqlite3_enable_load_extension(c.db, 1) if rv != C.SQLITE_OK { return errors.New(C.GoString(C.sqlite3_errmsg(c.db))) } clib := C.CString(lib) defer C.free(unsafe.Pointer(clib)) centry := C.CString(entry) defer C.free(unsafe.Pointer(centry)) rv = C.sqlite3_load_extension(c.db, clib, centry, nil) if rv != C.SQLITE_OK { return errors.New(C.GoString(C.sqlite3_errmsg(c.db))) } rv = C.sqlite3_enable_load_extension(c.db, 0) if rv != C.SQLITE_OK { return errors.New(C.GoString(C.sqlite3_errmsg(c.db))) } return nil }
go
func (c *SQLiteConn) LoadExtension(lib string, entry string) error { rv := C.sqlite3_enable_load_extension(c.db, 1) if rv != C.SQLITE_OK { return errors.New(C.GoString(C.sqlite3_errmsg(c.db))) } clib := C.CString(lib) defer C.free(unsafe.Pointer(clib)) centry := C.CString(entry) defer C.free(unsafe.Pointer(centry)) rv = C.sqlite3_load_extension(c.db, clib, centry, nil) if rv != C.SQLITE_OK { return errors.New(C.GoString(C.sqlite3_errmsg(c.db))) } rv = C.sqlite3_enable_load_extension(c.db, 0) if rv != C.SQLITE_OK { return errors.New(C.GoString(C.sqlite3_errmsg(c.db))) } return nil }
[ "func", "(", "c", "*", "SQLiteConn", ")", "LoadExtension", "(", "lib", "string", ",", "entry", "string", ")", "error", "{", "rv", ":=", "C", ".", "sqlite3_enable_load_extension", "(", "c", ".", "db", ",", "1", ")", "\n", "if", "rv", "!=", "C", ".", ...
// LoadExtension load the sqlite3 extension.
[ "LoadExtension", "load", "the", "sqlite3", "extension", "." ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3_load_extension.go#L48-L70
train
mattn/go-sqlite3
sqlite3_opt_userauth.go
AuthEnabled
func (c *SQLiteConn) AuthEnabled() (exists bool) { rv := c.authEnabled() if rv == 1 { exists = true } return }
go
func (c *SQLiteConn) AuthEnabled() (exists bool) { rv := c.authEnabled() if rv == 1 { exists = true } return }
[ "func", "(", "c", "*", "SQLiteConn", ")", "AuthEnabled", "(", ")", "(", "exists", "bool", ")", "{", "rv", ":=", "c", ".", "authEnabled", "(", ")", "\n", "if", "rv", "==", "1", "{", "exists", "=", "true", "\n", "}", "\n\n", "return", "\n", "}" ]
// AuthEnabled checks if the database is protected by user authentication
[ "AuthEnabled", "checks", "if", "the", "database", "is", "protected", "by", "user", "authentication" ]
5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3
https://github.com/mattn/go-sqlite3/blob/5994cc52dfa89a4ee21ac891b06fbc1ea02c52d3/sqlite3_opt_userauth.go#L268-L275
train
gliderlabs/registrator
consul/consul.go
Ping
func (r *ConsulAdapter) Ping() error { status := r.client.Status() leader, err := status.Leader() if err != nil { return err } log.Println("consul: current leader ", leader) return nil }
go
func (r *ConsulAdapter) Ping() error { status := r.client.Status() leader, err := status.Leader() if err != nil { return err } log.Println("consul: current leader ", leader) return nil }
[ "func", "(", "r", "*", "ConsulAdapter", ")", "Ping", "(", ")", "error", "{", "status", ":=", "r", ".", "client", ".", "Status", "(", ")", "\n", "leader", ",", "err", ":=", "status", ".", "Leader", "(", ")", "\n", "if", "err", "!=", "nil", "{", ...
// Ping will try to connect to consul by attempting to retrieve the current leader.
[ "Ping", "will", "try", "to", "connect", "to", "consul", "by", "attempting", "to", "retrieve", "the", "current", "leader", "." ]
da90d170da9dd7e1a8d9a13429d44686dc3d118f
https://github.com/gliderlabs/registrator/blob/da90d170da9dd7e1a8d9a13429d44686dc3d118f/consul/consul.go#L69-L78
train
orcaman/concurrent-map
concurrent_map.go
New
func New() ConcurrentMap { m := make(ConcurrentMap, SHARD_COUNT) for i := 0; i < SHARD_COUNT; i++ { m[i] = &ConcurrentMapShared{items: make(map[string]interface{})} } return m }
go
func New() ConcurrentMap { m := make(ConcurrentMap, SHARD_COUNT) for i := 0; i < SHARD_COUNT; i++ { m[i] = &ConcurrentMapShared{items: make(map[string]interface{})} } return m }
[ "func", "New", "(", ")", "ConcurrentMap", "{", "m", ":=", "make", "(", "ConcurrentMap", ",", "SHARD_COUNT", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "SHARD_COUNT", ";", "i", "++", "{", "m", "[", "i", "]", "=", "&", "ConcurrentMapShared", "{...
// Creates a new concurrent map.
[ "Creates", "a", "new", "concurrent", "map", "." ]
2693aad1ed7517c2bb5b3a42cb8fde88b941d89d
https://github.com/orcaman/concurrent-map/blob/2693aad1ed7517c2bb5b3a42cb8fde88b941d89d/concurrent_map.go#L21-L27
train
orcaman/concurrent-map
concurrent_map.go
GetShard
func (m ConcurrentMap) GetShard(key string) *ConcurrentMapShared { return m[uint(fnv32(key))%uint(SHARD_COUNT)] }
go
func (m ConcurrentMap) GetShard(key string) *ConcurrentMapShared { return m[uint(fnv32(key))%uint(SHARD_COUNT)] }
[ "func", "(", "m", "ConcurrentMap", ")", "GetShard", "(", "key", "string", ")", "*", "ConcurrentMapShared", "{", "return", "m", "[", "uint", "(", "fnv32", "(", "key", ")", ")", "%", "uint", "(", "SHARD_COUNT", ")", "]", "\n", "}" ]
// GetShard returns shard under given key
[ "GetShard", "returns", "shard", "under", "given", "key" ]
2693aad1ed7517c2bb5b3a42cb8fde88b941d89d
https://github.com/orcaman/concurrent-map/blob/2693aad1ed7517c2bb5b3a42cb8fde88b941d89d/concurrent_map.go#L30-L32
train
orcaman/concurrent-map
concurrent_map.go
Set
func (m ConcurrentMap) Set(key string, value interface{}) { // Get map shard. shard := m.GetShard(key) shard.Lock() shard.items[key] = value shard.Unlock() }
go
func (m ConcurrentMap) Set(key string, value interface{}) { // Get map shard. shard := m.GetShard(key) shard.Lock() shard.items[key] = value shard.Unlock() }
[ "func", "(", "m", "ConcurrentMap", ")", "Set", "(", "key", "string", ",", "value", "interface", "{", "}", ")", "{", "// Get map shard.", "shard", ":=", "m", ".", "GetShard", "(", "key", ")", "\n", "shard", ".", "Lock", "(", ")", "\n", "shard", ".", ...
// Sets the given value under the specified key.
[ "Sets", "the", "given", "value", "under", "the", "specified", "key", "." ]
2693aad1ed7517c2bb5b3a42cb8fde88b941d89d
https://github.com/orcaman/concurrent-map/blob/2693aad1ed7517c2bb5b3a42cb8fde88b941d89d/concurrent_map.go#L44-L50
train
orcaman/concurrent-map
concurrent_map.go
Upsert
func (m ConcurrentMap) Upsert(key string, value interface{}, cb UpsertCb) (res interface{}) { shard := m.GetShard(key) shard.Lock() v, ok := shard.items[key] res = cb(ok, v, value) shard.items[key] = res shard.Unlock() return res }
go
func (m ConcurrentMap) Upsert(key string, value interface{}, cb UpsertCb) (res interface{}) { shard := m.GetShard(key) shard.Lock() v, ok := shard.items[key] res = cb(ok, v, value) shard.items[key] = res shard.Unlock() return res }
[ "func", "(", "m", "ConcurrentMap", ")", "Upsert", "(", "key", "string", ",", "value", "interface", "{", "}", ",", "cb", "UpsertCb", ")", "(", "res", "interface", "{", "}", ")", "{", "shard", ":=", "m", ".", "GetShard", "(", "key", ")", "\n", "shard...
// Insert or Update - updates existing element or inserts a new one using UpsertCb
[ "Insert", "or", "Update", "-", "updates", "existing", "element", "or", "inserts", "a", "new", "one", "using", "UpsertCb" ]
2693aad1ed7517c2bb5b3a42cb8fde88b941d89d
https://github.com/orcaman/concurrent-map/blob/2693aad1ed7517c2bb5b3a42cb8fde88b941d89d/concurrent_map.go#L59-L67
train
orcaman/concurrent-map
concurrent_map.go
SetIfAbsent
func (m ConcurrentMap) SetIfAbsent(key string, value interface{}) bool { // Get map shard. shard := m.GetShard(key) shard.Lock() _, ok := shard.items[key] if !ok { shard.items[key] = value } shard.Unlock() return !ok }
go
func (m ConcurrentMap) SetIfAbsent(key string, value interface{}) bool { // Get map shard. shard := m.GetShard(key) shard.Lock() _, ok := shard.items[key] if !ok { shard.items[key] = value } shard.Unlock() return !ok }
[ "func", "(", "m", "ConcurrentMap", ")", "SetIfAbsent", "(", "key", "string", ",", "value", "interface", "{", "}", ")", "bool", "{", "// Get map shard.", "shard", ":=", "m", ".", "GetShard", "(", "key", ")", "\n", "shard", ".", "Lock", "(", ")", "\n", ...
// Sets the given value under the specified key if no value was associated with it.
[ "Sets", "the", "given", "value", "under", "the", "specified", "key", "if", "no", "value", "was", "associated", "with", "it", "." ]
2693aad1ed7517c2bb5b3a42cb8fde88b941d89d
https://github.com/orcaman/concurrent-map/blob/2693aad1ed7517c2bb5b3a42cb8fde88b941d89d/concurrent_map.go#L70-L80
train
orcaman/concurrent-map
concurrent_map.go
Get
func (m ConcurrentMap) Get(key string) (interface{}, bool) { // Get shard shard := m.GetShard(key) shard.RLock() // Get item from shard. val, ok := shard.items[key] shard.RUnlock() return val, ok }
go
func (m ConcurrentMap) Get(key string) (interface{}, bool) { // Get shard shard := m.GetShard(key) shard.RLock() // Get item from shard. val, ok := shard.items[key] shard.RUnlock() return val, ok }
[ "func", "(", "m", "ConcurrentMap", ")", "Get", "(", "key", "string", ")", "(", "interface", "{", "}", ",", "bool", ")", "{", "// Get shard", "shard", ":=", "m", ".", "GetShard", "(", "key", ")", "\n", "shard", ".", "RLock", "(", ")", "\n", "// Get ...
// Get retrieves an element from map under given key.
[ "Get", "retrieves", "an", "element", "from", "map", "under", "given", "key", "." ]
2693aad1ed7517c2bb5b3a42cb8fde88b941d89d
https://github.com/orcaman/concurrent-map/blob/2693aad1ed7517c2bb5b3a42cb8fde88b941d89d/concurrent_map.go#L83-L91
train
orcaman/concurrent-map
concurrent_map.go
Count
func (m ConcurrentMap) Count() int { count := 0 for i := 0; i < SHARD_COUNT; i++ { shard := m[i] shard.RLock() count += len(shard.items) shard.RUnlock() } return count }
go
func (m ConcurrentMap) Count() int { count := 0 for i := 0; i < SHARD_COUNT; i++ { shard := m[i] shard.RLock() count += len(shard.items) shard.RUnlock() } return count }
[ "func", "(", "m", "ConcurrentMap", ")", "Count", "(", ")", "int", "{", "count", ":=", "0", "\n", "for", "i", ":=", "0", ";", "i", "<", "SHARD_COUNT", ";", "i", "++", "{", "shard", ":=", "m", "[", "i", "]", "\n", "shard", ".", "RLock", "(", ")...
// Count returns the number of elements within the map.
[ "Count", "returns", "the", "number", "of", "elements", "within", "the", "map", "." ]
2693aad1ed7517c2bb5b3a42cb8fde88b941d89d
https://github.com/orcaman/concurrent-map/blob/2693aad1ed7517c2bb5b3a42cb8fde88b941d89d/concurrent_map.go#L94-L103
train
orcaman/concurrent-map
concurrent_map.go
Has
func (m ConcurrentMap) Has(key string) bool { // Get shard shard := m.GetShard(key) shard.RLock() // See if element is within shard. _, ok := shard.items[key] shard.RUnlock() return ok }
go
func (m ConcurrentMap) Has(key string) bool { // Get shard shard := m.GetShard(key) shard.RLock() // See if element is within shard. _, ok := shard.items[key] shard.RUnlock() return ok }
[ "func", "(", "m", "ConcurrentMap", ")", "Has", "(", "key", "string", ")", "bool", "{", "// Get shard", "shard", ":=", "m", ".", "GetShard", "(", "key", ")", "\n", "shard", ".", "RLock", "(", ")", "\n", "// See if element is within shard.", "_", ",", "ok"...
// Looks up an item under specified key
[ "Looks", "up", "an", "item", "under", "specified", "key" ]
2693aad1ed7517c2bb5b3a42cb8fde88b941d89d
https://github.com/orcaman/concurrent-map/blob/2693aad1ed7517c2bb5b3a42cb8fde88b941d89d/concurrent_map.go#L106-L114
train
orcaman/concurrent-map
concurrent_map.go
Remove
func (m ConcurrentMap) Remove(key string) { // Try to get shard. shard := m.GetShard(key) shard.Lock() delete(shard.items, key) shard.Unlock() }
go
func (m ConcurrentMap) Remove(key string) { // Try to get shard. shard := m.GetShard(key) shard.Lock() delete(shard.items, key) shard.Unlock() }
[ "func", "(", "m", "ConcurrentMap", ")", "Remove", "(", "key", "string", ")", "{", "// Try to get shard.", "shard", ":=", "m", ".", "GetShard", "(", "key", ")", "\n", "shard", ".", "Lock", "(", ")", "\n", "delete", "(", "shard", ".", "items", ",", "ke...
// Remove removes an element from the map.
[ "Remove", "removes", "an", "element", "from", "the", "map", "." ]
2693aad1ed7517c2bb5b3a42cb8fde88b941d89d
https://github.com/orcaman/concurrent-map/blob/2693aad1ed7517c2bb5b3a42cb8fde88b941d89d/concurrent_map.go#L117-L123
train
orcaman/concurrent-map
concurrent_map.go
Pop
func (m ConcurrentMap) Pop(key string) (v interface{}, exists bool) { // Try to get shard. shard := m.GetShard(key) shard.Lock() v, exists = shard.items[key] delete(shard.items, key) shard.Unlock() return v, exists }
go
func (m ConcurrentMap) Pop(key string) (v interface{}, exists bool) { // Try to get shard. shard := m.GetShard(key) shard.Lock() v, exists = shard.items[key] delete(shard.items, key) shard.Unlock() return v, exists }
[ "func", "(", "m", "ConcurrentMap", ")", "Pop", "(", "key", "string", ")", "(", "v", "interface", "{", "}", ",", "exists", "bool", ")", "{", "// Try to get shard.", "shard", ":=", "m", ".", "GetShard", "(", "key", ")", "\n", "shard", ".", "Lock", "(",...
// Pop removes an element from the map and returns it
[ "Pop", "removes", "an", "element", "from", "the", "map", "and", "returns", "it" ]
2693aad1ed7517c2bb5b3a42cb8fde88b941d89d
https://github.com/orcaman/concurrent-map/blob/2693aad1ed7517c2bb5b3a42cb8fde88b941d89d/concurrent_map.go#L146-L154
train
orcaman/concurrent-map
concurrent_map.go
IterBuffered
func (m ConcurrentMap) IterBuffered() <-chan Tuple { chans := snapshot(m) total := 0 for _, c := range chans { total += cap(c) } ch := make(chan Tuple, total) go fanIn(chans, ch) return ch }
go
func (m ConcurrentMap) IterBuffered() <-chan Tuple { chans := snapshot(m) total := 0 for _, c := range chans { total += cap(c) } ch := make(chan Tuple, total) go fanIn(chans, ch) return ch }
[ "func", "(", "m", "ConcurrentMap", ")", "IterBuffered", "(", ")", "<-", "chan", "Tuple", "{", "chans", ":=", "snapshot", "(", "m", ")", "\n", "total", ":=", "0", "\n", "for", "_", ",", "c", ":=", "range", "chans", "{", "total", "+=", "cap", "(", ...
// IterBuffered returns a buffered iterator which could be used in a for range loop.
[ "IterBuffered", "returns", "a", "buffered", "iterator", "which", "could", "be", "used", "in", "a", "for", "range", "loop", "." ]
2693aad1ed7517c2bb5b3a42cb8fde88b941d89d
https://github.com/orcaman/concurrent-map/blob/2693aad1ed7517c2bb5b3a42cb8fde88b941d89d/concurrent_map.go#L178-L187
train
orcaman/concurrent-map
concurrent_map.go
snapshot
func snapshot(m ConcurrentMap) (chans []chan Tuple) { chans = make([]chan Tuple, SHARD_COUNT) wg := sync.WaitGroup{} wg.Add(SHARD_COUNT) // Foreach shard. for index, shard := range m { go func(index int, shard *ConcurrentMapShared) { // Foreach key, value pair. shard.RLock() chans[index] = make(chan Tuple, len(shard.items)) wg.Done() for key, val := range shard.items { chans[index] <- Tuple{key, val} } shard.RUnlock() close(chans[index]) }(index, shard) } wg.Wait() return chans }
go
func snapshot(m ConcurrentMap) (chans []chan Tuple) { chans = make([]chan Tuple, SHARD_COUNT) wg := sync.WaitGroup{} wg.Add(SHARD_COUNT) // Foreach shard. for index, shard := range m { go func(index int, shard *ConcurrentMapShared) { // Foreach key, value pair. shard.RLock() chans[index] = make(chan Tuple, len(shard.items)) wg.Done() for key, val := range shard.items { chans[index] <- Tuple{key, val} } shard.RUnlock() close(chans[index]) }(index, shard) } wg.Wait() return chans }
[ "func", "snapshot", "(", "m", "ConcurrentMap", ")", "(", "chans", "[", "]", "chan", "Tuple", ")", "{", "chans", "=", "make", "(", "[", "]", "chan", "Tuple", ",", "SHARD_COUNT", ")", "\n", "wg", ":=", "sync", ".", "WaitGroup", "{", "}", "\n", "wg", ...
// Returns a array of channels that contains elements in each shard, // which likely takes a snapshot of `m`. // It returns once the size of each buffered channel is determined, // before all the channels are populated using goroutines.
[ "Returns", "a", "array", "of", "channels", "that", "contains", "elements", "in", "each", "shard", "which", "likely", "takes", "a", "snapshot", "of", "m", ".", "It", "returns", "once", "the", "size", "of", "each", "buffered", "channel", "is", "determined", ...
2693aad1ed7517c2bb5b3a42cb8fde88b941d89d
https://github.com/orcaman/concurrent-map/blob/2693aad1ed7517c2bb5b3a42cb8fde88b941d89d/concurrent_map.go#L193-L213
train
orcaman/concurrent-map
concurrent_map.go
fanIn
func fanIn(chans []chan Tuple, out chan Tuple) { wg := sync.WaitGroup{} wg.Add(len(chans)) for _, ch := range chans { go func(ch chan Tuple) { for t := range ch { out <- t } wg.Done() }(ch) } wg.Wait() close(out) }
go
func fanIn(chans []chan Tuple, out chan Tuple) { wg := sync.WaitGroup{} wg.Add(len(chans)) for _, ch := range chans { go func(ch chan Tuple) { for t := range ch { out <- t } wg.Done() }(ch) } wg.Wait() close(out) }
[ "func", "fanIn", "(", "chans", "[", "]", "chan", "Tuple", ",", "out", "chan", "Tuple", ")", "{", "wg", ":=", "sync", ".", "WaitGroup", "{", "}", "\n", "wg", ".", "Add", "(", "len", "(", "chans", ")", ")", "\n", "for", "_", ",", "ch", ":=", "r...
// fanIn reads elements from channels `chans` into channel `out`
[ "fanIn", "reads", "elements", "from", "channels", "chans", "into", "channel", "out" ]
2693aad1ed7517c2bb5b3a42cb8fde88b941d89d
https://github.com/orcaman/concurrent-map/blob/2693aad1ed7517c2bb5b3a42cb8fde88b941d89d/concurrent_map.go#L216-L229
train
orcaman/concurrent-map
concurrent_map.go
IterCb
func (m ConcurrentMap) IterCb(fn IterCb) { for idx := range m { shard := (m)[idx] shard.RLock() for key, value := range shard.items { fn(key, value) } shard.RUnlock() } }
go
func (m ConcurrentMap) IterCb(fn IterCb) { for idx := range m { shard := (m)[idx] shard.RLock() for key, value := range shard.items { fn(key, value) } shard.RUnlock() } }
[ "func", "(", "m", "ConcurrentMap", ")", "IterCb", "(", "fn", "IterCb", ")", "{", "for", "idx", ":=", "range", "m", "{", "shard", ":=", "(", "m", ")", "[", "idx", "]", "\n", "shard", ".", "RLock", "(", ")", "\n", "for", "key", ",", "value", ":="...
// Callback based iterator, cheapest way to read // all elements in a map.
[ "Callback", "based", "iterator", "cheapest", "way", "to", "read", "all", "elements", "in", "a", "map", "." ]
2693aad1ed7517c2bb5b3a42cb8fde88b941d89d
https://github.com/orcaman/concurrent-map/blob/2693aad1ed7517c2bb5b3a42cb8fde88b941d89d/concurrent_map.go#L251-L260
train
orcaman/concurrent-map
concurrent_map.go
MarshalJSON
func (m ConcurrentMap) MarshalJSON() ([]byte, error) { // Create a temporary map, which will hold all item spread across shards. tmp := make(map[string]interface{}) // Insert items to temporary map. for item := range m.IterBuffered() { tmp[item.Key] = item.Val } return json.Marshal(tmp) }
go
func (m ConcurrentMap) MarshalJSON() ([]byte, error) { // Create a temporary map, which will hold all item spread across shards. tmp := make(map[string]interface{}) // Insert items to temporary map. for item := range m.IterBuffered() { tmp[item.Key] = item.Val } return json.Marshal(tmp) }
[ "func", "(", "m", "ConcurrentMap", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// Create a temporary map, which will hold all item spread across shards.", "tmp", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}...
//Reviles ConcurrentMap "private" variables to json marshal.
[ "Reviles", "ConcurrentMap", "private", "variables", "to", "json", "marshal", "." ]
2693aad1ed7517c2bb5b3a42cb8fde88b941d89d
https://github.com/orcaman/concurrent-map/blob/2693aad1ed7517c2bb5b3a42cb8fde88b941d89d/concurrent_map.go#L294-L303
train