id
int32 0
167k
| 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
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
1,000 | namsral/flag | extras.go | NewFlagSetWithEnvPrefix | func NewFlagSetWithEnvPrefix(name string, prefix string, errorHandling ErrorHandling) *FlagSet {
f := NewFlagSet(name, errorHandling)
f.envPrefix = prefix
return f
} | go | func NewFlagSetWithEnvPrefix(name string, prefix string, errorHandling ErrorHandling) *FlagSet {
f := NewFlagSet(name, errorHandling)
f.envPrefix = prefix
return f
} | [
"func",
"NewFlagSetWithEnvPrefix",
"(",
"name",
"string",
",",
"prefix",
"string",
",",
"errorHandling",
"ErrorHandling",
")",
"*",
"FlagSet",
"{",
"f",
":=",
"NewFlagSet",
"(",
"name",
",",
"errorHandling",
")",
"\n",
"f",
".",
"envPrefix",
"=",
"prefix",
"\n",
"return",
"f",
"\n",
"}"
] | // NewFlagSetWithEnvPrefix returns a new empty flag set with the specified name,
// environment variable prefix, and error handling property. | [
"NewFlagSetWithEnvPrefix",
"returns",
"a",
"new",
"empty",
"flag",
"set",
"with",
"the",
"specified",
"name",
"environment",
"variable",
"prefix",
"and",
"error",
"handling",
"property",
"."
] | 67f268f20922975c067ed799e4be6bacf152208c | https://github.com/namsral/flag/blob/67f268f20922975c067ed799e4be6bacf152208c/extras.go#L91-L95 |
1,001 | namsral/flag | flag.go | VisitAll | func (f *FlagSet) VisitAll(fn func(*Flag)) {
for _, flag := range sortFlags(f.formal) {
fn(flag)
}
} | go | func (f *FlagSet) VisitAll(fn func(*Flag)) {
for _, flag := range sortFlags(f.formal) {
fn(flag)
}
} | [
"func",
"(",
"f",
"*",
"FlagSet",
")",
"VisitAll",
"(",
"fn",
"func",
"(",
"*",
"Flag",
")",
")",
"{",
"for",
"_",
",",
"flag",
":=",
"range",
"sortFlags",
"(",
"f",
".",
"formal",
")",
"{",
"fn",
"(",
"flag",
")",
"\n",
"}",
"\n",
"}"
] | // VisitAll visits the flags in lexicographical order, calling fn for each.
// It visits all flags, even those not set. | [
"VisitAll",
"visits",
"the",
"flags",
"in",
"lexicographical",
"order",
"calling",
"fn",
"for",
"each",
".",
"It",
"visits",
"all",
"flags",
"even",
"those",
"not",
"set",
"."
] | 67f268f20922975c067ed799e4be6bacf152208c | https://github.com/namsral/flag/blob/67f268f20922975c067ed799e4be6bacf152208c/flag.go#L323-L327 |
1,002 | namsral/flag | flag.go | isZeroValue | func isZeroValue(flag *Flag, value string) bool {
// Build a zero value of the flag's Value type, and see if the
// result of calling its String method equals the value passed in.
// This works unless the Value type is itself an interface type.
typ := reflect.TypeOf(flag.Value)
var z reflect.Value
if typ.Kind() == reflect.Ptr {
z = reflect.New(typ.Elem())
} else {
z = reflect.Zero(typ)
}
if value == z.Interface().(Value).String() {
return true
}
switch value {
case "false":
return true
case "":
return true
case "0":
return true
}
return false
} | go | func isZeroValue(flag *Flag, value string) bool {
// Build a zero value of the flag's Value type, and see if the
// result of calling its String method equals the value passed in.
// This works unless the Value type is itself an interface type.
typ := reflect.TypeOf(flag.Value)
var z reflect.Value
if typ.Kind() == reflect.Ptr {
z = reflect.New(typ.Elem())
} else {
z = reflect.Zero(typ)
}
if value == z.Interface().(Value).String() {
return true
}
switch value {
case "false":
return true
case "":
return true
case "0":
return true
}
return false
} | [
"func",
"isZeroValue",
"(",
"flag",
"*",
"Flag",
",",
"value",
"string",
")",
"bool",
"{",
"// Build a zero value of the flag's Value type, and see if the",
"// result of calling its String method equals the value passed in.",
"// This works unless the Value type is itself an interface type.",
"typ",
":=",
"reflect",
".",
"TypeOf",
"(",
"flag",
".",
"Value",
")",
"\n",
"var",
"z",
"reflect",
".",
"Value",
"\n",
"if",
"typ",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"{",
"z",
"=",
"reflect",
".",
"New",
"(",
"typ",
".",
"Elem",
"(",
")",
")",
"\n",
"}",
"else",
"{",
"z",
"=",
"reflect",
".",
"Zero",
"(",
"typ",
")",
"\n",
"}",
"\n",
"if",
"value",
"==",
"z",
".",
"Interface",
"(",
")",
".",
"(",
"Value",
")",
".",
"String",
"(",
")",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"switch",
"value",
"{",
"case",
"\"",
"\"",
":",
"return",
"true",
"\n",
"case",
"\"",
"\"",
":",
"return",
"true",
"\n",
"case",
"\"",
"\"",
":",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // isZeroValue guesses whether the string represents the zero
// value for a flag. It is not accurate but in practice works OK. | [
"isZeroValue",
"guesses",
"whether",
"the",
"string",
"represents",
"the",
"zero",
"value",
"for",
"a",
"flag",
".",
"It",
"is",
"not",
"accurate",
"but",
"in",
"practice",
"works",
"OK",
"."
] | 67f268f20922975c067ed799e4be6bacf152208c | https://github.com/namsral/flag/blob/67f268f20922975c067ed799e4be6bacf152208c/flag.go#L384-L408 |
1,003 | namsral/flag | flag.go | DurationVar | func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
f.Var(newDurationValue(value, p), name, usage)
} | go | func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
f.Var(newDurationValue(value, p), name, usage)
} | [
"func",
"(",
"f",
"*",
"FlagSet",
")",
"DurationVar",
"(",
"p",
"*",
"time",
".",
"Duration",
",",
"name",
"string",
",",
"value",
"time",
".",
"Duration",
",",
"usage",
"string",
")",
"{",
"f",
".",
"Var",
"(",
"newDurationValue",
"(",
"value",
",",
"p",
")",
",",
"name",
",",
"usage",
")",
"\n",
"}"
] | // DurationVar defines a time.Duration flag with specified name, default value, and usage string.
// The argument p points to a time.Duration variable in which to store the value of the flag.
// The flag accepts a value acceptable to time.ParseDuration. | [
"DurationVar",
"defines",
"a",
"time",
".",
"Duration",
"flag",
"with",
"specified",
"name",
"default",
"value",
"and",
"usage",
"string",
".",
"The",
"argument",
"p",
"points",
"to",
"a",
"time",
".",
"Duration",
"variable",
"in",
"which",
"to",
"store",
"the",
"value",
"of",
"the",
"flag",
".",
"The",
"flag",
"accepts",
"a",
"value",
"acceptable",
"to",
"time",
".",
"ParseDuration",
"."
] | 67f268f20922975c067ed799e4be6bacf152208c | https://github.com/namsral/flag/blob/67f268f20922975c067ed799e4be6bacf152208c/flag.go#L748-L750 |
1,004 | namsral/flag | flag.go | usage | func (f *FlagSet) usage() {
if f.Usage == nil {
if f == CommandLine {
Usage()
} else {
defaultUsage(f)
}
} else {
f.Usage()
}
} | go | func (f *FlagSet) usage() {
if f.Usage == nil {
if f == CommandLine {
Usage()
} else {
defaultUsage(f)
}
} else {
f.Usage()
}
} | [
"func",
"(",
"f",
"*",
"FlagSet",
")",
"usage",
"(",
")",
"{",
"if",
"f",
".",
"Usage",
"==",
"nil",
"{",
"if",
"f",
"==",
"CommandLine",
"{",
"Usage",
"(",
")",
"\n",
"}",
"else",
"{",
"defaultUsage",
"(",
"f",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"f",
".",
"Usage",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // usage calls the Usage method for the flag set if one is specified,
// or the appropriate default usage function otherwise. | [
"usage",
"calls",
"the",
"Usage",
"method",
"for",
"the",
"flag",
"set",
"if",
"one",
"is",
"specified",
"or",
"the",
"appropriate",
"default",
"usage",
"function",
"otherwise",
"."
] | 67f268f20922975c067ed799e4be6bacf152208c | https://github.com/namsral/flag/blob/67f268f20922975c067ed799e4be6bacf152208c/flag.go#L822-L832 |
1,005 | namsral/flag | flag.go | Parse | func (f *FlagSet) Parse(arguments []string) error {
f.parsed = true
f.args = arguments
for {
seen, err := f.parseOne()
if seen {
continue
}
if err == nil {
break
}
switch f.errorHandling {
case ContinueOnError:
return err
case ExitOnError:
os.Exit(2)
case PanicOnError:
panic(err)
}
}
// Parse environment variables
if err := f.ParseEnv(os.Environ()); err != nil {
switch f.errorHandling {
case ContinueOnError:
return err
case ExitOnError:
os.Exit(2)
case PanicOnError:
panic(err)
}
return err
}
// Parse configuration from file
var cFile string
if cf := f.formal[DefaultConfigFlagname]; cf != nil {
cFile = cf.Value.String()
}
if cf := f.actual[DefaultConfigFlagname]; cf != nil {
cFile = cf.Value.String()
}
if cFile != "" {
if err := f.ParseFile(cFile); err != nil {
switch f.errorHandling {
case ContinueOnError:
return err
case ExitOnError:
os.Exit(2)
case PanicOnError:
panic(err)
}
return err
}
}
return nil
} | go | func (f *FlagSet) Parse(arguments []string) error {
f.parsed = true
f.args = arguments
for {
seen, err := f.parseOne()
if seen {
continue
}
if err == nil {
break
}
switch f.errorHandling {
case ContinueOnError:
return err
case ExitOnError:
os.Exit(2)
case PanicOnError:
panic(err)
}
}
// Parse environment variables
if err := f.ParseEnv(os.Environ()); err != nil {
switch f.errorHandling {
case ContinueOnError:
return err
case ExitOnError:
os.Exit(2)
case PanicOnError:
panic(err)
}
return err
}
// Parse configuration from file
var cFile string
if cf := f.formal[DefaultConfigFlagname]; cf != nil {
cFile = cf.Value.String()
}
if cf := f.actual[DefaultConfigFlagname]; cf != nil {
cFile = cf.Value.String()
}
if cFile != "" {
if err := f.ParseFile(cFile); err != nil {
switch f.errorHandling {
case ContinueOnError:
return err
case ExitOnError:
os.Exit(2)
case PanicOnError:
panic(err)
}
return err
}
}
return nil
} | [
"func",
"(",
"f",
"*",
"FlagSet",
")",
"Parse",
"(",
"arguments",
"[",
"]",
"string",
")",
"error",
"{",
"f",
".",
"parsed",
"=",
"true",
"\n",
"f",
".",
"args",
"=",
"arguments",
"\n",
"for",
"{",
"seen",
",",
"err",
":=",
"f",
".",
"parseOne",
"(",
")",
"\n",
"if",
"seen",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"err",
"==",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"switch",
"f",
".",
"errorHandling",
"{",
"case",
"ContinueOnError",
":",
"return",
"err",
"\n",
"case",
"ExitOnError",
":",
"os",
".",
"Exit",
"(",
"2",
")",
"\n",
"case",
"PanicOnError",
":",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Parse environment variables",
"if",
"err",
":=",
"f",
".",
"ParseEnv",
"(",
"os",
".",
"Environ",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"switch",
"f",
".",
"errorHandling",
"{",
"case",
"ContinueOnError",
":",
"return",
"err",
"\n",
"case",
"ExitOnError",
":",
"os",
".",
"Exit",
"(",
"2",
")",
"\n",
"case",
"PanicOnError",
":",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// Parse configuration from file",
"var",
"cFile",
"string",
"\n",
"if",
"cf",
":=",
"f",
".",
"formal",
"[",
"DefaultConfigFlagname",
"]",
";",
"cf",
"!=",
"nil",
"{",
"cFile",
"=",
"cf",
".",
"Value",
".",
"String",
"(",
")",
"\n",
"}",
"\n",
"if",
"cf",
":=",
"f",
".",
"actual",
"[",
"DefaultConfigFlagname",
"]",
";",
"cf",
"!=",
"nil",
"{",
"cFile",
"=",
"cf",
".",
"Value",
".",
"String",
"(",
")",
"\n",
"}",
"\n",
"if",
"cFile",
"!=",
"\"",
"\"",
"{",
"if",
"err",
":=",
"f",
".",
"ParseFile",
"(",
"cFile",
")",
";",
"err",
"!=",
"nil",
"{",
"switch",
"f",
".",
"errorHandling",
"{",
"case",
"ContinueOnError",
":",
"return",
"err",
"\n",
"case",
"ExitOnError",
":",
"os",
".",
"Exit",
"(",
"2",
")",
"\n",
"case",
"PanicOnError",
":",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Parse parses flag definitions from the argument list, which should not
// include the command name. Must be called after all flags in the FlagSet
// are defined and before flags are accessed by the program.
// The return value will be ErrHelp if -help or -h were set but not defined. | [
"Parse",
"parses",
"flag",
"definitions",
"from",
"the",
"argument",
"list",
"which",
"should",
"not",
"include",
"the",
"command",
"name",
".",
"Must",
"be",
"called",
"after",
"all",
"flags",
"in",
"the",
"FlagSet",
"are",
"defined",
"and",
"before",
"flags",
"are",
"accessed",
"by",
"the",
"program",
".",
"The",
"return",
"value",
"will",
"be",
"ErrHelp",
"if",
"-",
"help",
"or",
"-",
"h",
"were",
"set",
"but",
"not",
"defined",
"."
] | 67f268f20922975c067ed799e4be6bacf152208c | https://github.com/namsral/flag/blob/67f268f20922975c067ed799e4be6bacf152208c/flag.go#L917-L974 |
1,006 | namsral/flag | flag.go | Init | func (f *FlagSet) Init(name string, errorHandling ErrorHandling) {
f.name = name
f.envPrefix = EnvironmentPrefix
f.errorHandling = errorHandling
} | go | func (f *FlagSet) Init(name string, errorHandling ErrorHandling) {
f.name = name
f.envPrefix = EnvironmentPrefix
f.errorHandling = errorHandling
} | [
"func",
"(",
"f",
"*",
"FlagSet",
")",
"Init",
"(",
"name",
"string",
",",
"errorHandling",
"ErrorHandling",
")",
"{",
"f",
".",
"name",
"=",
"name",
"\n",
"f",
".",
"envPrefix",
"=",
"EnvironmentPrefix",
"\n",
"f",
".",
"errorHandling",
"=",
"errorHandling",
"\n",
"}"
] | // Init sets the name and error handling property for a flag set.
// By default, the zero FlagSet uses an empty name, EnvironmentPrefix, and the
// ContinueOnError error handling policy. | [
"Init",
"sets",
"the",
"name",
"and",
"error",
"handling",
"property",
"for",
"a",
"flag",
"set",
".",
"By",
"default",
"the",
"zero",
"FlagSet",
"uses",
"an",
"empty",
"name",
"EnvironmentPrefix",
"and",
"the",
"ContinueOnError",
"error",
"handling",
"policy",
"."
] | 67f268f20922975c067ed799e4be6bacf152208c | https://github.com/namsral/flag/blob/67f268f20922975c067ed799e4be6bacf152208c/flag.go#L1011-L1015 |
1,007 | bshuster-repo/logrus-logstash-hook | hook.go | Fire | func (h Hook) Fire(e *logrus.Entry) error {
dataBytes, err := h.formatter.Format(e)
if err != nil {
return err
}
_, err = h.writer.Write(dataBytes)
return err
} | go | func (h Hook) Fire(e *logrus.Entry) error {
dataBytes, err := h.formatter.Format(e)
if err != nil {
return err
}
_, err = h.writer.Write(dataBytes)
return err
} | [
"func",
"(",
"h",
"Hook",
")",
"Fire",
"(",
"e",
"*",
"logrus",
".",
"Entry",
")",
"error",
"{",
"dataBytes",
",",
"err",
":=",
"h",
".",
"formatter",
".",
"Format",
"(",
"e",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"h",
".",
"writer",
".",
"Write",
"(",
"dataBytes",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Fire takes, formats and sends the entry to Logstash.
// Hook's formatter is used to format the entry into Logstash format
// and Hook's writer is used to write the formatted entry to the Logstash instance. | [
"Fire",
"takes",
"formats",
"and",
"sends",
"the",
"entry",
"to",
"Logstash",
".",
"Hook",
"s",
"formatter",
"is",
"used",
"to",
"format",
"the",
"entry",
"into",
"Logstash",
"format",
"and",
"Hook",
"s",
"writer",
"is",
"used",
"to",
"write",
"the",
"formatted",
"entry",
"to",
"the",
"Logstash",
"instance",
"."
] | 1e961e8e173c48bdddbf90e4fc4df8eaf8a7e918 | https://github.com/bshuster-repo/logrus-logstash-hook/blob/1e961e8e173c48bdddbf90e4fc4df8eaf8a7e918/hook.go#L37-L44 |
1,008 | bshuster-repo/logrus-logstash-hook | hook.go | copyEntry | func copyEntry(e *logrus.Entry, fields logrus.Fields) *logrus.Entry {
ne := entryPool.Get().(*logrus.Entry)
ne.Message = e.Message
ne.Level = e.Level
ne.Time = e.Time
ne.Data = logrus.Fields{}
for k, v := range fields {
ne.Data[k] = v
}
for k, v := range e.Data {
ne.Data[k] = v
}
return ne
} | go | func copyEntry(e *logrus.Entry, fields logrus.Fields) *logrus.Entry {
ne := entryPool.Get().(*logrus.Entry)
ne.Message = e.Message
ne.Level = e.Level
ne.Time = e.Time
ne.Data = logrus.Fields{}
for k, v := range fields {
ne.Data[k] = v
}
for k, v := range e.Data {
ne.Data[k] = v
}
return ne
} | [
"func",
"copyEntry",
"(",
"e",
"*",
"logrus",
".",
"Entry",
",",
"fields",
"logrus",
".",
"Fields",
")",
"*",
"logrus",
".",
"Entry",
"{",
"ne",
":=",
"entryPool",
".",
"Get",
"(",
")",
".",
"(",
"*",
"logrus",
".",
"Entry",
")",
"\n",
"ne",
".",
"Message",
"=",
"e",
".",
"Message",
"\n",
"ne",
".",
"Level",
"=",
"e",
".",
"Level",
"\n",
"ne",
".",
"Time",
"=",
"e",
".",
"Time",
"\n",
"ne",
".",
"Data",
"=",
"logrus",
".",
"Fields",
"{",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"fields",
"{",
"ne",
".",
"Data",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"e",
".",
"Data",
"{",
"ne",
".",
"Data",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"return",
"ne",
"\n",
"}"
] | // copyEntry copies the entry `e` to a new entry and then adds all the fields in `fields` that are missing in the new entry data.
// It uses `entryPool` to re-use allocated entries. | [
"copyEntry",
"copies",
"the",
"entry",
"e",
"to",
"a",
"new",
"entry",
"and",
"then",
"adds",
"all",
"the",
"fields",
"in",
"fields",
"that",
"are",
"missing",
"in",
"the",
"new",
"entry",
"data",
".",
"It",
"uses",
"entryPool",
"to",
"re",
"-",
"use",
"allocated",
"entries",
"."
] | 1e961e8e173c48bdddbf90e4fc4df8eaf8a7e918 | https://github.com/bshuster-repo/logrus-logstash-hook/blob/1e961e8e173c48bdddbf90e4fc4df8eaf8a7e918/hook.go#L61-L74 |
1,009 | sajari/fuzzy | old.go | convertOldFormat | func (model *Model) convertOldFormat(filename string) error {
oldmodel := new(OldModel)
f, err := os.Open(filename)
if err != nil {
return err
}
defer f.Close()
d := json.NewDecoder(f)
err = d.Decode(oldmodel)
if err != nil {
return err
}
// Correct for old models pre divergence measure
if model.SuffDivergenceThreshold == 0 {
model.SuffDivergenceThreshold = SuffDivergenceThresholdDefault
}
// Convert fields
model.Maxcount = oldmodel.Maxcount
model.Suggest = oldmodel.Suggest
model.Depth = oldmodel.Depth
model.Threshold = oldmodel.Threshold
model.UseAutocomplete = oldmodel.UseAutocomplete
// Convert the old counts
if len(oldmodel.Data) > 0 {
model.Data = make(map[string]*Counts, len(oldmodel.Data))
for term, cc := range oldmodel.Data {
model.Data[term] = &Counts{cc, 0}
}
}
return nil
} | go | func (model *Model) convertOldFormat(filename string) error {
oldmodel := new(OldModel)
f, err := os.Open(filename)
if err != nil {
return err
}
defer f.Close()
d := json.NewDecoder(f)
err = d.Decode(oldmodel)
if err != nil {
return err
}
// Correct for old models pre divergence measure
if model.SuffDivergenceThreshold == 0 {
model.SuffDivergenceThreshold = SuffDivergenceThresholdDefault
}
// Convert fields
model.Maxcount = oldmodel.Maxcount
model.Suggest = oldmodel.Suggest
model.Depth = oldmodel.Depth
model.Threshold = oldmodel.Threshold
model.UseAutocomplete = oldmodel.UseAutocomplete
// Convert the old counts
if len(oldmodel.Data) > 0 {
model.Data = make(map[string]*Counts, len(oldmodel.Data))
for term, cc := range oldmodel.Data {
model.Data[term] = &Counts{cc, 0}
}
}
return nil
} | [
"func",
"(",
"model",
"*",
"Model",
")",
"convertOldFormat",
"(",
"filename",
"string",
")",
"error",
"{",
"oldmodel",
":=",
"new",
"(",
"OldModel",
")",
"\n",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"d",
":=",
"json",
".",
"NewDecoder",
"(",
"f",
")",
"\n",
"err",
"=",
"d",
".",
"Decode",
"(",
"oldmodel",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Correct for old models pre divergence measure",
"if",
"model",
".",
"SuffDivergenceThreshold",
"==",
"0",
"{",
"model",
".",
"SuffDivergenceThreshold",
"=",
"SuffDivergenceThresholdDefault",
"\n",
"}",
"\n\n",
"// Convert fields",
"model",
".",
"Maxcount",
"=",
"oldmodel",
".",
"Maxcount",
"\n",
"model",
".",
"Suggest",
"=",
"oldmodel",
".",
"Suggest",
"\n",
"model",
".",
"Depth",
"=",
"oldmodel",
".",
"Depth",
"\n",
"model",
".",
"Threshold",
"=",
"oldmodel",
".",
"Threshold",
"\n",
"model",
".",
"UseAutocomplete",
"=",
"oldmodel",
".",
"UseAutocomplete",
"\n\n",
"// Convert the old counts",
"if",
"len",
"(",
"oldmodel",
".",
"Data",
")",
">",
"0",
"{",
"model",
".",
"Data",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"Counts",
",",
"len",
"(",
"oldmodel",
".",
"Data",
")",
")",
"\n",
"for",
"term",
",",
"cc",
":=",
"range",
"oldmodel",
".",
"Data",
"{",
"model",
".",
"Data",
"[",
"term",
"]",
"=",
"&",
"Counts",
"{",
"cc",
",",
"0",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Converts the old model format to the new version | [
"Converts",
"the",
"old",
"model",
"format",
"to",
"the",
"new",
"version"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/old.go#L20-L53 |
1,010 | sajari/fuzzy | fuzzy.go | WriteTo | func (model *Model) WriteTo(w io.Writer) (int64, error) {
model.RLock()
defer model.RUnlock()
b, err := json.Marshal(model)
if err != nil {
return 0, err
}
n, err := w.Write(b)
if err != nil {
return int64(n), err
}
return int64(n), nil
} | go | func (model *Model) WriteTo(w io.Writer) (int64, error) {
model.RLock()
defer model.RUnlock()
b, err := json.Marshal(model)
if err != nil {
return 0, err
}
n, err := w.Write(b)
if err != nil {
return int64(n), err
}
return int64(n), nil
} | [
"func",
"(",
"model",
"*",
"Model",
")",
"WriteTo",
"(",
"w",
"io",
".",
"Writer",
")",
"(",
"int64",
",",
"error",
")",
"{",
"model",
".",
"RLock",
"(",
")",
"\n",
"defer",
"model",
".",
"RUnlock",
"(",
")",
"\n",
"b",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"model",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"n",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"b",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"int64",
"(",
"n",
")",
",",
"err",
"\n",
"}",
"\n",
"return",
"int64",
"(",
"n",
")",
",",
"nil",
"\n",
"}"
] | // WriteTo writes a model to a Writer | [
"WriteTo",
"writes",
"a",
"model",
"to",
"a",
"Writer"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L124-L136 |
1,011 | sajari/fuzzy | fuzzy.go | Save | func (model *Model) Save(filename string) error {
f, err := os.Create(filename)
if err != nil {
log.Println("Fuzzy model:", err)
return err
}
defer f.Close()
_, err = model.WriteTo(f)
if err != nil {
log.Println("Fuzzy model:", err)
return err
}
return nil
} | go | func (model *Model) Save(filename string) error {
f, err := os.Create(filename)
if err != nil {
log.Println("Fuzzy model:", err)
return err
}
defer f.Close()
_, err = model.WriteTo(f)
if err != nil {
log.Println("Fuzzy model:", err)
return err
}
return nil
} | [
"func",
"(",
"model",
"*",
"Model",
")",
"Save",
"(",
"filename",
"string",
")",
"error",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"_",
",",
"err",
"=",
"model",
".",
"WriteTo",
"(",
"f",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Save a spelling model to disk | [
"Save",
"a",
"spelling",
"model",
"to",
"disk"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L139-L152 |
1,012 | sajari/fuzzy | fuzzy.go | SaveLight | func (model *Model) SaveLight(filename string) error {
model.Lock()
for term, count := range model.Data {
if count.Corpus < model.Threshold {
delete(model.Data, term)
}
}
model.Unlock()
return model.Save(filename)
} | go | func (model *Model) SaveLight(filename string) error {
model.Lock()
for term, count := range model.Data {
if count.Corpus < model.Threshold {
delete(model.Data, term)
}
}
model.Unlock()
return model.Save(filename)
} | [
"func",
"(",
"model",
"*",
"Model",
")",
"SaveLight",
"(",
"filename",
"string",
")",
"error",
"{",
"model",
".",
"Lock",
"(",
")",
"\n",
"for",
"term",
",",
"count",
":=",
"range",
"model",
".",
"Data",
"{",
"if",
"count",
".",
"Corpus",
"<",
"model",
".",
"Threshold",
"{",
"delete",
"(",
"model",
".",
"Data",
",",
"term",
")",
"\n",
"}",
"\n",
"}",
"\n",
"model",
".",
"Unlock",
"(",
")",
"\n",
"return",
"model",
".",
"Save",
"(",
"filename",
")",
"\n",
"}"
] | // Save a spelling model to disk, but discard all
// entries less than the threshold number of occurences
// Much smaller and all that is used when generated
// as a once off, but not useful for incremental usage | [
"Save",
"a",
"spelling",
"model",
"to",
"disk",
"but",
"discard",
"all",
"entries",
"less",
"than",
"the",
"threshold",
"number",
"of",
"occurences",
"Much",
"smaller",
"and",
"all",
"that",
"is",
"used",
"when",
"generated",
"as",
"a",
"once",
"off",
"but",
"not",
"useful",
"for",
"incremental",
"usage"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L158-L167 |
1,013 | sajari/fuzzy | fuzzy.go | FromReader | func FromReader(r io.Reader) (*Model, error) {
model := new(Model)
d := json.NewDecoder(r)
err := d.Decode(model)
if err != nil {
return nil, err
}
model.updateSuffixArr()
return model, nil
} | go | func FromReader(r io.Reader) (*Model, error) {
model := new(Model)
d := json.NewDecoder(r)
err := d.Decode(model)
if err != nil {
return nil, err
}
model.updateSuffixArr()
return model, nil
} | [
"func",
"FromReader",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"*",
"Model",
",",
"error",
")",
"{",
"model",
":=",
"new",
"(",
"Model",
")",
"\n",
"d",
":=",
"json",
".",
"NewDecoder",
"(",
"r",
")",
"\n",
"err",
":=",
"d",
".",
"Decode",
"(",
"model",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"model",
".",
"updateSuffixArr",
"(",
")",
"\n",
"return",
"model",
",",
"nil",
"\n",
"}"
] | // FromReader loads a model from a Reader | [
"FromReader",
"loads",
"a",
"model",
"from",
"a",
"Reader"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L170-L179 |
1,014 | sajari/fuzzy | fuzzy.go | Load | func Load(filename string) (*Model, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
model, err := FromReader(f)
if err != nil {
model = new(Model)
if err1 := model.convertOldFormat(filename); err1 != nil {
return model, err1
}
return model, nil
}
return model, nil
} | go | func Load(filename string) (*Model, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
model, err := FromReader(f)
if err != nil {
model = new(Model)
if err1 := model.convertOldFormat(filename); err1 != nil {
return model, err1
}
return model, nil
}
return model, nil
} | [
"func",
"Load",
"(",
"filename",
"string",
")",
"(",
"*",
"Model",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"model",
",",
"err",
":=",
"FromReader",
"(",
"f",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"model",
"=",
"new",
"(",
"Model",
")",
"\n",
"if",
"err1",
":=",
"model",
".",
"convertOldFormat",
"(",
"filename",
")",
";",
"err1",
"!=",
"nil",
"{",
"return",
"model",
",",
"err1",
"\n",
"}",
"\n",
"return",
"model",
",",
"nil",
"\n",
"}",
"\n",
"return",
"model",
",",
"nil",
"\n",
"}"
] | // Load a saved model from disk | [
"Load",
"a",
"saved",
"model",
"from",
"disk"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L182-L197 |
1,015 | sajari/fuzzy | fuzzy.go | SetDepth | func (model *Model) SetDepth(val int) {
model.Lock()
model.Depth = val
model.Unlock()
} | go | func (model *Model) SetDepth(val int) {
model.Lock()
model.Depth = val
model.Unlock()
} | [
"func",
"(",
"model",
"*",
"Model",
")",
"SetDepth",
"(",
"val",
"int",
")",
"{",
"model",
".",
"Lock",
"(",
")",
"\n",
"model",
".",
"Depth",
"=",
"val",
"\n",
"model",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // Change the default depth value of the model. This sets how many
// character differences are indexed. The default is 2. | [
"Change",
"the",
"default",
"depth",
"value",
"of",
"the",
"model",
".",
"This",
"sets",
"how",
"many",
"character",
"differences",
"are",
"indexed",
".",
"The",
"default",
"is",
"2",
"."
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L201-L205 |
1,016 | sajari/fuzzy | fuzzy.go | SetThreshold | func (model *Model) SetThreshold(val int) {
model.Lock()
model.Threshold = val
model.Unlock()
} | go | func (model *Model) SetThreshold(val int) {
model.Lock()
model.Threshold = val
model.Unlock()
} | [
"func",
"(",
"model",
"*",
"Model",
")",
"SetThreshold",
"(",
"val",
"int",
")",
"{",
"model",
".",
"Lock",
"(",
")",
"\n",
"model",
".",
"Threshold",
"=",
"val",
"\n",
"model",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // Change the default threshold of the model. This is how many times
// a term must be seen before suggestions are created for it | [
"Change",
"the",
"default",
"threshold",
"of",
"the",
"model",
".",
"This",
"is",
"how",
"many",
"times",
"a",
"term",
"must",
"be",
"seen",
"before",
"suggestions",
"are",
"created",
"for",
"it"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L209-L213 |
1,017 | sajari/fuzzy | fuzzy.go | SetUseAutocomplete | func (model *Model) SetUseAutocomplete(val bool) {
model.Lock()
old := model.UseAutocomplete
model.Unlock()
model.UseAutocomplete = val
if !old && val {
model.updateSuffixArr()
}
} | go | func (model *Model) SetUseAutocomplete(val bool) {
model.Lock()
old := model.UseAutocomplete
model.Unlock()
model.UseAutocomplete = val
if !old && val {
model.updateSuffixArr()
}
} | [
"func",
"(",
"model",
"*",
"Model",
")",
"SetUseAutocomplete",
"(",
"val",
"bool",
")",
"{",
"model",
".",
"Lock",
"(",
")",
"\n",
"old",
":=",
"model",
".",
"UseAutocomplete",
"\n",
"model",
".",
"Unlock",
"(",
")",
"\n",
"model",
".",
"UseAutocomplete",
"=",
"val",
"\n",
"if",
"!",
"old",
"&&",
"val",
"{",
"model",
".",
"updateSuffixArr",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // Optionally disabled suffixarray based autocomplete support | [
"Optionally",
"disabled",
"suffixarray",
"based",
"autocomplete",
"support"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L216-L224 |
1,018 | sajari/fuzzy | fuzzy.go | SetDivergenceThreshold | func (model *Model) SetDivergenceThreshold(val int) {
model.Lock()
model.SuffDivergenceThreshold = val
model.Unlock()
} | go | func (model *Model) SetDivergenceThreshold(val int) {
model.Lock()
model.SuffDivergenceThreshold = val
model.Unlock()
} | [
"func",
"(",
"model",
"*",
"Model",
")",
"SetDivergenceThreshold",
"(",
"val",
"int",
")",
"{",
"model",
".",
"Lock",
"(",
")",
"\n",
"model",
".",
"SuffDivergenceThreshold",
"=",
"val",
"\n",
"model",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // Optionally set the suffix array divergence threshold. This is
// the number of query training steps between rebuilds of the
// suffix array. A low number will be more accurate but will use
// resources and create more garbage. | [
"Optionally",
"set",
"the",
"suffix",
"array",
"divergence",
"threshold",
".",
"This",
"is",
"the",
"number",
"of",
"query",
"training",
"steps",
"between",
"rebuilds",
"of",
"the",
"suffix",
"array",
".",
"A",
"low",
"number",
"will",
"be",
"more",
"accurate",
"but",
"will",
"use",
"resources",
"and",
"create",
"more",
"garbage",
"."
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L230-L234 |
1,019 | sajari/fuzzy | fuzzy.go | Levenshtein | func Levenshtein(a, b *string) int {
la := len(*a)
lb := len(*b)
d := make([]int, la+1)
var lastdiag, olddiag, temp int
for i := 1; i <= la; i++ {
d[i] = i
}
for i := 1; i <= lb; i++ {
d[0] = i
lastdiag = i - 1
for j := 1; j <= la; j++ {
olddiag = d[j]
min := d[j] + 1
if (d[j-1] + 1) < min {
min = d[j-1] + 1
}
if (*a)[j-1] == (*b)[i-1] {
temp = 0
} else {
temp = 1
}
if (lastdiag + temp) < min {
min = lastdiag + temp
}
d[j] = min
lastdiag = olddiag
}
}
return d[la]
} | go | func Levenshtein(a, b *string) int {
la := len(*a)
lb := len(*b)
d := make([]int, la+1)
var lastdiag, olddiag, temp int
for i := 1; i <= la; i++ {
d[i] = i
}
for i := 1; i <= lb; i++ {
d[0] = i
lastdiag = i - 1
for j := 1; j <= la; j++ {
olddiag = d[j]
min := d[j] + 1
if (d[j-1] + 1) < min {
min = d[j-1] + 1
}
if (*a)[j-1] == (*b)[i-1] {
temp = 0
} else {
temp = 1
}
if (lastdiag + temp) < min {
min = lastdiag + temp
}
d[j] = min
lastdiag = olddiag
}
}
return d[la]
} | [
"func",
"Levenshtein",
"(",
"a",
",",
"b",
"*",
"string",
")",
"int",
"{",
"la",
":=",
"len",
"(",
"*",
"a",
")",
"\n",
"lb",
":=",
"len",
"(",
"*",
"b",
")",
"\n",
"d",
":=",
"make",
"(",
"[",
"]",
"int",
",",
"la",
"+",
"1",
")",
"\n",
"var",
"lastdiag",
",",
"olddiag",
",",
"temp",
"int",
"\n\n",
"for",
"i",
":=",
"1",
";",
"i",
"<=",
"la",
";",
"i",
"++",
"{",
"d",
"[",
"i",
"]",
"=",
"i",
"\n",
"}",
"\n",
"for",
"i",
":=",
"1",
";",
"i",
"<=",
"lb",
";",
"i",
"++",
"{",
"d",
"[",
"0",
"]",
"=",
"i",
"\n",
"lastdiag",
"=",
"i",
"-",
"1",
"\n",
"for",
"j",
":=",
"1",
";",
"j",
"<=",
"la",
";",
"j",
"++",
"{",
"olddiag",
"=",
"d",
"[",
"j",
"]",
"\n",
"min",
":=",
"d",
"[",
"j",
"]",
"+",
"1",
"\n",
"if",
"(",
"d",
"[",
"j",
"-",
"1",
"]",
"+",
"1",
")",
"<",
"min",
"{",
"min",
"=",
"d",
"[",
"j",
"-",
"1",
"]",
"+",
"1",
"\n",
"}",
"\n",
"if",
"(",
"*",
"a",
")",
"[",
"j",
"-",
"1",
"]",
"==",
"(",
"*",
"b",
")",
"[",
"i",
"-",
"1",
"]",
"{",
"temp",
"=",
"0",
"\n",
"}",
"else",
"{",
"temp",
"=",
"1",
"\n",
"}",
"\n",
"if",
"(",
"lastdiag",
"+",
"temp",
")",
"<",
"min",
"{",
"min",
"=",
"lastdiag",
"+",
"temp",
"\n",
"}",
"\n",
"d",
"[",
"j",
"]",
"=",
"min",
"\n",
"lastdiag",
"=",
"olddiag",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"d",
"[",
"la",
"]",
"\n",
"}"
] | // Calculate the Levenshtein distance between two strings | [
"Calculate",
"the",
"Levenshtein",
"distance",
"between",
"two",
"strings"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L237-L268 |
1,020 | sajari/fuzzy | fuzzy.go | Train | func (model *Model) Train(terms []string) {
for _, term := range terms {
model.TrainWord(term)
}
model.updateSuffixArr()
} | go | func (model *Model) Train(terms []string) {
for _, term := range terms {
model.TrainWord(term)
}
model.updateSuffixArr()
} | [
"func",
"(",
"model",
"*",
"Model",
")",
"Train",
"(",
"terms",
"[",
"]",
"string",
")",
"{",
"for",
"_",
",",
"term",
":=",
"range",
"terms",
"{",
"model",
".",
"TrainWord",
"(",
"term",
")",
"\n",
"}",
"\n",
"model",
".",
"updateSuffixArr",
"(",
")",
"\n",
"}"
] | // Add an array of words to train the model in bulk | [
"Add",
"an",
"array",
"of",
"words",
"to",
"train",
"the",
"model",
"in",
"bulk"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L271-L276 |
1,021 | sajari/fuzzy | fuzzy.go | SetCount | func (model *Model) SetCount(term string, count int, suggest bool) {
model.Lock()
model.Data[term] = &Counts{count, 0} // Note: This may reset a query count? TODO
if suggest {
model.createSuggestKeys(term)
}
model.Unlock()
} | go | func (model *Model) SetCount(term string, count int, suggest bool) {
model.Lock()
model.Data[term] = &Counts{count, 0} // Note: This may reset a query count? TODO
if suggest {
model.createSuggestKeys(term)
}
model.Unlock()
} | [
"func",
"(",
"model",
"*",
"Model",
")",
"SetCount",
"(",
"term",
"string",
",",
"count",
"int",
",",
"suggest",
"bool",
")",
"{",
"model",
".",
"Lock",
"(",
")",
"\n",
"model",
".",
"Data",
"[",
"term",
"]",
"=",
"&",
"Counts",
"{",
"count",
",",
"0",
"}",
"// Note: This may reset a query count? TODO",
"\n",
"if",
"suggest",
"{",
"model",
".",
"createSuggestKeys",
"(",
"term",
")",
"\n",
"}",
"\n",
"model",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // Manually set the count of a word. Optionally trigger the
// creation of suggestion keys for the term. This function lets
// you build a model from an existing dictionary with word popularity
// counts without needing to run "TrainWord" repeatedly | [
"Manually",
"set",
"the",
"count",
"of",
"a",
"word",
".",
"Optionally",
"trigger",
"the",
"creation",
"of",
"suggestion",
"keys",
"for",
"the",
"term",
".",
"This",
"function",
"lets",
"you",
"build",
"a",
"model",
"from",
"an",
"existing",
"dictionary",
"with",
"word",
"popularity",
"counts",
"without",
"needing",
"to",
"run",
"TrainWord",
"repeatedly"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L282-L289 |
1,022 | sajari/fuzzy | fuzzy.go | TrainWord | func (model *Model) TrainWord(term string) {
model.Lock()
if t, ok := model.Data[term]; ok {
t.Corpus++
} else {
model.Data[term] = &Counts{1, 0}
}
// Set the max
if model.Data[term].Corpus > model.Maxcount {
model.Maxcount = model.Data[term].Corpus
model.SuffDivergence++
}
// If threshold is triggered, store delete suggestion keys
if model.Data[term].Corpus == model.Threshold {
model.createSuggestKeys(term)
}
model.Unlock()
} | go | func (model *Model) TrainWord(term string) {
model.Lock()
if t, ok := model.Data[term]; ok {
t.Corpus++
} else {
model.Data[term] = &Counts{1, 0}
}
// Set the max
if model.Data[term].Corpus > model.Maxcount {
model.Maxcount = model.Data[term].Corpus
model.SuffDivergence++
}
// If threshold is triggered, store delete suggestion keys
if model.Data[term].Corpus == model.Threshold {
model.createSuggestKeys(term)
}
model.Unlock()
} | [
"func",
"(",
"model",
"*",
"Model",
")",
"TrainWord",
"(",
"term",
"string",
")",
"{",
"model",
".",
"Lock",
"(",
")",
"\n",
"if",
"t",
",",
"ok",
":=",
"model",
".",
"Data",
"[",
"term",
"]",
";",
"ok",
"{",
"t",
".",
"Corpus",
"++",
"\n",
"}",
"else",
"{",
"model",
".",
"Data",
"[",
"term",
"]",
"=",
"&",
"Counts",
"{",
"1",
",",
"0",
"}",
"\n",
"}",
"\n",
"// Set the max",
"if",
"model",
".",
"Data",
"[",
"term",
"]",
".",
"Corpus",
">",
"model",
".",
"Maxcount",
"{",
"model",
".",
"Maxcount",
"=",
"model",
".",
"Data",
"[",
"term",
"]",
".",
"Corpus",
"\n",
"model",
".",
"SuffDivergence",
"++",
"\n",
"}",
"\n",
"// If threshold is triggered, store delete suggestion keys",
"if",
"model",
".",
"Data",
"[",
"term",
"]",
".",
"Corpus",
"==",
"model",
".",
"Threshold",
"{",
"model",
".",
"createSuggestKeys",
"(",
"term",
")",
"\n",
"}",
"\n",
"model",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // Train the model word by word. This is corpus training as opposed
// to query training. Word counts from this type of training are not
// likely to correlate with those of search queries | [
"Train",
"the",
"model",
"word",
"by",
"word",
".",
"This",
"is",
"corpus",
"training",
"as",
"opposed",
"to",
"query",
"training",
".",
"Word",
"counts",
"from",
"this",
"type",
"of",
"training",
"are",
"not",
"likely",
"to",
"correlate",
"with",
"those",
"of",
"search",
"queries"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L294-L311 |
1,023 | sajari/fuzzy | fuzzy.go | TrainQuery | func (model *Model) TrainQuery(term string) {
model.Lock()
if t, ok := model.Data[term]; ok {
t.Query++
} else {
model.Data[term] = &Counts{0, 1}
}
model.SuffDivergence++
update := model.SuffDivergence > model.SuffDivergenceThreshold
model.Unlock()
if update {
model.updateSuffixArr()
}
} | go | func (model *Model) TrainQuery(term string) {
model.Lock()
if t, ok := model.Data[term]; ok {
t.Query++
} else {
model.Data[term] = &Counts{0, 1}
}
model.SuffDivergence++
update := model.SuffDivergence > model.SuffDivergenceThreshold
model.Unlock()
if update {
model.updateSuffixArr()
}
} | [
"func",
"(",
"model",
"*",
"Model",
")",
"TrainQuery",
"(",
"term",
"string",
")",
"{",
"model",
".",
"Lock",
"(",
")",
"\n",
"if",
"t",
",",
"ok",
":=",
"model",
".",
"Data",
"[",
"term",
"]",
";",
"ok",
"{",
"t",
".",
"Query",
"++",
"\n",
"}",
"else",
"{",
"model",
".",
"Data",
"[",
"term",
"]",
"=",
"&",
"Counts",
"{",
"0",
",",
"1",
"}",
"\n",
"}",
"\n",
"model",
".",
"SuffDivergence",
"++",
"\n",
"update",
":=",
"model",
".",
"SuffDivergence",
">",
"model",
".",
"SuffDivergenceThreshold",
"\n",
"model",
".",
"Unlock",
"(",
")",
"\n",
"if",
"update",
"{",
"model",
".",
"updateSuffixArr",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // Train using a search query term. This builds a second popularity
// index of terms used to search, as opposed to generally occurring
// in corpus text | [
"Train",
"using",
"a",
"search",
"query",
"term",
".",
"This",
"builds",
"a",
"second",
"popularity",
"index",
"of",
"terms",
"used",
"to",
"search",
"as",
"opposed",
"to",
"generally",
"occurring",
"in",
"corpus",
"text"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L316-L329 |
1,024 | sajari/fuzzy | fuzzy.go | createSuggestKeys | func (model *Model) createSuggestKeys(term string) {
edits := model.EditsMulti(term, model.Depth)
for _, edit := range edits {
skip := false
for _, hit := range model.Suggest[edit] {
if hit == term {
// Already know about this one
skip = true
continue
}
}
if !skip && len(edit) > 1 {
model.Suggest[edit] = append(model.Suggest[edit], term)
}
}
} | go | func (model *Model) createSuggestKeys(term string) {
edits := model.EditsMulti(term, model.Depth)
for _, edit := range edits {
skip := false
for _, hit := range model.Suggest[edit] {
if hit == term {
// Already know about this one
skip = true
continue
}
}
if !skip && len(edit) > 1 {
model.Suggest[edit] = append(model.Suggest[edit], term)
}
}
} | [
"func",
"(",
"model",
"*",
"Model",
")",
"createSuggestKeys",
"(",
"term",
"string",
")",
"{",
"edits",
":=",
"model",
".",
"EditsMulti",
"(",
"term",
",",
"model",
".",
"Depth",
")",
"\n",
"for",
"_",
",",
"edit",
":=",
"range",
"edits",
"{",
"skip",
":=",
"false",
"\n",
"for",
"_",
",",
"hit",
":=",
"range",
"model",
".",
"Suggest",
"[",
"edit",
"]",
"{",
"if",
"hit",
"==",
"term",
"{",
"// Already know about this one",
"skip",
"=",
"true",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"skip",
"&&",
"len",
"(",
"edit",
")",
">",
"1",
"{",
"model",
".",
"Suggest",
"[",
"edit",
"]",
"=",
"append",
"(",
"model",
".",
"Suggest",
"[",
"edit",
"]",
",",
"term",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // For a given term, create the partially deleted lookup keys | [
"For",
"a",
"given",
"term",
"create",
"the",
"partially",
"deleted",
"lookup",
"keys"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L332-L347 |
1,025 | sajari/fuzzy | fuzzy.go | EditsMulti | func (model *Model) EditsMulti(term string, depth int) []string {
edits := Edits1(term)
for {
depth--
if depth <= 0 {
break
}
for _, edit := range edits {
edits2 := Edits1(edit)
for _, edit2 := range edits2 {
edits = append(edits, edit2)
}
}
}
return edits
} | go | func (model *Model) EditsMulti(term string, depth int) []string {
edits := Edits1(term)
for {
depth--
if depth <= 0 {
break
}
for _, edit := range edits {
edits2 := Edits1(edit)
for _, edit2 := range edits2 {
edits = append(edits, edit2)
}
}
}
return edits
} | [
"func",
"(",
"model",
"*",
"Model",
")",
"EditsMulti",
"(",
"term",
"string",
",",
"depth",
"int",
")",
"[",
"]",
"string",
"{",
"edits",
":=",
"Edits1",
"(",
"term",
")",
"\n",
"for",
"{",
"depth",
"--",
"\n",
"if",
"depth",
"<=",
"0",
"{",
"break",
"\n",
"}",
"\n",
"for",
"_",
",",
"edit",
":=",
"range",
"edits",
"{",
"edits2",
":=",
"Edits1",
"(",
"edit",
")",
"\n",
"for",
"_",
",",
"edit2",
":=",
"range",
"edits2",
"{",
"edits",
"=",
"append",
"(",
"edits",
",",
"edit2",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"edits",
"\n",
"}"
] | // Edits at any depth for a given term. The depth of the model is used | [
"Edits",
"at",
"any",
"depth",
"for",
"a",
"given",
"term",
".",
"The",
"depth",
"of",
"the",
"model",
"is",
"used"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L350-L365 |
1,026 | sajari/fuzzy | fuzzy.go | Edits1 | func Edits1(word string) []string {
splits := []Pair{}
for i := 0; i <= len(word); i++ {
splits = append(splits, Pair{word[:i], word[i:]})
}
total_set := []string{}
for _, elem := range splits {
//deletion
if len(elem.str2) > 0 {
total_set = append(total_set, elem.str1+elem.str2[1:])
} else {
total_set = append(total_set, elem.str1)
}
}
// Special case ending in "ies" or "ys"
if strings.HasSuffix(word, "ies") {
total_set = append(total_set, word[:len(word)-3]+"ys")
}
if strings.HasSuffix(word, "ys") {
total_set = append(total_set, word[:len(word)-2]+"ies")
}
return total_set
} | go | func Edits1(word string) []string {
splits := []Pair{}
for i := 0; i <= len(word); i++ {
splits = append(splits, Pair{word[:i], word[i:]})
}
total_set := []string{}
for _, elem := range splits {
//deletion
if len(elem.str2) > 0 {
total_set = append(total_set, elem.str1+elem.str2[1:])
} else {
total_set = append(total_set, elem.str1)
}
}
// Special case ending in "ies" or "ys"
if strings.HasSuffix(word, "ies") {
total_set = append(total_set, word[:len(word)-3]+"ys")
}
if strings.HasSuffix(word, "ys") {
total_set = append(total_set, word[:len(word)-2]+"ies")
}
return total_set
} | [
"func",
"Edits1",
"(",
"word",
"string",
")",
"[",
"]",
"string",
"{",
"splits",
":=",
"[",
"]",
"Pair",
"{",
"}",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<=",
"len",
"(",
"word",
")",
";",
"i",
"++",
"{",
"splits",
"=",
"append",
"(",
"splits",
",",
"Pair",
"{",
"word",
"[",
":",
"i",
"]",
",",
"word",
"[",
"i",
":",
"]",
"}",
")",
"\n",
"}",
"\n\n",
"total_set",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"elem",
":=",
"range",
"splits",
"{",
"//deletion",
"if",
"len",
"(",
"elem",
".",
"str2",
")",
">",
"0",
"{",
"total_set",
"=",
"append",
"(",
"total_set",
",",
"elem",
".",
"str1",
"+",
"elem",
".",
"str2",
"[",
"1",
":",
"]",
")",
"\n",
"}",
"else",
"{",
"total_set",
"=",
"append",
"(",
"total_set",
",",
"elem",
".",
"str1",
")",
"\n",
"}",
"\n\n",
"}",
"\n\n",
"// Special case ending in \"ies\" or \"ys\"",
"if",
"strings",
".",
"HasSuffix",
"(",
"word",
",",
"\"",
"\"",
")",
"{",
"total_set",
"=",
"append",
"(",
"total_set",
",",
"word",
"[",
":",
"len",
"(",
"word",
")",
"-",
"3",
"]",
"+",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"strings",
".",
"HasSuffix",
"(",
"word",
",",
"\"",
"\"",
")",
"{",
"total_set",
"=",
"append",
"(",
"total_set",
",",
"word",
"[",
":",
"len",
"(",
"word",
")",
"-",
"2",
"]",
"+",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"total_set",
"\n",
"}"
] | // Edits1 creates a set of terms that are 1 char delete from the input term | [
"Edits1",
"creates",
"a",
"set",
"of",
"terms",
"that",
"are",
"1",
"char",
"delete",
"from",
"the",
"input",
"term"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L368-L396 |
1,027 | sajari/fuzzy | fuzzy.go | best | func best(input string, potential map[string]*Potential) string {
var best string
var bestcalc, bonus int
for i := 0; i < 4; i++ {
for _, pot := range potential {
if pot.Leven == 0 {
return pot.Term
} else if pot.Leven == i {
bonus = 0
// If the first letter is the same, that's a good sign. Bias these potentials
if pot.Term[0] == input[0] {
bonus += 100
}
if pot.Score+bonus > bestcalc {
bestcalc = pot.Score + bonus
best = pot.Term
}
}
}
if bestcalc > 0 {
return best
}
}
return best
} | go | func best(input string, potential map[string]*Potential) string {
var best string
var bestcalc, bonus int
for i := 0; i < 4; i++ {
for _, pot := range potential {
if pot.Leven == 0 {
return pot.Term
} else if pot.Leven == i {
bonus = 0
// If the first letter is the same, that's a good sign. Bias these potentials
if pot.Term[0] == input[0] {
bonus += 100
}
if pot.Score+bonus > bestcalc {
bestcalc = pot.Score + bonus
best = pot.Term
}
}
}
if bestcalc > 0 {
return best
}
}
return best
} | [
"func",
"best",
"(",
"input",
"string",
",",
"potential",
"map",
"[",
"string",
"]",
"*",
"Potential",
")",
"string",
"{",
"var",
"best",
"string",
"\n",
"var",
"bestcalc",
",",
"bonus",
"int",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"4",
";",
"i",
"++",
"{",
"for",
"_",
",",
"pot",
":=",
"range",
"potential",
"{",
"if",
"pot",
".",
"Leven",
"==",
"0",
"{",
"return",
"pot",
".",
"Term",
"\n",
"}",
"else",
"if",
"pot",
".",
"Leven",
"==",
"i",
"{",
"bonus",
"=",
"0",
"\n",
"// If the first letter is the same, that's a good sign. Bias these potentials",
"if",
"pot",
".",
"Term",
"[",
"0",
"]",
"==",
"input",
"[",
"0",
"]",
"{",
"bonus",
"+=",
"100",
"\n",
"}",
"\n",
"if",
"pot",
".",
"Score",
"+",
"bonus",
">",
"bestcalc",
"{",
"bestcalc",
"=",
"pot",
".",
"Score",
"+",
"bonus",
"\n",
"best",
"=",
"pot",
".",
"Term",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"bestcalc",
">",
"0",
"{",
"return",
"best",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"best",
"\n",
"}"
] | // From a group of potentials, work out the most likely result | [
"From",
"a",
"group",
"of",
"potentials",
"work",
"out",
"the",
"most",
"likely",
"result"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L406-L430 |
1,028 | sajari/fuzzy | fuzzy.go | bestn | func bestn(input string, potential map[string]*Potential, n int) []string {
var output []string
for i := 0; i < n; i++ {
if len(potential) == 0 {
break
}
b := best(input, potential)
output = append(output, b)
delete(potential, b)
}
return output
} | go | func bestn(input string, potential map[string]*Potential, n int) []string {
var output []string
for i := 0; i < n; i++ {
if len(potential) == 0 {
break
}
b := best(input, potential)
output = append(output, b)
delete(potential, b)
}
return output
} | [
"func",
"bestn",
"(",
"input",
"string",
",",
"potential",
"map",
"[",
"string",
"]",
"*",
"Potential",
",",
"n",
"int",
")",
"[",
"]",
"string",
"{",
"var",
"output",
"[",
"]",
"string",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
"{",
"if",
"len",
"(",
"potential",
")",
"==",
"0",
"{",
"break",
"\n",
"}",
"\n",
"b",
":=",
"best",
"(",
"input",
",",
"potential",
")",
"\n",
"output",
"=",
"append",
"(",
"output",
",",
"b",
")",
"\n",
"delete",
"(",
"potential",
",",
"b",
")",
"\n",
"}",
"\n",
"return",
"output",
"\n",
"}"
] | // From a group of potentials, work out the most likely results, in order of
// best to worst | [
"From",
"a",
"group",
"of",
"potentials",
"work",
"out",
"the",
"most",
"likely",
"results",
"in",
"order",
"of",
"best",
"to",
"worst"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L434-L445 |
1,029 | sajari/fuzzy | fuzzy.go | CheckKnown | func (model *Model) CheckKnown(input string, correct string) bool {
model.RLock()
defer model.RUnlock()
suggestions := model.suggestPotential(input, true)
best := best(input, suggestions)
if best == correct {
// This guess is correct
fmt.Printf("Input correctly maps to correct term")
return true
}
if pot, ok := suggestions[correct]; !ok {
if model.corpusCount(correct) > 0 {
fmt.Printf("\"%v\" - %v (%v) not in the suggestions. (%v) best option.\n", input, correct, model.corpusCount(correct), best)
for _, sugg := range suggestions {
fmt.Printf(" %v\n", sugg)
}
} else {
fmt.Printf("\"%v\" - Not in dictionary\n", correct)
}
} else {
fmt.Printf("\"%v\" - (%v) suggested, should however be (%v).\n", input, suggestions[best], pot)
}
return false
} | go | func (model *Model) CheckKnown(input string, correct string) bool {
model.RLock()
defer model.RUnlock()
suggestions := model.suggestPotential(input, true)
best := best(input, suggestions)
if best == correct {
// This guess is correct
fmt.Printf("Input correctly maps to correct term")
return true
}
if pot, ok := suggestions[correct]; !ok {
if model.corpusCount(correct) > 0 {
fmt.Printf("\"%v\" - %v (%v) not in the suggestions. (%v) best option.\n", input, correct, model.corpusCount(correct), best)
for _, sugg := range suggestions {
fmt.Printf(" %v\n", sugg)
}
} else {
fmt.Printf("\"%v\" - Not in dictionary\n", correct)
}
} else {
fmt.Printf("\"%v\" - (%v) suggested, should however be (%v).\n", input, suggestions[best], pot)
}
return false
} | [
"func",
"(",
"model",
"*",
"Model",
")",
"CheckKnown",
"(",
"input",
"string",
",",
"correct",
"string",
")",
"bool",
"{",
"model",
".",
"RLock",
"(",
")",
"\n",
"defer",
"model",
".",
"RUnlock",
"(",
")",
"\n",
"suggestions",
":=",
"model",
".",
"suggestPotential",
"(",
"input",
",",
"true",
")",
"\n",
"best",
":=",
"best",
"(",
"input",
",",
"suggestions",
")",
"\n",
"if",
"best",
"==",
"correct",
"{",
"// This guess is correct",
"fmt",
".",
"Printf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"if",
"pot",
",",
"ok",
":=",
"suggestions",
"[",
"correct",
"]",
";",
"!",
"ok",
"{",
"if",
"model",
".",
"corpusCount",
"(",
"correct",
")",
">",
"0",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\\"",
"\\\"",
"\\n",
"\"",
",",
"input",
",",
"correct",
",",
"model",
".",
"corpusCount",
"(",
"correct",
")",
",",
"best",
")",
"\n",
"for",
"_",
",",
"sugg",
":=",
"range",
"suggestions",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"sugg",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\\"",
"\\\"",
"\\n",
"\"",
",",
"correct",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\\"",
"\\\"",
"\\n",
"\"",
",",
"input",
",",
"suggestions",
"[",
"best",
"]",
",",
"pot",
")",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // Test an input, if we get it wrong, look at why it is wrong. This
// function returns a bool indicating if the guess was correct as well
// as the term it is suggesting. Typically this function would be used
// for testing, not for production | [
"Test",
"an",
"input",
"if",
"we",
"get",
"it",
"wrong",
"look",
"at",
"why",
"it",
"is",
"wrong",
".",
"This",
"function",
"returns",
"a",
"bool",
"indicating",
"if",
"the",
"guess",
"was",
"correct",
"as",
"well",
"as",
"the",
"term",
"it",
"is",
"suggesting",
".",
"Typically",
"this",
"function",
"would",
"be",
"used",
"for",
"testing",
"not",
"for",
"production"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L451-L475 |
1,030 | sajari/fuzzy | fuzzy.go | suggestPotential | func (model *Model) suggestPotential(input string, exhaustive bool) map[string]*Potential {
input = strings.ToLower(input)
suggestions := make(map[string]*Potential, 20)
// 0 - If this is a dictionary term we're all good, no need to go further
if model.corpusCount(input) > model.Threshold {
suggestions[input] = &Potential{Term: input, Score: model.corpusCount(input), Leven: 0, Method: MethodIsWord}
if !exhaustive {
return suggestions
}
}
// 1 - See if the input matches a "suggest" key
if sugg, ok := model.Suggest[input]; ok {
for _, pot := range sugg {
if _, ok := suggestions[pot]; !ok {
suggestions[pot] = &Potential{Term: pot, Score: model.corpusCount(pot), Leven: Levenshtein(&input, &pot), Method: MethodSuggestMapsToInput}
}
}
if !exhaustive {
return suggestions
}
}
// 2 - See if edit1 matches input
max := 0
edits := model.EditsMulti(input, model.Depth)
for _, edit := range edits {
score := model.corpusCount(edit)
if score > 0 && len(edit) > 2 {
if _, ok := suggestions[edit]; !ok {
suggestions[edit] = &Potential{Term: edit, Score: score, Leven: Levenshtein(&input, &edit), Method: MethodInputDeleteMapsToDict}
}
if score > max {
max = score
}
}
}
if max > 0 {
if !exhaustive {
return suggestions
}
}
// 3 - No hits on edit1 distance, look for transposes and replaces
// Note: these are more complex, we need to check the guesses
// more thoroughly, e.g. levals=[valves] in a raw sense, which
// is incorrect
for _, edit := range edits {
if sugg, ok := model.Suggest[edit]; ok {
// Is this a real transpose or replace?
for _, pot := range sugg {
lev := Levenshtein(&input, &pot)
if lev <= model.Depth+1 { // The +1 doesn't seem to impact speed, but has greater coverage when the depth is not sufficient to make suggestions
if _, ok := suggestions[pot]; !ok {
suggestions[pot] = &Potential{Term: pot, Score: model.corpusCount(pot), Leven: lev, Method: MethodInputDeleteMapsToSuggest}
}
}
}
}
}
return suggestions
} | go | func (model *Model) suggestPotential(input string, exhaustive bool) map[string]*Potential {
input = strings.ToLower(input)
suggestions := make(map[string]*Potential, 20)
// 0 - If this is a dictionary term we're all good, no need to go further
if model.corpusCount(input) > model.Threshold {
suggestions[input] = &Potential{Term: input, Score: model.corpusCount(input), Leven: 0, Method: MethodIsWord}
if !exhaustive {
return suggestions
}
}
// 1 - See if the input matches a "suggest" key
if sugg, ok := model.Suggest[input]; ok {
for _, pot := range sugg {
if _, ok := suggestions[pot]; !ok {
suggestions[pot] = &Potential{Term: pot, Score: model.corpusCount(pot), Leven: Levenshtein(&input, &pot), Method: MethodSuggestMapsToInput}
}
}
if !exhaustive {
return suggestions
}
}
// 2 - See if edit1 matches input
max := 0
edits := model.EditsMulti(input, model.Depth)
for _, edit := range edits {
score := model.corpusCount(edit)
if score > 0 && len(edit) > 2 {
if _, ok := suggestions[edit]; !ok {
suggestions[edit] = &Potential{Term: edit, Score: score, Leven: Levenshtein(&input, &edit), Method: MethodInputDeleteMapsToDict}
}
if score > max {
max = score
}
}
}
if max > 0 {
if !exhaustive {
return suggestions
}
}
// 3 - No hits on edit1 distance, look for transposes and replaces
// Note: these are more complex, we need to check the guesses
// more thoroughly, e.g. levals=[valves] in a raw sense, which
// is incorrect
for _, edit := range edits {
if sugg, ok := model.Suggest[edit]; ok {
// Is this a real transpose or replace?
for _, pot := range sugg {
lev := Levenshtein(&input, &pot)
if lev <= model.Depth+1 { // The +1 doesn't seem to impact speed, but has greater coverage when the depth is not sufficient to make suggestions
if _, ok := suggestions[pot]; !ok {
suggestions[pot] = &Potential{Term: pot, Score: model.corpusCount(pot), Leven: lev, Method: MethodInputDeleteMapsToSuggest}
}
}
}
}
}
return suggestions
} | [
"func",
"(",
"model",
"*",
"Model",
")",
"suggestPotential",
"(",
"input",
"string",
",",
"exhaustive",
"bool",
")",
"map",
"[",
"string",
"]",
"*",
"Potential",
"{",
"input",
"=",
"strings",
".",
"ToLower",
"(",
"input",
")",
"\n",
"suggestions",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"Potential",
",",
"20",
")",
"\n\n",
"// 0 - If this is a dictionary term we're all good, no need to go further",
"if",
"model",
".",
"corpusCount",
"(",
"input",
")",
">",
"model",
".",
"Threshold",
"{",
"suggestions",
"[",
"input",
"]",
"=",
"&",
"Potential",
"{",
"Term",
":",
"input",
",",
"Score",
":",
"model",
".",
"corpusCount",
"(",
"input",
")",
",",
"Leven",
":",
"0",
",",
"Method",
":",
"MethodIsWord",
"}",
"\n",
"if",
"!",
"exhaustive",
"{",
"return",
"suggestions",
"\n",
"}",
"\n",
"}",
"\n\n",
"// 1 - See if the input matches a \"suggest\" key",
"if",
"sugg",
",",
"ok",
":=",
"model",
".",
"Suggest",
"[",
"input",
"]",
";",
"ok",
"{",
"for",
"_",
",",
"pot",
":=",
"range",
"sugg",
"{",
"if",
"_",
",",
"ok",
":=",
"suggestions",
"[",
"pot",
"]",
";",
"!",
"ok",
"{",
"suggestions",
"[",
"pot",
"]",
"=",
"&",
"Potential",
"{",
"Term",
":",
"pot",
",",
"Score",
":",
"model",
".",
"corpusCount",
"(",
"pot",
")",
",",
"Leven",
":",
"Levenshtein",
"(",
"&",
"input",
",",
"&",
"pot",
")",
",",
"Method",
":",
"MethodSuggestMapsToInput",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"!",
"exhaustive",
"{",
"return",
"suggestions",
"\n",
"}",
"\n",
"}",
"\n\n",
"// 2 - See if edit1 matches input",
"max",
":=",
"0",
"\n",
"edits",
":=",
"model",
".",
"EditsMulti",
"(",
"input",
",",
"model",
".",
"Depth",
")",
"\n",
"for",
"_",
",",
"edit",
":=",
"range",
"edits",
"{",
"score",
":=",
"model",
".",
"corpusCount",
"(",
"edit",
")",
"\n",
"if",
"score",
">",
"0",
"&&",
"len",
"(",
"edit",
")",
">",
"2",
"{",
"if",
"_",
",",
"ok",
":=",
"suggestions",
"[",
"edit",
"]",
";",
"!",
"ok",
"{",
"suggestions",
"[",
"edit",
"]",
"=",
"&",
"Potential",
"{",
"Term",
":",
"edit",
",",
"Score",
":",
"score",
",",
"Leven",
":",
"Levenshtein",
"(",
"&",
"input",
",",
"&",
"edit",
")",
",",
"Method",
":",
"MethodInputDeleteMapsToDict",
"}",
"\n",
"}",
"\n",
"if",
"score",
">",
"max",
"{",
"max",
"=",
"score",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"max",
">",
"0",
"{",
"if",
"!",
"exhaustive",
"{",
"return",
"suggestions",
"\n",
"}",
"\n",
"}",
"\n\n",
"// 3 - No hits on edit1 distance, look for transposes and replaces",
"// Note: these are more complex, we need to check the guesses",
"// more thoroughly, e.g. levals=[valves] in a raw sense, which",
"// is incorrect",
"for",
"_",
",",
"edit",
":=",
"range",
"edits",
"{",
"if",
"sugg",
",",
"ok",
":=",
"model",
".",
"Suggest",
"[",
"edit",
"]",
";",
"ok",
"{",
"// Is this a real transpose or replace?",
"for",
"_",
",",
"pot",
":=",
"range",
"sugg",
"{",
"lev",
":=",
"Levenshtein",
"(",
"&",
"input",
",",
"&",
"pot",
")",
"\n",
"if",
"lev",
"<=",
"model",
".",
"Depth",
"+",
"1",
"{",
"// The +1 doesn't seem to impact speed, but has greater coverage when the depth is not sufficient to make suggestions",
"if",
"_",
",",
"ok",
":=",
"suggestions",
"[",
"pot",
"]",
";",
"!",
"ok",
"{",
"suggestions",
"[",
"pot",
"]",
"=",
"&",
"Potential",
"{",
"Term",
":",
"pot",
",",
"Score",
":",
"model",
".",
"corpusCount",
"(",
"pot",
")",
",",
"Leven",
":",
"lev",
",",
"Method",
":",
"MethodInputDeleteMapsToSuggest",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"suggestions",
"\n",
"}"
] | // For a given input term, suggest some alternatives. If exhaustive, each of the 4
// cascading checks will be performed and all potentials will be sorted accordingly | [
"For",
"a",
"given",
"input",
"term",
"suggest",
"some",
"alternatives",
".",
"If",
"exhaustive",
"each",
"of",
"the",
"4",
"cascading",
"checks",
"will",
"be",
"performed",
"and",
"all",
"potentials",
"will",
"be",
"sorted",
"accordingly"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L479-L542 |
1,031 | sajari/fuzzy | fuzzy.go | Potentials | func (model *Model) Potentials(input string, exhaustive bool) map[string]*Potential {
model.RLock()
defer model.RUnlock()
return model.suggestPotential(input, exhaustive)
} | go | func (model *Model) Potentials(input string, exhaustive bool) map[string]*Potential {
model.RLock()
defer model.RUnlock()
return model.suggestPotential(input, exhaustive)
} | [
"func",
"(",
"model",
"*",
"Model",
")",
"Potentials",
"(",
"input",
"string",
",",
"exhaustive",
"bool",
")",
"map",
"[",
"string",
"]",
"*",
"Potential",
"{",
"model",
".",
"RLock",
"(",
")",
"\n",
"defer",
"model",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"model",
".",
"suggestPotential",
"(",
"input",
",",
"exhaustive",
")",
"\n",
"}"
] | // Return the raw potential terms so they can be ranked externally
// to this package | [
"Return",
"the",
"raw",
"potential",
"terms",
"so",
"they",
"can",
"be",
"ranked",
"externally",
"to",
"this",
"package"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L546-L550 |
1,032 | sajari/fuzzy | fuzzy.go | Suggestions | func (model *Model) Suggestions(input string, exhaustive bool) []string {
model.RLock()
suggestions := model.suggestPotential(input, exhaustive)
model.RUnlock()
output := make([]string, 0, 10)
for _, suggestion := range suggestions {
output = append(output, suggestion.Term)
}
return output
} | go | func (model *Model) Suggestions(input string, exhaustive bool) []string {
model.RLock()
suggestions := model.suggestPotential(input, exhaustive)
model.RUnlock()
output := make([]string, 0, 10)
for _, suggestion := range suggestions {
output = append(output, suggestion.Term)
}
return output
} | [
"func",
"(",
"model",
"*",
"Model",
")",
"Suggestions",
"(",
"input",
"string",
",",
"exhaustive",
"bool",
")",
"[",
"]",
"string",
"{",
"model",
".",
"RLock",
"(",
")",
"\n",
"suggestions",
":=",
"model",
".",
"suggestPotential",
"(",
"input",
",",
"exhaustive",
")",
"\n",
"model",
".",
"RUnlock",
"(",
")",
"\n",
"output",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"10",
")",
"\n",
"for",
"_",
",",
"suggestion",
":=",
"range",
"suggestions",
"{",
"output",
"=",
"append",
"(",
"output",
",",
"suggestion",
".",
"Term",
")",
"\n",
"}",
"\n",
"return",
"output",
"\n",
"}"
] | // For a given input string, suggests potential replacements | [
"For",
"a",
"given",
"input",
"string",
"suggests",
"potential",
"replacements"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L553-L562 |
1,033 | sajari/fuzzy | fuzzy.go | SpellCheck | func (model *Model) SpellCheck(input string) string {
model.RLock()
suggestions := model.suggestPotential(input, false)
model.RUnlock()
return best(input, suggestions)
} | go | func (model *Model) SpellCheck(input string) string {
model.RLock()
suggestions := model.suggestPotential(input, false)
model.RUnlock()
return best(input, suggestions)
} | [
"func",
"(",
"model",
"*",
"Model",
")",
"SpellCheck",
"(",
"input",
"string",
")",
"string",
"{",
"model",
".",
"RLock",
"(",
")",
"\n",
"suggestions",
":=",
"model",
".",
"suggestPotential",
"(",
"input",
",",
"false",
")",
"\n",
"model",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"best",
"(",
"input",
",",
"suggestions",
")",
"\n",
"}"
] | // Return the most likely correction for the input term | [
"Return",
"the",
"most",
"likely",
"correction",
"for",
"the",
"input",
"term"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L565-L570 |
1,034 | sajari/fuzzy | fuzzy.go | SpellCheckSuggestions | func (model *Model) SpellCheckSuggestions(input string, n int) []string {
model.RLock()
suggestions := model.suggestPotential(input, true)
model.RUnlock()
return bestn(input, suggestions, n)
} | go | func (model *Model) SpellCheckSuggestions(input string, n int) []string {
model.RLock()
suggestions := model.suggestPotential(input, true)
model.RUnlock()
return bestn(input, suggestions, n)
} | [
"func",
"(",
"model",
"*",
"Model",
")",
"SpellCheckSuggestions",
"(",
"input",
"string",
",",
"n",
"int",
")",
"[",
"]",
"string",
"{",
"model",
".",
"RLock",
"(",
")",
"\n",
"suggestions",
":=",
"model",
".",
"suggestPotential",
"(",
"input",
",",
"true",
")",
"\n",
"model",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"bestn",
"(",
"input",
",",
"suggestions",
",",
"n",
")",
"\n",
"}"
] | // Return the most likely corrections in order from best to worst | [
"Return",
"the",
"most",
"likely",
"corrections",
"in",
"order",
"from",
"best",
"to",
"worst"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L573-L578 |
1,035 | sajari/fuzzy | fuzzy.go | updateSuffixArr | func (model *Model) updateSuffixArr() {
if !model.UseAutocomplete {
return
}
model.RLock()
termArr := make([]string, 0, 1000)
for term, count := range model.Data {
if count.Corpus > model.Threshold || count.Query > 0 { // TODO: query threshold?
termArr = append(termArr, term)
}
}
model.SuffixArrConcat = "\x00" + strings.Join(termArr, "\x00") + "\x00"
model.SuffixArr = suffixarray.New([]byte(model.SuffixArrConcat))
model.SuffDivergence = 0
model.RUnlock()
} | go | func (model *Model) updateSuffixArr() {
if !model.UseAutocomplete {
return
}
model.RLock()
termArr := make([]string, 0, 1000)
for term, count := range model.Data {
if count.Corpus > model.Threshold || count.Query > 0 { // TODO: query threshold?
termArr = append(termArr, term)
}
}
model.SuffixArrConcat = "\x00" + strings.Join(termArr, "\x00") + "\x00"
model.SuffixArr = suffixarray.New([]byte(model.SuffixArrConcat))
model.SuffDivergence = 0
model.RUnlock()
} | [
"func",
"(",
"model",
"*",
"Model",
")",
"updateSuffixArr",
"(",
")",
"{",
"if",
"!",
"model",
".",
"UseAutocomplete",
"{",
"return",
"\n",
"}",
"\n",
"model",
".",
"RLock",
"(",
")",
"\n",
"termArr",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"1000",
")",
"\n",
"for",
"term",
",",
"count",
":=",
"range",
"model",
".",
"Data",
"{",
"if",
"count",
".",
"Corpus",
">",
"model",
".",
"Threshold",
"||",
"count",
".",
"Query",
">",
"0",
"{",
"// TODO: query threshold?",
"termArr",
"=",
"append",
"(",
"termArr",
",",
"term",
")",
"\n",
"}",
"\n",
"}",
"\n",
"model",
".",
"SuffixArrConcat",
"=",
"\"",
"\\x00",
"\"",
"+",
"strings",
".",
"Join",
"(",
"termArr",
",",
"\"",
"\\x00",
"\"",
")",
"+",
"\"",
"\\x00",
"\"",
"\n",
"model",
".",
"SuffixArr",
"=",
"suffixarray",
".",
"New",
"(",
"[",
"]",
"byte",
"(",
"model",
".",
"SuffixArrConcat",
")",
")",
"\n",
"model",
".",
"SuffDivergence",
"=",
"0",
"\n",
"model",
".",
"RUnlock",
"(",
")",
"\n",
"}"
] | // Takes the known dictionary listing and creates a suffix array
// model for these terms. If a model already existed, it is discarded | [
"Takes",
"the",
"known",
"dictionary",
"listing",
"and",
"creates",
"a",
"suffix",
"array",
"model",
"for",
"these",
"terms",
".",
"If",
"a",
"model",
"already",
"existed",
"it",
"is",
"discarded"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L611-L626 |
1,036 | sajari/fuzzy | fuzzy.go | Autocomplete | func (model *Model) Autocomplete(input string) ([]string, error) {
model.RLock()
defer model.RUnlock()
if !model.UseAutocomplete {
return []string{}, errors.New("Autocomplete is disabled")
}
if len(input) == 0 {
return []string{}, errors.New("Input cannot have length zero")
}
express := "\x00" + input + "[^\x00]*"
match, err := regexp.Compile(express)
if err != nil {
return []string{}, err
}
matches := model.SuffixArr.FindAllIndex(match, -1)
a := &Autos{Results: make([]string, 0, len(matches)), Model: model}
for _, m := range matches {
str := strings.Trim(model.SuffixArrConcat[m[0]:m[1]], "\x00")
if count, ok := model.Data[str]; ok {
if count.Corpus > model.Threshold || count.Query > 0 {
a.Results = append(a.Results, str)
}
}
}
sort.Sort(a)
if len(a.Results) >= 10 {
return a.Results[:10], nil
}
return a.Results, nil
} | go | func (model *Model) Autocomplete(input string) ([]string, error) {
model.RLock()
defer model.RUnlock()
if !model.UseAutocomplete {
return []string{}, errors.New("Autocomplete is disabled")
}
if len(input) == 0 {
return []string{}, errors.New("Input cannot have length zero")
}
express := "\x00" + input + "[^\x00]*"
match, err := regexp.Compile(express)
if err != nil {
return []string{}, err
}
matches := model.SuffixArr.FindAllIndex(match, -1)
a := &Autos{Results: make([]string, 0, len(matches)), Model: model}
for _, m := range matches {
str := strings.Trim(model.SuffixArrConcat[m[0]:m[1]], "\x00")
if count, ok := model.Data[str]; ok {
if count.Corpus > model.Threshold || count.Query > 0 {
a.Results = append(a.Results, str)
}
}
}
sort.Sort(a)
if len(a.Results) >= 10 {
return a.Results[:10], nil
}
return a.Results, nil
} | [
"func",
"(",
"model",
"*",
"Model",
")",
"Autocomplete",
"(",
"input",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"model",
".",
"RLock",
"(",
")",
"\n",
"defer",
"model",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"!",
"model",
".",
"UseAutocomplete",
"{",
"return",
"[",
"]",
"string",
"{",
"}",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"input",
")",
"==",
"0",
"{",
"return",
"[",
"]",
"string",
"{",
"}",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"express",
":=",
"\"",
"\\x00",
"\"",
"+",
"input",
"+",
"\"",
"\\x00",
"\"",
"\n",
"match",
",",
"err",
":=",
"regexp",
".",
"Compile",
"(",
"express",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"[",
"]",
"string",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"matches",
":=",
"model",
".",
"SuffixArr",
".",
"FindAllIndex",
"(",
"match",
",",
"-",
"1",
")",
"\n",
"a",
":=",
"&",
"Autos",
"{",
"Results",
":",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"matches",
")",
")",
",",
"Model",
":",
"model",
"}",
"\n",
"for",
"_",
",",
"m",
":=",
"range",
"matches",
"{",
"str",
":=",
"strings",
".",
"Trim",
"(",
"model",
".",
"SuffixArrConcat",
"[",
"m",
"[",
"0",
"]",
":",
"m",
"[",
"1",
"]",
"]",
",",
"\"",
"\\x00",
"\"",
")",
"\n",
"if",
"count",
",",
"ok",
":=",
"model",
".",
"Data",
"[",
"str",
"]",
";",
"ok",
"{",
"if",
"count",
".",
"Corpus",
">",
"model",
".",
"Threshold",
"||",
"count",
".",
"Query",
">",
"0",
"{",
"a",
".",
"Results",
"=",
"append",
"(",
"a",
".",
"Results",
",",
"str",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"a",
")",
"\n",
"if",
"len",
"(",
"a",
".",
"Results",
")",
">=",
"10",
"{",
"return",
"a",
".",
"Results",
"[",
":",
"10",
"]",
",",
"nil",
"\n",
"}",
"\n",
"return",
"a",
".",
"Results",
",",
"nil",
"\n",
"}"
] | // For a given string, autocomplete using the suffix array model | [
"For",
"a",
"given",
"string",
"autocomplete",
"using",
"the",
"suffix",
"array",
"model"
] | 243c923763cac789d1196949a834ca698dbd7a28 | https://github.com/sajari/fuzzy/blob/243c923763cac789d1196949a834ca698dbd7a28/fuzzy.go#L629-L658 |
1,037 | jonboulle/clockwork | ticker.go | tick | func (ft *fakeTicker) tick() {
tick := ft.clock.Now()
for {
tick = tick.Add(ft.period)
remaining := tick.Sub(ft.clock.Now())
if remaining <= 0 {
// The tick should have already happened. This can happen when
// Advance() is called on the fake clock with a duration larger
// than this ticker's period.
select {
case ft.c <- tick:
default:
}
continue
}
select {
case <-ft.stop:
return
case <-ft.clock.After(remaining):
select {
case ft.c <- tick:
default:
}
}
}
} | go | func (ft *fakeTicker) tick() {
tick := ft.clock.Now()
for {
tick = tick.Add(ft.period)
remaining := tick.Sub(ft.clock.Now())
if remaining <= 0 {
// The tick should have already happened. This can happen when
// Advance() is called on the fake clock with a duration larger
// than this ticker's period.
select {
case ft.c <- tick:
default:
}
continue
}
select {
case <-ft.stop:
return
case <-ft.clock.After(remaining):
select {
case ft.c <- tick:
default:
}
}
}
} | [
"func",
"(",
"ft",
"*",
"fakeTicker",
")",
"tick",
"(",
")",
"{",
"tick",
":=",
"ft",
".",
"clock",
".",
"Now",
"(",
")",
"\n",
"for",
"{",
"tick",
"=",
"tick",
".",
"Add",
"(",
"ft",
".",
"period",
")",
"\n",
"remaining",
":=",
"tick",
".",
"Sub",
"(",
"ft",
".",
"clock",
".",
"Now",
"(",
")",
")",
"\n",
"if",
"remaining",
"<=",
"0",
"{",
"// The tick should have already happened. This can happen when",
"// Advance() is called on the fake clock with a duration larger",
"// than this ticker's period.",
"select",
"{",
"case",
"ft",
".",
"c",
"<-",
"tick",
":",
"default",
":",
"}",
"\n",
"continue",
"\n",
"}",
"\n\n",
"select",
"{",
"case",
"<-",
"ft",
".",
"stop",
":",
"return",
"\n",
"case",
"<-",
"ft",
".",
"clock",
".",
"After",
"(",
"remaining",
")",
":",
"select",
"{",
"case",
"ft",
".",
"c",
"<-",
"tick",
":",
"default",
":",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // tick sends the tick time to the ticker channel after every period.
// Tick events are discarded if the underlying ticker channel does
// not have enough capacity. | [
"tick",
"sends",
"the",
"tick",
"time",
"to",
"the",
"ticker",
"channel",
"after",
"every",
"period",
".",
"Tick",
"events",
"are",
"discarded",
"if",
"the",
"underlying",
"ticker",
"channel",
"does",
"not",
"have",
"enough",
"capacity",
"."
] | 62fb9bc030d14f92c58df3c1601e50a0e445edef | https://github.com/jonboulle/clockwork/blob/62fb9bc030d14f92c58df3c1601e50a0e445edef/ticker.go#L40-L66 |
1,038 | jonboulle/clockwork | clockwork.go | After | func (fc *fakeClock) After(d time.Duration) <-chan time.Time {
fc.l.Lock()
defer fc.l.Unlock()
now := fc.time
done := make(chan time.Time, 1)
if d.Nanoseconds() == 0 {
// special case - trigger immediately
done <- now
} else {
// otherwise, add to the set of sleepers
s := &sleeper{
until: now.Add(d),
done: done,
}
fc.sleepers = append(fc.sleepers, s)
// and notify any blockers
fc.blockers = notifyBlockers(fc.blockers, len(fc.sleepers))
}
return done
} | go | func (fc *fakeClock) After(d time.Duration) <-chan time.Time {
fc.l.Lock()
defer fc.l.Unlock()
now := fc.time
done := make(chan time.Time, 1)
if d.Nanoseconds() == 0 {
// special case - trigger immediately
done <- now
} else {
// otherwise, add to the set of sleepers
s := &sleeper{
until: now.Add(d),
done: done,
}
fc.sleepers = append(fc.sleepers, s)
// and notify any blockers
fc.blockers = notifyBlockers(fc.blockers, len(fc.sleepers))
}
return done
} | [
"func",
"(",
"fc",
"*",
"fakeClock",
")",
"After",
"(",
"d",
"time",
".",
"Duration",
")",
"<-",
"chan",
"time",
".",
"Time",
"{",
"fc",
".",
"l",
".",
"Lock",
"(",
")",
"\n",
"defer",
"fc",
".",
"l",
".",
"Unlock",
"(",
")",
"\n",
"now",
":=",
"fc",
".",
"time",
"\n",
"done",
":=",
"make",
"(",
"chan",
"time",
".",
"Time",
",",
"1",
")",
"\n",
"if",
"d",
".",
"Nanoseconds",
"(",
")",
"==",
"0",
"{",
"// special case - trigger immediately",
"done",
"<-",
"now",
"\n",
"}",
"else",
"{",
"// otherwise, add to the set of sleepers",
"s",
":=",
"&",
"sleeper",
"{",
"until",
":",
"now",
".",
"Add",
"(",
"d",
")",
",",
"done",
":",
"done",
",",
"}",
"\n",
"fc",
".",
"sleepers",
"=",
"append",
"(",
"fc",
".",
"sleepers",
",",
"s",
")",
"\n",
"// and notify any blockers",
"fc",
".",
"blockers",
"=",
"notifyBlockers",
"(",
"fc",
".",
"blockers",
",",
"len",
"(",
"fc",
".",
"sleepers",
")",
")",
"\n",
"}",
"\n",
"return",
"done",
"\n",
"}"
] | // After mimics time.After; it waits for the given duration to elapse on the
// fakeClock, then sends the current time on the returned channel. | [
"After",
"mimics",
"time",
".",
"After",
";",
"it",
"waits",
"for",
"the",
"given",
"duration",
"to",
"elapse",
"on",
"the",
"fakeClock",
"then",
"sends",
"the",
"current",
"time",
"on",
"the",
"returned",
"channel",
"."
] | 62fb9bc030d14f92c58df3c1601e50a0e445edef | https://github.com/jonboulle/clockwork/blob/62fb9bc030d14f92c58df3c1601e50a0e445edef/clockwork.go#L95-L114 |
1,039 | jonboulle/clockwork | clockwork.go | Now | func (fc *fakeClock) Now() time.Time {
fc.l.RLock()
t := fc.time
fc.l.RUnlock()
return t
} | go | func (fc *fakeClock) Now() time.Time {
fc.l.RLock()
t := fc.time
fc.l.RUnlock()
return t
} | [
"func",
"(",
"fc",
"*",
"fakeClock",
")",
"Now",
"(",
")",
"time",
".",
"Time",
"{",
"fc",
".",
"l",
".",
"RLock",
"(",
")",
"\n",
"t",
":=",
"fc",
".",
"time",
"\n",
"fc",
".",
"l",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"t",
"\n",
"}"
] | // Time returns the current time of the fakeClock | [
"Time",
"returns",
"the",
"current",
"time",
"of",
"the",
"fakeClock"
] | 62fb9bc030d14f92c58df3c1601e50a0e445edef | https://github.com/jonboulle/clockwork/blob/62fb9bc030d14f92c58df3c1601e50a0e445edef/clockwork.go#L136-L141 |
1,040 | jonboulle/clockwork | clockwork.go | Since | func (fc *fakeClock) Since(t time.Time) time.Duration {
return fc.Now().Sub(t)
} | go | func (fc *fakeClock) Since(t time.Time) time.Duration {
return fc.Now().Sub(t)
} | [
"func",
"(",
"fc",
"*",
"fakeClock",
")",
"Since",
"(",
"t",
"time",
".",
"Time",
")",
"time",
".",
"Duration",
"{",
"return",
"fc",
".",
"Now",
"(",
")",
".",
"Sub",
"(",
"t",
")",
"\n",
"}"
] | // Since returns the duration that has passed since the given time on the fakeClock | [
"Since",
"returns",
"the",
"duration",
"that",
"has",
"passed",
"since",
"the",
"given",
"time",
"on",
"the",
"fakeClock"
] | 62fb9bc030d14f92c58df3c1601e50a0e445edef | https://github.com/jonboulle/clockwork/blob/62fb9bc030d14f92c58df3c1601e50a0e445edef/clockwork.go#L144-L146 |
1,041 | jonboulle/clockwork | clockwork.go | Advance | func (fc *fakeClock) Advance(d time.Duration) {
fc.l.Lock()
defer fc.l.Unlock()
end := fc.time.Add(d)
var newSleepers []*sleeper
for _, s := range fc.sleepers {
if end.Sub(s.until) >= 0 {
s.done <- end
} else {
newSleepers = append(newSleepers, s)
}
}
fc.sleepers = newSleepers
fc.blockers = notifyBlockers(fc.blockers, len(fc.sleepers))
fc.time = end
} | go | func (fc *fakeClock) Advance(d time.Duration) {
fc.l.Lock()
defer fc.l.Unlock()
end := fc.time.Add(d)
var newSleepers []*sleeper
for _, s := range fc.sleepers {
if end.Sub(s.until) >= 0 {
s.done <- end
} else {
newSleepers = append(newSleepers, s)
}
}
fc.sleepers = newSleepers
fc.blockers = notifyBlockers(fc.blockers, len(fc.sleepers))
fc.time = end
} | [
"func",
"(",
"fc",
"*",
"fakeClock",
")",
"Advance",
"(",
"d",
"time",
".",
"Duration",
")",
"{",
"fc",
".",
"l",
".",
"Lock",
"(",
")",
"\n",
"defer",
"fc",
".",
"l",
".",
"Unlock",
"(",
")",
"\n",
"end",
":=",
"fc",
".",
"time",
".",
"Add",
"(",
"d",
")",
"\n",
"var",
"newSleepers",
"[",
"]",
"*",
"sleeper",
"\n",
"for",
"_",
",",
"s",
":=",
"range",
"fc",
".",
"sleepers",
"{",
"if",
"end",
".",
"Sub",
"(",
"s",
".",
"until",
")",
">=",
"0",
"{",
"s",
".",
"done",
"<-",
"end",
"\n",
"}",
"else",
"{",
"newSleepers",
"=",
"append",
"(",
"newSleepers",
",",
"s",
")",
"\n",
"}",
"\n",
"}",
"\n",
"fc",
".",
"sleepers",
"=",
"newSleepers",
"\n",
"fc",
".",
"blockers",
"=",
"notifyBlockers",
"(",
"fc",
".",
"blockers",
",",
"len",
"(",
"fc",
".",
"sleepers",
")",
")",
"\n",
"fc",
".",
"time",
"=",
"end",
"\n",
"}"
] | // Advance advances fakeClock to a new point in time, ensuring channels from any
// previous invocations of After are notified appropriately before returning | [
"Advance",
"advances",
"fakeClock",
"to",
"a",
"new",
"point",
"in",
"time",
"ensuring",
"channels",
"from",
"any",
"previous",
"invocations",
"of",
"After",
"are",
"notified",
"appropriately",
"before",
"returning"
] | 62fb9bc030d14f92c58df3c1601e50a0e445edef | https://github.com/jonboulle/clockwork/blob/62fb9bc030d14f92c58df3c1601e50a0e445edef/clockwork.go#L161-L176 |
1,042 | go-stack/stack | stack.go | Caller | func Caller(skip int) Call {
// As of Go 1.9 we need room for up to three PC entries.
//
// 0. An entry for the stack frame prior to the target to check for
// special handling needed if that prior entry is runtime.sigpanic.
// 1. A possible second entry to hold metadata about skipped inlined
// functions. If inline functions were not skipped the target frame
// PC will be here.
// 2. A third entry for the target frame PC when the second entry
// is used for skipped inline functions.
var pcs [3]uintptr
n := runtime.Callers(skip+1, pcs[:])
frames := runtime.CallersFrames(pcs[:n])
frame, _ := frames.Next()
frame, _ = frames.Next()
return Call{
frame: frame,
}
} | go | func Caller(skip int) Call {
// As of Go 1.9 we need room for up to three PC entries.
//
// 0. An entry for the stack frame prior to the target to check for
// special handling needed if that prior entry is runtime.sigpanic.
// 1. A possible second entry to hold metadata about skipped inlined
// functions. If inline functions were not skipped the target frame
// PC will be here.
// 2. A third entry for the target frame PC when the second entry
// is used for skipped inline functions.
var pcs [3]uintptr
n := runtime.Callers(skip+1, pcs[:])
frames := runtime.CallersFrames(pcs[:n])
frame, _ := frames.Next()
frame, _ = frames.Next()
return Call{
frame: frame,
}
} | [
"func",
"Caller",
"(",
"skip",
"int",
")",
"Call",
"{",
"// As of Go 1.9 we need room for up to three PC entries.",
"//",
"// 0. An entry for the stack frame prior to the target to check for",
"// special handling needed if that prior entry is runtime.sigpanic.",
"// 1. A possible second entry to hold metadata about skipped inlined",
"// functions. If inline functions were not skipped the target frame",
"// PC will be here.",
"// 2. A third entry for the target frame PC when the second entry",
"// is used for skipped inline functions.",
"var",
"pcs",
"[",
"3",
"]",
"uintptr",
"\n",
"n",
":=",
"runtime",
".",
"Callers",
"(",
"skip",
"+",
"1",
",",
"pcs",
"[",
":",
"]",
")",
"\n",
"frames",
":=",
"runtime",
".",
"CallersFrames",
"(",
"pcs",
"[",
":",
"n",
"]",
")",
"\n",
"frame",
",",
"_",
":=",
"frames",
".",
"Next",
"(",
")",
"\n",
"frame",
",",
"_",
"=",
"frames",
".",
"Next",
"(",
")",
"\n\n",
"return",
"Call",
"{",
"frame",
":",
"frame",
",",
"}",
"\n",
"}"
] | // Caller returns a Call from the stack of the current goroutine. The argument
// skip is the number of stack frames to ascend, with 0 identifying the
// calling function. | [
"Caller",
"returns",
"a",
"Call",
"from",
"the",
"stack",
"of",
"the",
"current",
"goroutine",
".",
"The",
"argument",
"skip",
"is",
"the",
"number",
"of",
"stack",
"frames",
"to",
"ascend",
"with",
"0",
"identifying",
"the",
"calling",
"function",
"."
] | 2fee6af1a9795aafbe0253a0cfbdf668e1fb8a9a | https://github.com/go-stack/stack/blob/2fee6af1a9795aafbe0253a0cfbdf668e1fb8a9a/stack.go#L32-L51 |
1,043 | go-stack/stack | stack.go | Trace | func Trace() CallStack {
var pcs [512]uintptr
n := runtime.Callers(1, pcs[:])
frames := runtime.CallersFrames(pcs[:n])
cs := make(CallStack, 0, n)
// Skip extra frame retrieved just to make sure the runtime.sigpanic
// special case is handled.
frame, more := frames.Next()
for more {
frame, more = frames.Next()
cs = append(cs, Call{frame: frame})
}
return cs
} | go | func Trace() CallStack {
var pcs [512]uintptr
n := runtime.Callers(1, pcs[:])
frames := runtime.CallersFrames(pcs[:n])
cs := make(CallStack, 0, n)
// Skip extra frame retrieved just to make sure the runtime.sigpanic
// special case is handled.
frame, more := frames.Next()
for more {
frame, more = frames.Next()
cs = append(cs, Call{frame: frame})
}
return cs
} | [
"func",
"Trace",
"(",
")",
"CallStack",
"{",
"var",
"pcs",
"[",
"512",
"]",
"uintptr",
"\n",
"n",
":=",
"runtime",
".",
"Callers",
"(",
"1",
",",
"pcs",
"[",
":",
"]",
")",
"\n\n",
"frames",
":=",
"runtime",
".",
"CallersFrames",
"(",
"pcs",
"[",
":",
"n",
"]",
")",
"\n",
"cs",
":=",
"make",
"(",
"CallStack",
",",
"0",
",",
"n",
")",
"\n\n",
"// Skip extra frame retrieved just to make sure the runtime.sigpanic",
"// special case is handled.",
"frame",
",",
"more",
":=",
"frames",
".",
"Next",
"(",
")",
"\n\n",
"for",
"more",
"{",
"frame",
",",
"more",
"=",
"frames",
".",
"Next",
"(",
")",
"\n",
"cs",
"=",
"append",
"(",
"cs",
",",
"Call",
"{",
"frame",
":",
"frame",
"}",
")",
"\n",
"}",
"\n\n",
"return",
"cs",
"\n",
"}"
] | // Trace returns a CallStack for the current goroutine with element 0
// identifying the calling function. | [
"Trace",
"returns",
"a",
"CallStack",
"for",
"the",
"current",
"goroutine",
"with",
"element",
"0",
"identifying",
"the",
"calling",
"function",
"."
] | 2fee6af1a9795aafbe0253a0cfbdf668e1fb8a9a | https://github.com/go-stack/stack/blob/2fee6af1a9795aafbe0253a0cfbdf668e1fb8a9a/stack.go#L213-L230 |
1,044 | go-stack/stack | stack.go | TrimBelow | func (cs CallStack) TrimBelow(c Call) CallStack {
for len(cs) > 0 && cs[0] != c {
cs = cs[1:]
}
return cs
} | go | func (cs CallStack) TrimBelow(c Call) CallStack {
for len(cs) > 0 && cs[0] != c {
cs = cs[1:]
}
return cs
} | [
"func",
"(",
"cs",
"CallStack",
")",
"TrimBelow",
"(",
"c",
"Call",
")",
"CallStack",
"{",
"for",
"len",
"(",
"cs",
")",
">",
"0",
"&&",
"cs",
"[",
"0",
"]",
"!=",
"c",
"{",
"cs",
"=",
"cs",
"[",
"1",
":",
"]",
"\n",
"}",
"\n",
"return",
"cs",
"\n",
"}"
] | // TrimBelow returns a slice of the CallStack with all entries below c
// removed. | [
"TrimBelow",
"returns",
"a",
"slice",
"of",
"the",
"CallStack",
"with",
"all",
"entries",
"below",
"c",
"removed",
"."
] | 2fee6af1a9795aafbe0253a0cfbdf668e1fb8a9a | https://github.com/go-stack/stack/blob/2fee6af1a9795aafbe0253a0cfbdf668e1fb8a9a/stack.go#L234-L239 |
1,045 | go-stack/stack | stack.go | TrimAbove | func (cs CallStack) TrimAbove(c Call) CallStack {
for len(cs) > 0 && cs[len(cs)-1] != c {
cs = cs[:len(cs)-1]
}
return cs
} | go | func (cs CallStack) TrimAbove(c Call) CallStack {
for len(cs) > 0 && cs[len(cs)-1] != c {
cs = cs[:len(cs)-1]
}
return cs
} | [
"func",
"(",
"cs",
"CallStack",
")",
"TrimAbove",
"(",
"c",
"Call",
")",
"CallStack",
"{",
"for",
"len",
"(",
"cs",
")",
">",
"0",
"&&",
"cs",
"[",
"len",
"(",
"cs",
")",
"-",
"1",
"]",
"!=",
"c",
"{",
"cs",
"=",
"cs",
"[",
":",
"len",
"(",
"cs",
")",
"-",
"1",
"]",
"\n",
"}",
"\n",
"return",
"cs",
"\n",
"}"
] | // TrimAbove returns a slice of the CallStack with all entries above c
// removed. | [
"TrimAbove",
"returns",
"a",
"slice",
"of",
"the",
"CallStack",
"with",
"all",
"entries",
"above",
"c",
"removed",
"."
] | 2fee6af1a9795aafbe0253a0cfbdf668e1fb8a9a | https://github.com/go-stack/stack/blob/2fee6af1a9795aafbe0253a0cfbdf668e1fb8a9a/stack.go#L243-L248 |
1,046 | go-stack/stack | stack.go | pkgPrefix | func pkgPrefix(funcName string) string {
const pathSep = "/"
end := strings.LastIndex(funcName, pathSep)
if end == -1 {
return ""
}
return funcName[:end]
} | go | func pkgPrefix(funcName string) string {
const pathSep = "/"
end := strings.LastIndex(funcName, pathSep)
if end == -1 {
return ""
}
return funcName[:end]
} | [
"func",
"pkgPrefix",
"(",
"funcName",
"string",
")",
"string",
"{",
"const",
"pathSep",
"=",
"\"",
"\"",
"\n",
"end",
":=",
"strings",
".",
"LastIndex",
"(",
"funcName",
",",
"pathSep",
")",
"\n",
"if",
"end",
"==",
"-",
"1",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"funcName",
"[",
":",
"end",
"]",
"\n",
"}"
] | // pkgPrefix returns the import path of the function's package with the final
// segment removed. | [
"pkgPrefix",
"returns",
"the",
"import",
"path",
"of",
"the",
"function",
"s",
"package",
"with",
"the",
"final",
"segment",
"removed",
"."
] | 2fee6af1a9795aafbe0253a0cfbdf668e1fb8a9a | https://github.com/go-stack/stack/blob/2fee6af1a9795aafbe0253a0cfbdf668e1fb8a9a/stack.go#L345-L352 |
1,047 | go-stack/stack | stack.go | pathSuffix | func pathSuffix(path string) string {
const pathSep = "/"
lastSep := strings.LastIndex(path, pathSep)
if lastSep == -1 {
return path
}
return path[strings.LastIndex(path[:lastSep], pathSep)+1:]
} | go | func pathSuffix(path string) string {
const pathSep = "/"
lastSep := strings.LastIndex(path, pathSep)
if lastSep == -1 {
return path
}
return path[strings.LastIndex(path[:lastSep], pathSep)+1:]
} | [
"func",
"pathSuffix",
"(",
"path",
"string",
")",
"string",
"{",
"const",
"pathSep",
"=",
"\"",
"\"",
"\n",
"lastSep",
":=",
"strings",
".",
"LastIndex",
"(",
"path",
",",
"pathSep",
")",
"\n",
"if",
"lastSep",
"==",
"-",
"1",
"{",
"return",
"path",
"\n",
"}",
"\n",
"return",
"path",
"[",
"strings",
".",
"LastIndex",
"(",
"path",
"[",
":",
"lastSep",
"]",
",",
"pathSep",
")",
"+",
"1",
":",
"]",
"\n",
"}"
] | // pathSuffix returns the last two segments of path. | [
"pathSuffix",
"returns",
"the",
"last",
"two",
"segments",
"of",
"path",
"."
] | 2fee6af1a9795aafbe0253a0cfbdf668e1fb8a9a | https://github.com/go-stack/stack/blob/2fee6af1a9795aafbe0253a0cfbdf668e1fb8a9a/stack.go#L355-L362 |
1,048 | go-stack/stack | stack.go | TrimRuntime | func (cs CallStack) TrimRuntime() CallStack {
for len(cs) > 0 && inGoroot(cs[len(cs)-1]) {
cs = cs[:len(cs)-1]
}
return cs
} | go | func (cs CallStack) TrimRuntime() CallStack {
for len(cs) > 0 && inGoroot(cs[len(cs)-1]) {
cs = cs[:len(cs)-1]
}
return cs
} | [
"func",
"(",
"cs",
"CallStack",
")",
"TrimRuntime",
"(",
")",
"CallStack",
"{",
"for",
"len",
"(",
"cs",
")",
">",
"0",
"&&",
"inGoroot",
"(",
"cs",
"[",
"len",
"(",
"cs",
")",
"-",
"1",
"]",
")",
"{",
"cs",
"=",
"cs",
"[",
":",
"len",
"(",
"cs",
")",
"-",
"1",
"]",
"\n",
"}",
"\n",
"return",
"cs",
"\n",
"}"
] | // TrimRuntime returns a slice of the CallStack with the topmost entries from
// the go runtime removed. It considers any calls originating from unknown
// files, files under GOROOT, or _testmain.go as part of the runtime. | [
"TrimRuntime",
"returns",
"a",
"slice",
"of",
"the",
"CallStack",
"with",
"the",
"topmost",
"entries",
"from",
"the",
"go",
"runtime",
"removed",
".",
"It",
"considers",
"any",
"calls",
"originating",
"from",
"unknown",
"files",
"files",
"under",
"GOROOT",
"or",
"_testmain",
".",
"go",
"as",
"part",
"of",
"the",
"runtime",
"."
] | 2fee6af1a9795aafbe0253a0cfbdf668e1fb8a9a | https://github.com/go-stack/stack/blob/2fee6af1a9795aafbe0253a0cfbdf668e1fb8a9a/stack.go#L395-L400 |
1,049 | eapache/queue | queue.go | resize | func (q *Queue) resize() {
newBuf := make([]interface{}, q.count<<1)
if q.tail > q.head {
copy(newBuf, q.buf[q.head:q.tail])
} else {
n := copy(newBuf, q.buf[q.head:])
copy(newBuf[n:], q.buf[:q.tail])
}
q.head = 0
q.tail = q.count
q.buf = newBuf
} | go | func (q *Queue) resize() {
newBuf := make([]interface{}, q.count<<1)
if q.tail > q.head {
copy(newBuf, q.buf[q.head:q.tail])
} else {
n := copy(newBuf, q.buf[q.head:])
copy(newBuf[n:], q.buf[:q.tail])
}
q.head = 0
q.tail = q.count
q.buf = newBuf
} | [
"func",
"(",
"q",
"*",
"Queue",
")",
"resize",
"(",
")",
"{",
"newBuf",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"q",
".",
"count",
"<<",
"1",
")",
"\n\n",
"if",
"q",
".",
"tail",
">",
"q",
".",
"head",
"{",
"copy",
"(",
"newBuf",
",",
"q",
".",
"buf",
"[",
"q",
".",
"head",
":",
"q",
".",
"tail",
"]",
")",
"\n",
"}",
"else",
"{",
"n",
":=",
"copy",
"(",
"newBuf",
",",
"q",
".",
"buf",
"[",
"q",
".",
"head",
":",
"]",
")",
"\n",
"copy",
"(",
"newBuf",
"[",
"n",
":",
"]",
",",
"q",
".",
"buf",
"[",
":",
"q",
".",
"tail",
"]",
")",
"\n",
"}",
"\n\n",
"q",
".",
"head",
"=",
"0",
"\n",
"q",
".",
"tail",
"=",
"q",
".",
"count",
"\n",
"q",
".",
"buf",
"=",
"newBuf",
"\n",
"}"
] | // resizes the queue to fit exactly twice its current contents
// this can result in shrinking if the queue is less than half-full | [
"resizes",
"the",
"queue",
"to",
"fit",
"exactly",
"twice",
"its",
"current",
"contents",
"this",
"can",
"result",
"in",
"shrinking",
"if",
"the",
"queue",
"is",
"less",
"than",
"half",
"-",
"full"
] | 093482f3f8ce946c05bcba64badd2c82369e084d | https://github.com/eapache/queue/blob/093482f3f8ce946c05bcba64badd2c82369e084d/queue.go#L34-L47 |
1,050 | eapache/queue | queue.go | Add | func (q *Queue) Add(elem interface{}) {
if q.count == len(q.buf) {
q.resize()
}
q.buf[q.tail] = elem
// bitwise modulus
q.tail = (q.tail + 1) & (len(q.buf) - 1)
q.count++
} | go | func (q *Queue) Add(elem interface{}) {
if q.count == len(q.buf) {
q.resize()
}
q.buf[q.tail] = elem
// bitwise modulus
q.tail = (q.tail + 1) & (len(q.buf) - 1)
q.count++
} | [
"func",
"(",
"q",
"*",
"Queue",
")",
"Add",
"(",
"elem",
"interface",
"{",
"}",
")",
"{",
"if",
"q",
".",
"count",
"==",
"len",
"(",
"q",
".",
"buf",
")",
"{",
"q",
".",
"resize",
"(",
")",
"\n",
"}",
"\n\n",
"q",
".",
"buf",
"[",
"q",
".",
"tail",
"]",
"=",
"elem",
"\n",
"// bitwise modulus",
"q",
".",
"tail",
"=",
"(",
"q",
".",
"tail",
"+",
"1",
")",
"&",
"(",
"len",
"(",
"q",
".",
"buf",
")",
"-",
"1",
")",
"\n",
"q",
".",
"count",
"++",
"\n",
"}"
] | // Add puts an element on the end of the queue. | [
"Add",
"puts",
"an",
"element",
"on",
"the",
"end",
"of",
"the",
"queue",
"."
] | 093482f3f8ce946c05bcba64badd2c82369e084d | https://github.com/eapache/queue/blob/093482f3f8ce946c05bcba64badd2c82369e084d/queue.go#L50-L59 |
1,051 | eapache/queue | queue.go | Peek | func (q *Queue) Peek() interface{} {
if q.count <= 0 {
panic("queue: Peek() called on empty queue")
}
return q.buf[q.head]
} | go | func (q *Queue) Peek() interface{} {
if q.count <= 0 {
panic("queue: Peek() called on empty queue")
}
return q.buf[q.head]
} | [
"func",
"(",
"q",
"*",
"Queue",
")",
"Peek",
"(",
")",
"interface",
"{",
"}",
"{",
"if",
"q",
".",
"count",
"<=",
"0",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"q",
".",
"buf",
"[",
"q",
".",
"head",
"]",
"\n",
"}"
] | // Peek returns the element at the head of the queue. This call panics
// if the queue is empty. | [
"Peek",
"returns",
"the",
"element",
"at",
"the",
"head",
"of",
"the",
"queue",
".",
"This",
"call",
"panics",
"if",
"the",
"queue",
"is",
"empty",
"."
] | 093482f3f8ce946c05bcba64badd2c82369e084d | https://github.com/eapache/queue/blob/093482f3f8ce946c05bcba64badd2c82369e084d/queue.go#L63-L68 |
1,052 | eapache/queue | queue.go | Get | func (q *Queue) Get(i int) interface{} {
// If indexing backwards, convert to positive index.
if i < 0 {
i += q.count
}
if i < 0 || i >= q.count {
panic("queue: Get() called with index out of range")
}
// bitwise modulus
return q.buf[(q.head+i)&(len(q.buf)-1)]
} | go | func (q *Queue) Get(i int) interface{} {
// If indexing backwards, convert to positive index.
if i < 0 {
i += q.count
}
if i < 0 || i >= q.count {
panic("queue: Get() called with index out of range")
}
// bitwise modulus
return q.buf[(q.head+i)&(len(q.buf)-1)]
} | [
"func",
"(",
"q",
"*",
"Queue",
")",
"Get",
"(",
"i",
"int",
")",
"interface",
"{",
"}",
"{",
"// If indexing backwards, convert to positive index.",
"if",
"i",
"<",
"0",
"{",
"i",
"+=",
"q",
".",
"count",
"\n",
"}",
"\n",
"if",
"i",
"<",
"0",
"||",
"i",
">=",
"q",
".",
"count",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// bitwise modulus",
"return",
"q",
".",
"buf",
"[",
"(",
"q",
".",
"head",
"+",
"i",
")",
"&",
"(",
"len",
"(",
"q",
".",
"buf",
")",
"-",
"1",
")",
"]",
"\n",
"}"
] | // Get returns the element at index i in the queue. If the index is
// invalid, the call will panic. This method accepts both positive and
// negative index values. Index 0 refers to the first element, and
// index -1 refers to the last. | [
"Get",
"returns",
"the",
"element",
"at",
"index",
"i",
"in",
"the",
"queue",
".",
"If",
"the",
"index",
"is",
"invalid",
"the",
"call",
"will",
"panic",
".",
"This",
"method",
"accepts",
"both",
"positive",
"and",
"negative",
"index",
"values",
".",
"Index",
"0",
"refers",
"to",
"the",
"first",
"element",
"and",
"index",
"-",
"1",
"refers",
"to",
"the",
"last",
"."
] | 093482f3f8ce946c05bcba64badd2c82369e084d | https://github.com/eapache/queue/blob/093482f3f8ce946c05bcba64badd2c82369e084d/queue.go#L74-L84 |
1,053 | eapache/queue | queue.go | Remove | func (q *Queue) Remove() interface{} {
if q.count <= 0 {
panic("queue: Remove() called on empty queue")
}
ret := q.buf[q.head]
q.buf[q.head] = nil
// bitwise modulus
q.head = (q.head + 1) & (len(q.buf) - 1)
q.count--
// Resize down if buffer 1/4 full.
if len(q.buf) > minQueueLen && (q.count<<2) == len(q.buf) {
q.resize()
}
return ret
} | go | func (q *Queue) Remove() interface{} {
if q.count <= 0 {
panic("queue: Remove() called on empty queue")
}
ret := q.buf[q.head]
q.buf[q.head] = nil
// bitwise modulus
q.head = (q.head + 1) & (len(q.buf) - 1)
q.count--
// Resize down if buffer 1/4 full.
if len(q.buf) > minQueueLen && (q.count<<2) == len(q.buf) {
q.resize()
}
return ret
} | [
"func",
"(",
"q",
"*",
"Queue",
")",
"Remove",
"(",
")",
"interface",
"{",
"}",
"{",
"if",
"q",
".",
"count",
"<=",
"0",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"ret",
":=",
"q",
".",
"buf",
"[",
"q",
".",
"head",
"]",
"\n",
"q",
".",
"buf",
"[",
"q",
".",
"head",
"]",
"=",
"nil",
"\n",
"// bitwise modulus",
"q",
".",
"head",
"=",
"(",
"q",
".",
"head",
"+",
"1",
")",
"&",
"(",
"len",
"(",
"q",
".",
"buf",
")",
"-",
"1",
")",
"\n",
"q",
".",
"count",
"--",
"\n",
"// Resize down if buffer 1/4 full.",
"if",
"len",
"(",
"q",
".",
"buf",
")",
">",
"minQueueLen",
"&&",
"(",
"q",
".",
"count",
"<<",
"2",
")",
"==",
"len",
"(",
"q",
".",
"buf",
")",
"{",
"q",
".",
"resize",
"(",
")",
"\n",
"}",
"\n",
"return",
"ret",
"\n",
"}"
] | // Remove removes and returns the element from the front of the queue. If the
// queue is empty, the call will panic. | [
"Remove",
"removes",
"and",
"returns",
"the",
"element",
"from",
"the",
"front",
"of",
"the",
"queue",
".",
"If",
"the",
"queue",
"is",
"empty",
"the",
"call",
"will",
"panic",
"."
] | 093482f3f8ce946c05bcba64badd2c82369e084d | https://github.com/eapache/queue/blob/093482f3f8ce946c05bcba64badd2c82369e084d/queue.go#L88-L102 |
1,054 | faiface/glhf | texture.go | SetPixels | func (t *Texture) SetPixels(x, y, w, h int, pixels []uint8) {
if len(pixels) != w*h*4 {
panic("set pixels: wrong number of pixels")
}
gl.TexSubImage2D(
gl.TEXTURE_2D,
0,
int32(x),
int32(y),
int32(w),
int32(h),
gl.RGBA,
gl.UNSIGNED_BYTE,
gl.Ptr(pixels),
)
} | go | func (t *Texture) SetPixels(x, y, w, h int, pixels []uint8) {
if len(pixels) != w*h*4 {
panic("set pixels: wrong number of pixels")
}
gl.TexSubImage2D(
gl.TEXTURE_2D,
0,
int32(x),
int32(y),
int32(w),
int32(h),
gl.RGBA,
gl.UNSIGNED_BYTE,
gl.Ptr(pixels),
)
} | [
"func",
"(",
"t",
"*",
"Texture",
")",
"SetPixels",
"(",
"x",
",",
"y",
",",
"w",
",",
"h",
"int",
",",
"pixels",
"[",
"]",
"uint8",
")",
"{",
"if",
"len",
"(",
"pixels",
")",
"!=",
"w",
"*",
"h",
"*",
"4",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"gl",
".",
"TexSubImage2D",
"(",
"gl",
".",
"TEXTURE_2D",
",",
"0",
",",
"int32",
"(",
"x",
")",
",",
"int32",
"(",
"y",
")",
",",
"int32",
"(",
"w",
")",
",",
"int32",
"(",
"h",
")",
",",
"gl",
".",
"RGBA",
",",
"gl",
".",
"UNSIGNED_BYTE",
",",
"gl",
".",
"Ptr",
"(",
"pixels",
")",
",",
")",
"\n",
"}"
] | // SetPixels sets the content of a sub-region of the Texture. Pixels must be an RGBA byte sequence. | [
"SetPixels",
"sets",
"the",
"content",
"of",
"a",
"sub",
"-",
"region",
"of",
"the",
"Texture",
".",
"Pixels",
"must",
"be",
"an",
"RGBA",
"byte",
"sequence",
"."
] | 82a6317ac380cdc61567d729fe48833d75b8108e | https://github.com/faiface/glhf/blob/82a6317ac380cdc61567d729fe48833d75b8108e/texture.go#L84-L99 |
1,055 | faiface/glhf | texture.go | Pixels | func (t *Texture) Pixels(x, y, w, h int) []uint8 {
pixels := make([]uint8, t.width*t.height*4)
gl.GetTexImage(
gl.TEXTURE_2D,
0,
gl.RGBA,
gl.UNSIGNED_BYTE,
gl.Ptr(pixels),
)
subPixels := make([]uint8, w*h*4)
for i := 0; i < h; i++ {
row := pixels[(i+y)*t.width*4+x*4 : (i+y)*t.width*4+(x+w)*4]
subRow := subPixels[i*w*4 : (i+1)*w*4]
copy(subRow, row)
}
return subPixels
} | go | func (t *Texture) Pixels(x, y, w, h int) []uint8 {
pixels := make([]uint8, t.width*t.height*4)
gl.GetTexImage(
gl.TEXTURE_2D,
0,
gl.RGBA,
gl.UNSIGNED_BYTE,
gl.Ptr(pixels),
)
subPixels := make([]uint8, w*h*4)
for i := 0; i < h; i++ {
row := pixels[(i+y)*t.width*4+x*4 : (i+y)*t.width*4+(x+w)*4]
subRow := subPixels[i*w*4 : (i+1)*w*4]
copy(subRow, row)
}
return subPixels
} | [
"func",
"(",
"t",
"*",
"Texture",
")",
"Pixels",
"(",
"x",
",",
"y",
",",
"w",
",",
"h",
"int",
")",
"[",
"]",
"uint8",
"{",
"pixels",
":=",
"make",
"(",
"[",
"]",
"uint8",
",",
"t",
".",
"width",
"*",
"t",
".",
"height",
"*",
"4",
")",
"\n",
"gl",
".",
"GetTexImage",
"(",
"gl",
".",
"TEXTURE_2D",
",",
"0",
",",
"gl",
".",
"RGBA",
",",
"gl",
".",
"UNSIGNED_BYTE",
",",
"gl",
".",
"Ptr",
"(",
"pixels",
")",
",",
")",
"\n",
"subPixels",
":=",
"make",
"(",
"[",
"]",
"uint8",
",",
"w",
"*",
"h",
"*",
"4",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"h",
";",
"i",
"++",
"{",
"row",
":=",
"pixels",
"[",
"(",
"i",
"+",
"y",
")",
"*",
"t",
".",
"width",
"*",
"4",
"+",
"x",
"*",
"4",
":",
"(",
"i",
"+",
"y",
")",
"*",
"t",
".",
"width",
"*",
"4",
"+",
"(",
"x",
"+",
"w",
")",
"*",
"4",
"]",
"\n",
"subRow",
":=",
"subPixels",
"[",
"i",
"*",
"w",
"*",
"4",
":",
"(",
"i",
"+",
"1",
")",
"*",
"w",
"*",
"4",
"]",
"\n",
"copy",
"(",
"subRow",
",",
"row",
")",
"\n",
"}",
"\n",
"return",
"subPixels",
"\n",
"}"
] | // Pixels returns the content of a sub-region of the Texture as an RGBA byte sequence. | [
"Pixels",
"returns",
"the",
"content",
"of",
"a",
"sub",
"-",
"region",
"of",
"the",
"Texture",
"as",
"an",
"RGBA",
"byte",
"sequence",
"."
] | 82a6317ac380cdc61567d729fe48833d75b8108e | https://github.com/faiface/glhf/blob/82a6317ac380cdc61567d729fe48833d75b8108e/texture.go#L102-L118 |
1,056 | faiface/glhf | texture.go | SetSmooth | func (t *Texture) SetSmooth(smooth bool) {
t.smooth = smooth
if smooth {
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
} else {
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
}
} | go | func (t *Texture) SetSmooth(smooth bool) {
t.smooth = smooth
if smooth {
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
} else {
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
}
} | [
"func",
"(",
"t",
"*",
"Texture",
")",
"SetSmooth",
"(",
"smooth",
"bool",
")",
"{",
"t",
".",
"smooth",
"=",
"smooth",
"\n",
"if",
"smooth",
"{",
"gl",
".",
"TexParameteri",
"(",
"gl",
".",
"TEXTURE_2D",
",",
"gl",
".",
"TEXTURE_MIN_FILTER",
",",
"gl",
".",
"LINEAR",
")",
"\n",
"gl",
".",
"TexParameteri",
"(",
"gl",
".",
"TEXTURE_2D",
",",
"gl",
".",
"TEXTURE_MAG_FILTER",
",",
"gl",
".",
"LINEAR",
")",
"\n",
"}",
"else",
"{",
"gl",
".",
"TexParameteri",
"(",
"gl",
".",
"TEXTURE_2D",
",",
"gl",
".",
"TEXTURE_MIN_FILTER",
",",
"gl",
".",
"NEAREST",
")",
"\n",
"gl",
".",
"TexParameteri",
"(",
"gl",
".",
"TEXTURE_2D",
",",
"gl",
".",
"TEXTURE_MAG_FILTER",
",",
"gl",
".",
"NEAREST",
")",
"\n",
"}",
"\n",
"}"
] | // SetSmooth sets whether the Texture should be drawn "smoothly" or "pixely".
//
// It affects how the Texture is drawn when zoomed. Smooth interpolates between the neighbour
// pixels, while pixely always chooses the nearest pixel. | [
"SetSmooth",
"sets",
"whether",
"the",
"Texture",
"should",
"be",
"drawn",
"smoothly",
"or",
"pixely",
".",
"It",
"affects",
"how",
"the",
"Texture",
"is",
"drawn",
"when",
"zoomed",
".",
"Smooth",
"interpolates",
"between",
"the",
"neighbour",
"pixels",
"while",
"pixely",
"always",
"chooses",
"the",
"nearest",
"pixel",
"."
] | 82a6317ac380cdc61567d729fe48833d75b8108e | https://github.com/faiface/glhf/blob/82a6317ac380cdc61567d729fe48833d75b8108e/texture.go#L124-L133 |
1,057 | faiface/glhf | attr.go | Size | func (af AttrFormat) Size() int {
total := 0
for _, attr := range af {
total += attr.Type.Size()
}
return total
} | go | func (af AttrFormat) Size() int {
total := 0
for _, attr := range af {
total += attr.Type.Size()
}
return total
} | [
"func",
"(",
"af",
"AttrFormat",
")",
"Size",
"(",
")",
"int",
"{",
"total",
":=",
"0",
"\n",
"for",
"_",
",",
"attr",
":=",
"range",
"af",
"{",
"total",
"+=",
"attr",
".",
"Type",
".",
"Size",
"(",
")",
"\n",
"}",
"\n",
"return",
"total",
"\n",
"}"
] | // Size returns the total size of all attributes of the AttrFormat. | [
"Size",
"returns",
"the",
"total",
"size",
"of",
"all",
"attributes",
"of",
"the",
"AttrFormat",
"."
] | 82a6317ac380cdc61567d729fe48833d75b8108e | https://github.com/faiface/glhf/blob/82a6317ac380cdc61567d729fe48833d75b8108e/attr.go#L10-L16 |
1,058 | faiface/glhf | attr.go | Size | func (at AttrType) Size() int {
switch at {
case Int:
return 4
case Float:
return 4
case Vec2:
return 2 * 4
case Vec3:
return 3 * 4
case Vec4:
return 4 * 4
case Mat2:
return 2 * 2 * 4
case Mat23:
return 2 * 3 * 4
case Mat24:
return 2 * 4 * 4
case Mat3:
return 3 * 3 * 4
case Mat32:
return 3 * 2 * 4
case Mat34:
return 3 * 4 * 4
case Mat4:
return 4 * 4 * 4
case Mat42:
return 4 * 2 * 4
case Mat43:
return 4 * 3 * 4
default:
panic("size of vertex attribute type: invalid type")
}
} | go | func (at AttrType) Size() int {
switch at {
case Int:
return 4
case Float:
return 4
case Vec2:
return 2 * 4
case Vec3:
return 3 * 4
case Vec4:
return 4 * 4
case Mat2:
return 2 * 2 * 4
case Mat23:
return 2 * 3 * 4
case Mat24:
return 2 * 4 * 4
case Mat3:
return 3 * 3 * 4
case Mat32:
return 3 * 2 * 4
case Mat34:
return 3 * 4 * 4
case Mat4:
return 4 * 4 * 4
case Mat42:
return 4 * 2 * 4
case Mat43:
return 4 * 3 * 4
default:
panic("size of vertex attribute type: invalid type")
}
} | [
"func",
"(",
"at",
"AttrType",
")",
"Size",
"(",
")",
"int",
"{",
"switch",
"at",
"{",
"case",
"Int",
":",
"return",
"4",
"\n",
"case",
"Float",
":",
"return",
"4",
"\n",
"case",
"Vec2",
":",
"return",
"2",
"*",
"4",
"\n",
"case",
"Vec3",
":",
"return",
"3",
"*",
"4",
"\n",
"case",
"Vec4",
":",
"return",
"4",
"*",
"4",
"\n",
"case",
"Mat2",
":",
"return",
"2",
"*",
"2",
"*",
"4",
"\n",
"case",
"Mat23",
":",
"return",
"2",
"*",
"3",
"*",
"4",
"\n",
"case",
"Mat24",
":",
"return",
"2",
"*",
"4",
"*",
"4",
"\n",
"case",
"Mat3",
":",
"return",
"3",
"*",
"3",
"*",
"4",
"\n",
"case",
"Mat32",
":",
"return",
"3",
"*",
"2",
"*",
"4",
"\n",
"case",
"Mat34",
":",
"return",
"3",
"*",
"4",
"*",
"4",
"\n",
"case",
"Mat4",
":",
"return",
"4",
"*",
"4",
"*",
"4",
"\n",
"case",
"Mat42",
":",
"return",
"4",
"*",
"2",
"*",
"4",
"\n",
"case",
"Mat43",
":",
"return",
"4",
"*",
"3",
"*",
"4",
"\n",
"default",
":",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}"
] | // Size returns the size of a type in bytes. | [
"Size",
"returns",
"the",
"size",
"of",
"a",
"type",
"in",
"bytes",
"."
] | 82a6317ac380cdc61567d729fe48833d75b8108e | https://github.com/faiface/glhf/blob/82a6317ac380cdc61567d729fe48833d75b8108e/attr.go#L47-L80 |
1,059 | faiface/glhf | frame.go | NewFrame | func NewFrame(width, height int, smooth bool) *Frame {
f := &Frame{
fb: binder{
restoreLoc: gl.FRAMEBUFFER_BINDING,
bindFunc: func(obj uint32) {
gl.BindFramebuffer(gl.FRAMEBUFFER, obj)
},
},
rf: binder{
restoreLoc: gl.READ_FRAMEBUFFER_BINDING,
bindFunc: func(obj uint32) {
gl.BindFramebuffer(gl.READ_FRAMEBUFFER, obj)
},
},
df: binder{
restoreLoc: gl.DRAW_FRAMEBUFFER_BINDING,
bindFunc: func(obj uint32) {
gl.BindFramebuffer(gl.DRAW_FRAMEBUFFER, obj)
},
},
tex: NewTexture(width, height, smooth, make([]uint8, width*height*4)),
}
gl.GenFramebuffers(1, &f.fb.obj)
f.fb.bind()
gl.FramebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, f.tex.tex.obj, 0)
f.fb.restore()
runtime.SetFinalizer(f, (*Frame).delete)
return f
} | go | func NewFrame(width, height int, smooth bool) *Frame {
f := &Frame{
fb: binder{
restoreLoc: gl.FRAMEBUFFER_BINDING,
bindFunc: func(obj uint32) {
gl.BindFramebuffer(gl.FRAMEBUFFER, obj)
},
},
rf: binder{
restoreLoc: gl.READ_FRAMEBUFFER_BINDING,
bindFunc: func(obj uint32) {
gl.BindFramebuffer(gl.READ_FRAMEBUFFER, obj)
},
},
df: binder{
restoreLoc: gl.DRAW_FRAMEBUFFER_BINDING,
bindFunc: func(obj uint32) {
gl.BindFramebuffer(gl.DRAW_FRAMEBUFFER, obj)
},
},
tex: NewTexture(width, height, smooth, make([]uint8, width*height*4)),
}
gl.GenFramebuffers(1, &f.fb.obj)
f.fb.bind()
gl.FramebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, f.tex.tex.obj, 0)
f.fb.restore()
runtime.SetFinalizer(f, (*Frame).delete)
return f
} | [
"func",
"NewFrame",
"(",
"width",
",",
"height",
"int",
",",
"smooth",
"bool",
")",
"*",
"Frame",
"{",
"f",
":=",
"&",
"Frame",
"{",
"fb",
":",
"binder",
"{",
"restoreLoc",
":",
"gl",
".",
"FRAMEBUFFER_BINDING",
",",
"bindFunc",
":",
"func",
"(",
"obj",
"uint32",
")",
"{",
"gl",
".",
"BindFramebuffer",
"(",
"gl",
".",
"FRAMEBUFFER",
",",
"obj",
")",
"\n",
"}",
",",
"}",
",",
"rf",
":",
"binder",
"{",
"restoreLoc",
":",
"gl",
".",
"READ_FRAMEBUFFER_BINDING",
",",
"bindFunc",
":",
"func",
"(",
"obj",
"uint32",
")",
"{",
"gl",
".",
"BindFramebuffer",
"(",
"gl",
".",
"READ_FRAMEBUFFER",
",",
"obj",
")",
"\n",
"}",
",",
"}",
",",
"df",
":",
"binder",
"{",
"restoreLoc",
":",
"gl",
".",
"DRAW_FRAMEBUFFER_BINDING",
",",
"bindFunc",
":",
"func",
"(",
"obj",
"uint32",
")",
"{",
"gl",
".",
"BindFramebuffer",
"(",
"gl",
".",
"DRAW_FRAMEBUFFER",
",",
"obj",
")",
"\n",
"}",
",",
"}",
",",
"tex",
":",
"NewTexture",
"(",
"width",
",",
"height",
",",
"smooth",
",",
"make",
"(",
"[",
"]",
"uint8",
",",
"width",
"*",
"height",
"*",
"4",
")",
")",
",",
"}",
"\n\n",
"gl",
".",
"GenFramebuffers",
"(",
"1",
",",
"&",
"f",
".",
"fb",
".",
"obj",
")",
"\n\n",
"f",
".",
"fb",
".",
"bind",
"(",
")",
"\n",
"gl",
".",
"FramebufferTexture2D",
"(",
"gl",
".",
"FRAMEBUFFER",
",",
"gl",
".",
"COLOR_ATTACHMENT0",
",",
"gl",
".",
"TEXTURE_2D",
",",
"f",
".",
"tex",
".",
"tex",
".",
"obj",
",",
"0",
")",
"\n",
"f",
".",
"fb",
".",
"restore",
"(",
")",
"\n\n",
"runtime",
".",
"SetFinalizer",
"(",
"f",
",",
"(",
"*",
"Frame",
")",
".",
"delete",
")",
"\n\n",
"return",
"f",
"\n",
"}"
] | // NewFrame creates a new fully transparent Frame with given dimensions in pixels. | [
"NewFrame",
"creates",
"a",
"new",
"fully",
"transparent",
"Frame",
"with",
"given",
"dimensions",
"in",
"pixels",
"."
] | 82a6317ac380cdc61567d729fe48833d75b8108e | https://github.com/faiface/glhf/blob/82a6317ac380cdc61567d729fe48833d75b8108e/frame.go#L17-L49 |
1,060 | faiface/glhf | orphan.go | Clear | func Clear(r, g, b, a float32) {
gl.ClearColor(r, g, b, a)
gl.Clear(gl.COLOR_BUFFER_BIT)
} | go | func Clear(r, g, b, a float32) {
gl.ClearColor(r, g, b, a)
gl.Clear(gl.COLOR_BUFFER_BIT)
} | [
"func",
"Clear",
"(",
"r",
",",
"g",
",",
"b",
",",
"a",
"float32",
")",
"{",
"gl",
".",
"ClearColor",
"(",
"r",
",",
"g",
",",
"b",
",",
"a",
")",
"\n",
"gl",
".",
"Clear",
"(",
"gl",
".",
"COLOR_BUFFER_BIT",
")",
"\n",
"}"
] | // Clear clears the current framebuffer or window with the given color. | [
"Clear",
"clears",
"the",
"current",
"framebuffer",
"or",
"window",
"with",
"the",
"given",
"color",
"."
] | 82a6317ac380cdc61567d729fe48833d75b8108e | https://github.com/faiface/glhf/blob/82a6317ac380cdc61567d729fe48833d75b8108e/orphan.go#L22-L25 |
1,061 | faiface/glhf | orphan.go | Bounds | func Bounds(x, y, w, h int) {
gl.Viewport(int32(x), int32(y), int32(w), int32(h))
gl.Scissor(int32(x), int32(y), int32(w), int32(h))
} | go | func Bounds(x, y, w, h int) {
gl.Viewport(int32(x), int32(y), int32(w), int32(h))
gl.Scissor(int32(x), int32(y), int32(w), int32(h))
} | [
"func",
"Bounds",
"(",
"x",
",",
"y",
",",
"w",
",",
"h",
"int",
")",
"{",
"gl",
".",
"Viewport",
"(",
"int32",
"(",
"x",
")",
",",
"int32",
"(",
"y",
")",
",",
"int32",
"(",
"w",
")",
",",
"int32",
"(",
"h",
")",
")",
"\n",
"gl",
".",
"Scissor",
"(",
"int32",
"(",
"x",
")",
",",
"int32",
"(",
"y",
")",
",",
"int32",
"(",
"w",
")",
",",
"int32",
"(",
"h",
")",
")",
"\n",
"}"
] | // Bounds sets the drawing bounds in pixels. Drawing outside bounds is always discarted.
//
// Calling this function is equivalent to setting viewport and scissor in OpenGL. | [
"Bounds",
"sets",
"the",
"drawing",
"bounds",
"in",
"pixels",
".",
"Drawing",
"outside",
"bounds",
"is",
"always",
"discarted",
".",
"Calling",
"this",
"function",
"is",
"equivalent",
"to",
"setting",
"viewport",
"and",
"scissor",
"in",
"OpenGL",
"."
] | 82a6317ac380cdc61567d729fe48833d75b8108e | https://github.com/faiface/glhf/blob/82a6317ac380cdc61567d729fe48833d75b8108e/orphan.go#L30-L33 |
1,062 | faiface/glhf | orphan.go | BlendFunc | func BlendFunc(src, dst BlendFactor) {
gl.BlendFunc(uint32(src), uint32(dst))
} | go | func BlendFunc(src, dst BlendFactor) {
gl.BlendFunc(uint32(src), uint32(dst))
} | [
"func",
"BlendFunc",
"(",
"src",
",",
"dst",
"BlendFactor",
")",
"{",
"gl",
".",
"BlendFunc",
"(",
"uint32",
"(",
"src",
")",
",",
"uint32",
"(",
"dst",
")",
")",
"\n",
"}"
] | // BlendFunc sets the source and destination blend factor. | [
"BlendFunc",
"sets",
"the",
"source",
"and",
"destination",
"blend",
"factor",
"."
] | 82a6317ac380cdc61567d729fe48833d75b8108e | https://github.com/faiface/glhf/blob/82a6317ac380cdc61567d729fe48833d75b8108e/orphan.go#L49-L51 |
1,063 | faiface/glhf | vertex.go | MakeVertexSlice | func MakeVertexSlice(shader *Shader, len, cap int) *VertexSlice {
if len > cap {
panic("failed to make vertex slice: len > cap")
}
return &VertexSlice{
va: newVertexArray(shader, cap),
i: 0,
j: len,
}
} | go | func MakeVertexSlice(shader *Shader, len, cap int) *VertexSlice {
if len > cap {
panic("failed to make vertex slice: len > cap")
}
return &VertexSlice{
va: newVertexArray(shader, cap),
i: 0,
j: len,
}
} | [
"func",
"MakeVertexSlice",
"(",
"shader",
"*",
"Shader",
",",
"len",
",",
"cap",
"int",
")",
"*",
"VertexSlice",
"{",
"if",
"len",
">",
"cap",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"&",
"VertexSlice",
"{",
"va",
":",
"newVertexArray",
"(",
"shader",
",",
"cap",
")",
",",
"i",
":",
"0",
",",
"j",
":",
"len",
",",
"}",
"\n",
"}"
] | // MakeVertexSlice allocates a new vertex array with specified capacity and returns a VertexSlice
// that points to it's first len elements.
//
// Note, that a vertex array is specialized for a specific shader and can't be used with another
// shader. | [
"MakeVertexSlice",
"allocates",
"a",
"new",
"vertex",
"array",
"with",
"specified",
"capacity",
"and",
"returns",
"a",
"VertexSlice",
"that",
"points",
"to",
"it",
"s",
"first",
"len",
"elements",
".",
"Note",
"that",
"a",
"vertex",
"array",
"is",
"specialized",
"for",
"a",
"specific",
"shader",
"and",
"can",
"t",
"be",
"used",
"with",
"another",
"shader",
"."
] | 82a6317ac380cdc61567d729fe48833d75b8108e | https://github.com/faiface/glhf/blob/82a6317ac380cdc61567d729fe48833d75b8108e/vertex.go#L31-L40 |
1,064 | faiface/glhf | vertex.go | SetLen | func (vs *VertexSlice) SetLen(len int) {
vs.End() // vs must have been Begin-ed before calling this method
*vs = vs.grow(len)
vs.Begin()
} | go | func (vs *VertexSlice) SetLen(len int) {
vs.End() // vs must have been Begin-ed before calling this method
*vs = vs.grow(len)
vs.Begin()
} | [
"func",
"(",
"vs",
"*",
"VertexSlice",
")",
"SetLen",
"(",
"len",
"int",
")",
"{",
"vs",
".",
"End",
"(",
")",
"// vs must have been Begin-ed before calling this method",
"\n",
"*",
"vs",
"=",
"vs",
".",
"grow",
"(",
"len",
")",
"\n",
"vs",
".",
"Begin",
"(",
")",
"\n",
"}"
] | // SetLen resizes the VertexSlice to length len. | [
"SetLen",
"resizes",
"the",
"VertexSlice",
"to",
"length",
"len",
"."
] | 82a6317ac380cdc61567d729fe48833d75b8108e | https://github.com/faiface/glhf/blob/82a6317ac380cdc61567d729fe48833d75b8108e/vertex.go#L64-L68 |
1,065 | faiface/glhf | vertex.go | grow | func (vs VertexSlice) grow(len int) VertexSlice {
if len <= vs.Cap() {
// capacity sufficient
return VertexSlice{
va: vs.va,
i: vs.i,
j: vs.i + len,
}
}
// grow the capacity
newCap := vs.Cap()
if newCap < 1024 {
newCap += newCap
} else {
newCap += newCap / 4
}
if newCap < len {
newCap = len
}
newVs := VertexSlice{
va: newVertexArray(vs.va.shader, newCap),
i: 0,
j: len,
}
// preserve the original content
newVs.Begin()
newVs.Slice(0, vs.Len()).SetVertexData(vs.VertexData())
newVs.End()
return newVs
} | go | func (vs VertexSlice) grow(len int) VertexSlice {
if len <= vs.Cap() {
// capacity sufficient
return VertexSlice{
va: vs.va,
i: vs.i,
j: vs.i + len,
}
}
// grow the capacity
newCap := vs.Cap()
if newCap < 1024 {
newCap += newCap
} else {
newCap += newCap / 4
}
if newCap < len {
newCap = len
}
newVs := VertexSlice{
va: newVertexArray(vs.va.shader, newCap),
i: 0,
j: len,
}
// preserve the original content
newVs.Begin()
newVs.Slice(0, vs.Len()).SetVertexData(vs.VertexData())
newVs.End()
return newVs
} | [
"func",
"(",
"vs",
"VertexSlice",
")",
"grow",
"(",
"len",
"int",
")",
"VertexSlice",
"{",
"if",
"len",
"<=",
"vs",
".",
"Cap",
"(",
")",
"{",
"// capacity sufficient",
"return",
"VertexSlice",
"{",
"va",
":",
"vs",
".",
"va",
",",
"i",
":",
"vs",
".",
"i",
",",
"j",
":",
"vs",
".",
"i",
"+",
"len",
",",
"}",
"\n",
"}",
"\n\n",
"// grow the capacity",
"newCap",
":=",
"vs",
".",
"Cap",
"(",
")",
"\n",
"if",
"newCap",
"<",
"1024",
"{",
"newCap",
"+=",
"newCap",
"\n",
"}",
"else",
"{",
"newCap",
"+=",
"newCap",
"/",
"4",
"\n",
"}",
"\n",
"if",
"newCap",
"<",
"len",
"{",
"newCap",
"=",
"len",
"\n",
"}",
"\n",
"newVs",
":=",
"VertexSlice",
"{",
"va",
":",
"newVertexArray",
"(",
"vs",
".",
"va",
".",
"shader",
",",
"newCap",
")",
",",
"i",
":",
"0",
",",
"j",
":",
"len",
",",
"}",
"\n",
"// preserve the original content",
"newVs",
".",
"Begin",
"(",
")",
"\n",
"newVs",
".",
"Slice",
"(",
"0",
",",
"vs",
".",
"Len",
"(",
")",
")",
".",
"SetVertexData",
"(",
"vs",
".",
"VertexData",
"(",
")",
")",
"\n",
"newVs",
".",
"End",
"(",
")",
"\n",
"return",
"newVs",
"\n",
"}"
] | // grow returns supplied vs with length changed to len. Allocates new underlying vertex array if
// necessary. The original content is preserved. | [
"grow",
"returns",
"supplied",
"vs",
"with",
"length",
"changed",
"to",
"len",
".",
"Allocates",
"new",
"underlying",
"vertex",
"array",
"if",
"necessary",
".",
"The",
"original",
"content",
"is",
"preserved",
"."
] | 82a6317ac380cdc61567d729fe48833d75b8108e | https://github.com/faiface/glhf/blob/82a6317ac380cdc61567d729fe48833d75b8108e/vertex.go#L72-L102 |
1,066 | faiface/glhf | vertex.go | SetVertexData | func (vs *VertexSlice) SetVertexData(data []float32) {
if len(data)/vs.Stride() != vs.Len() {
fmt.Println(len(data)/vs.Stride(), vs.Len())
panic("set vertex data: wrong length of vertices")
}
vs.va.setVertexData(vs.i, vs.j, data)
} | go | func (vs *VertexSlice) SetVertexData(data []float32) {
if len(data)/vs.Stride() != vs.Len() {
fmt.Println(len(data)/vs.Stride(), vs.Len())
panic("set vertex data: wrong length of vertices")
}
vs.va.setVertexData(vs.i, vs.j, data)
} | [
"func",
"(",
"vs",
"*",
"VertexSlice",
")",
"SetVertexData",
"(",
"data",
"[",
"]",
"float32",
")",
"{",
"if",
"len",
"(",
"data",
")",
"/",
"vs",
".",
"Stride",
"(",
")",
"!=",
"vs",
".",
"Len",
"(",
")",
"{",
"fmt",
".",
"Println",
"(",
"len",
"(",
"data",
")",
"/",
"vs",
".",
"Stride",
"(",
")",
",",
"vs",
".",
"Len",
"(",
")",
")",
"\n",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"vs",
".",
"va",
".",
"setVertexData",
"(",
"vs",
".",
"i",
",",
"vs",
".",
"j",
",",
"data",
")",
"\n",
"}"
] | // SetVertexData sets the contents of the VertexSlice.
//
// The data is a slice of float32's, where each vertex attribute occupies a certain number of
// elements. Namely, Float occupies 1, Vec2 occupies 2, Vec3 occupies 3 and Vec4 occupies 4. The
// attribues in the data slice must be in the same order as in the vertex format of this Vertex
// Slice.
//
// If the length of vertices does not match the length of the VertexSlice, this methdo panics. | [
"SetVertexData",
"sets",
"the",
"contents",
"of",
"the",
"VertexSlice",
".",
"The",
"data",
"is",
"a",
"slice",
"of",
"float32",
"s",
"where",
"each",
"vertex",
"attribute",
"occupies",
"a",
"certain",
"number",
"of",
"elements",
".",
"Namely",
"Float",
"occupies",
"1",
"Vec2",
"occupies",
"2",
"Vec3",
"occupies",
"3",
"and",
"Vec4",
"occupies",
"4",
".",
"The",
"attribues",
"in",
"the",
"data",
"slice",
"must",
"be",
"in",
"the",
"same",
"order",
"as",
"in",
"the",
"vertex",
"format",
"of",
"this",
"Vertex",
"Slice",
".",
"If",
"the",
"length",
"of",
"vertices",
"does",
"not",
"match",
"the",
"length",
"of",
"the",
"VertexSlice",
"this",
"methdo",
"panics",
"."
] | 82a6317ac380cdc61567d729fe48833d75b8108e | https://github.com/faiface/glhf/blob/82a6317ac380cdc61567d729fe48833d75b8108e/vertex.go#L128-L134 |
1,067 | faiface/glhf | vertex.go | VertexData | func (vs *VertexSlice) VertexData() []float32 {
return vs.va.vertexData(vs.i, vs.j)
} | go | func (vs *VertexSlice) VertexData() []float32 {
return vs.va.vertexData(vs.i, vs.j)
} | [
"func",
"(",
"vs",
"*",
"VertexSlice",
")",
"VertexData",
"(",
")",
"[",
"]",
"float32",
"{",
"return",
"vs",
".",
"va",
".",
"vertexData",
"(",
"vs",
".",
"i",
",",
"vs",
".",
"j",
")",
"\n",
"}"
] | // VertexData returns the contents of the VertexSlice.
//
// The data is in the same format as with SetVertexData. | [
"VertexData",
"returns",
"the",
"contents",
"of",
"the",
"VertexSlice",
".",
"The",
"data",
"is",
"in",
"the",
"same",
"format",
"as",
"with",
"SetVertexData",
"."
] | 82a6317ac380cdc61567d729fe48833d75b8108e | https://github.com/faiface/glhf/blob/82a6317ac380cdc61567d729fe48833d75b8108e/vertex.go#L139-L141 |
1,068 | faiface/glhf | vertex.go | Draw | func (vs *VertexSlice) Draw() {
vs.va.draw(vs.i, vs.j)
} | go | func (vs *VertexSlice) Draw() {
vs.va.draw(vs.i, vs.j)
} | [
"func",
"(",
"vs",
"*",
"VertexSlice",
")",
"Draw",
"(",
")",
"{",
"vs",
".",
"va",
".",
"draw",
"(",
"vs",
".",
"i",
",",
"vs",
".",
"j",
")",
"\n",
"}"
] | // Draw draws the content of the VertexSlice. | [
"Draw",
"draws",
"the",
"content",
"of",
"the",
"VertexSlice",
"."
] | 82a6317ac380cdc61567d729fe48833d75b8108e | https://github.com/faiface/glhf/blob/82a6317ac380cdc61567d729fe48833d75b8108e/vertex.go#L144-L146 |
1,069 | bluele/factory-go | factory/factory.go | Parent | func (args *argsStruct) Parent() Args {
if args.pl == nil {
return nil
}
return args.pl.parent
} | go | func (args *argsStruct) Parent() Args {
if args.pl == nil {
return nil
}
return args.pl.parent
} | [
"func",
"(",
"args",
"*",
"argsStruct",
")",
"Parent",
"(",
")",
"Args",
"{",
"if",
"args",
".",
"pl",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"args",
".",
"pl",
".",
"parent",
"\n",
"}"
] | // Parent returns a parent argument if current factory is a subfactory of parent | [
"Parent",
"returns",
"a",
"parent",
"argument",
"if",
"current",
"factory",
"is",
"a",
"subfactory",
"of",
"parent"
] | e6e8633dd3fee91852bffdbe7eccb07f3d2a2f8f | https://github.com/bluele/factory-go/blob/e6e8633dd3fee91852bffdbe7eccb07f3d2a2f8f/factory/factory.go#L46-L51 |
1,070 | bluele/factory-go | factory/factory.go | Set | func (st *Stacks) Set(idx, val int) {
var ini int64 = 0
(*st)[idx] = &ini
atomic.StoreInt64((*st)[idx], int64(val))
} | go | func (st *Stacks) Set(idx, val int) {
var ini int64 = 0
(*st)[idx] = &ini
atomic.StoreInt64((*st)[idx], int64(val))
} | [
"func",
"(",
"st",
"*",
"Stacks",
")",
"Set",
"(",
"idx",
",",
"val",
"int",
")",
"{",
"var",
"ini",
"int64",
"=",
"0",
"\n",
"(",
"*",
"st",
")",
"[",
"idx",
"]",
"=",
"&",
"ini",
"\n",
"atomic",
".",
"StoreInt64",
"(",
"(",
"*",
"st",
")",
"[",
"idx",
"]",
",",
"int64",
"(",
"val",
")",
")",
"\n",
"}"
] | // Set method is not goroutine safe. | [
"Set",
"method",
"is",
"not",
"goroutine",
"safe",
"."
] | e6e8633dd3fee91852bffdbe7eccb07f3d2a2f8f | https://github.com/bluele/factory-go/blob/e6e8633dd3fee91852bffdbe7eccb07f3d2a2f8f/factory/factory.go#L75-L79 |
1,071 | bluele/factory-go | factory/factory.go | NewFactory | func NewFactory(model interface{}) *Factory {
fa := &Factory{}
fa.model = model
fa.nameIndexMap = make(map[string]int)
fa.init()
return fa
} | go | func NewFactory(model interface{}) *Factory {
fa := &Factory{}
fa.model = model
fa.nameIndexMap = make(map[string]int)
fa.init()
return fa
} | [
"func",
"NewFactory",
"(",
"model",
"interface",
"{",
"}",
")",
"*",
"Factory",
"{",
"fa",
":=",
"&",
"Factory",
"{",
"}",
"\n",
"fa",
".",
"model",
"=",
"model",
"\n",
"fa",
".",
"nameIndexMap",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"int",
")",
"\n\n",
"fa",
".",
"init",
"(",
")",
"\n",
"return",
"fa",
"\n",
"}"
] | // NewFactory returns a new factory for specified model class
// Each generator is applied in the order in which they are declared | [
"NewFactory",
"returns",
"a",
"new",
"factory",
"for",
"specified",
"model",
"class",
"Each",
"generator",
"is",
"applied",
"in",
"the",
"order",
"in",
"which",
"they",
"are",
"declared"
] | e6e8633dd3fee91852bffdbe7eccb07f3d2a2f8f | https://github.com/bluele/factory-go/blob/e6e8633dd3fee91852bffdbe7eccb07f3d2a2f8f/factory/factory.go#L122-L129 |
1,072 | bluele/factory-go | factory/factory.go | OnCreate | func (fa *Factory) OnCreate(cb func(Args) error) *Factory {
fa.onCreate = cb
return fa
} | go | func (fa *Factory) OnCreate(cb func(Args) error) *Factory {
fa.onCreate = cb
return fa
} | [
"func",
"(",
"fa",
"*",
"Factory",
")",
"OnCreate",
"(",
"cb",
"func",
"(",
"Args",
")",
"error",
")",
"*",
"Factory",
"{",
"fa",
".",
"onCreate",
"=",
"cb",
"\n",
"return",
"fa",
"\n",
"}"
] | // OnCreate registers a callback on object creation.
// If callback function returns error, object creation is failed. | [
"OnCreate",
"registers",
"a",
"callback",
"on",
"object",
"creation",
".",
"If",
"callback",
"function",
"returns",
"error",
"object",
"creation",
"is",
"failed",
"."
] | e6e8633dd3fee91852bffdbe7eccb07f3d2a2f8f | https://github.com/bluele/factory-go/blob/e6e8633dd3fee91852bffdbe7eccb07f3d2a2f8f/factory/factory.go#L280-L283 |
1,073 | sbstjn/hanu | command.go | NewCommand | func NewCommand(text string, description string, handler Handler) Command {
cmd := Command{}
cmd.Set(allot.New(text))
cmd.SetDescription(description)
cmd.SetHandler(handler)
return cmd
} | go | func NewCommand(text string, description string, handler Handler) Command {
cmd := Command{}
cmd.Set(allot.New(text))
cmd.SetDescription(description)
cmd.SetHandler(handler)
return cmd
} | [
"func",
"NewCommand",
"(",
"text",
"string",
",",
"description",
"string",
",",
"handler",
"Handler",
")",
"Command",
"{",
"cmd",
":=",
"Command",
"{",
"}",
"\n",
"cmd",
".",
"Set",
"(",
"allot",
".",
"New",
"(",
"text",
")",
")",
"\n",
"cmd",
".",
"SetDescription",
"(",
"description",
")",
"\n",
"cmd",
".",
"SetHandler",
"(",
"handler",
")",
"\n\n",
"return",
"cmd",
"\n",
"}"
] | // NewCommand creates a new command | [
"NewCommand",
"creates",
"a",
"new",
"command"
] | 0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c | https://github.com/sbstjn/hanu/blob/0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c/command.go#L55-L62 |
1,074 | sbstjn/hanu | message.go | StripMention | func (m *Message) StripMention(user string) {
prefix := "<@" + user + "> "
text := m.Text()
if strings.HasPrefix(text, prefix) {
m.SetText(text[len(prefix):len(text)])
}
} | go | func (m *Message) StripMention(user string) {
prefix := "<@" + user + "> "
text := m.Text()
if strings.HasPrefix(text, prefix) {
m.SetText(text[len(prefix):len(text)])
}
} | [
"func",
"(",
"m",
"*",
"Message",
")",
"StripMention",
"(",
"user",
"string",
")",
"{",
"prefix",
":=",
"\"",
"\"",
"+",
"user",
"+",
"\"",
"\"",
"\n",
"text",
":=",
"m",
".",
"Text",
"(",
")",
"\n\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"text",
",",
"prefix",
")",
"{",
"m",
".",
"SetText",
"(",
"text",
"[",
"len",
"(",
"prefix",
")",
":",
"len",
"(",
"text",
")",
"]",
")",
"\n",
"}",
"\n",
"}"
] | // StripMention removes the mention from the message beginning | [
"StripMention",
"removes",
"the",
"mention",
"from",
"the",
"message",
"beginning"
] | 0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c | https://github.com/sbstjn/hanu/blob/0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c/message.go#L56-L63 |
1,075 | sbstjn/hanu | message.go | IsHelpRequest | func (m Message) IsHelpRequest() bool {
return strings.HasSuffix(m.Message, "help") || strings.HasPrefix(m.Message, "help")
} | go | func (m Message) IsHelpRequest() bool {
return strings.HasSuffix(m.Message, "help") || strings.HasPrefix(m.Message, "help")
} | [
"func",
"(",
"m",
"Message",
")",
"IsHelpRequest",
"(",
")",
"bool",
"{",
"return",
"strings",
".",
"HasSuffix",
"(",
"m",
".",
"Message",
",",
"\"",
"\"",
")",
"||",
"strings",
".",
"HasPrefix",
"(",
"m",
".",
"Message",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // IsHelpRequest checks if the user requests the help command | [
"IsHelpRequest",
"checks",
"if",
"the",
"user",
"requests",
"the",
"help",
"command"
] | 0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c | https://github.com/sbstjn/hanu/blob/0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c/message.go#L94-L96 |
1,076 | sbstjn/hanu | message.go | IsMentionFor | func (m Message) IsMentionFor(user string) bool {
return strings.HasPrefix(m.Message, "<@"+user+">")
} | go | func (m Message) IsMentionFor(user string) bool {
return strings.HasPrefix(m.Message, "<@"+user+">")
} | [
"func",
"(",
"m",
"Message",
")",
"IsMentionFor",
"(",
"user",
"string",
")",
"bool",
"{",
"return",
"strings",
".",
"HasPrefix",
"(",
"m",
".",
"Message",
",",
"\"",
"\"",
"+",
"user",
"+",
"\"",
"\"",
")",
"\n",
"}"
] | // IsMentionFor checks if the given user was mentioned with the message | [
"IsMentionFor",
"checks",
"if",
"the",
"given",
"user",
"was",
"mentioned",
"with",
"the",
"message"
] | 0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c | https://github.com/sbstjn/hanu/blob/0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c/message.go#L104-L106 |
1,077 | sbstjn/hanu | message.go | IsRelevantFor | func (m Message) IsRelevantFor(user string) bool {
return m.IsMessage() && !m.IsFrom(user) && (m.IsDirectMessage() || m.IsMentionFor(user))
} | go | func (m Message) IsRelevantFor(user string) bool {
return m.IsMessage() && !m.IsFrom(user) && (m.IsDirectMessage() || m.IsMentionFor(user))
} | [
"func",
"(",
"m",
"Message",
")",
"IsRelevantFor",
"(",
"user",
"string",
")",
"bool",
"{",
"return",
"m",
".",
"IsMessage",
"(",
")",
"&&",
"!",
"m",
".",
"IsFrom",
"(",
"user",
")",
"&&",
"(",
"m",
".",
"IsDirectMessage",
"(",
")",
"||",
"m",
".",
"IsMentionFor",
"(",
"user",
")",
")",
"\n",
"}"
] | // IsRelevantFor checks if the message is relevant for a user | [
"IsRelevantFor",
"checks",
"if",
"the",
"message",
"is",
"relevant",
"for",
"a",
"user"
] | 0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c | https://github.com/sbstjn/hanu/blob/0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c/message.go#L109-L111 |
1,078 | sbstjn/hanu | main.go | New | func New(token string) (*Bot, error) {
bot := Bot{
Token: token,
}
return bot.Handshake()
} | go | func New(token string) (*Bot, error) {
bot := Bot{
Token: token,
}
return bot.Handshake()
} | [
"func",
"New",
"(",
"token",
"string",
")",
"(",
"*",
"Bot",
",",
"error",
")",
"{",
"bot",
":=",
"Bot",
"{",
"Token",
":",
"token",
",",
"}",
"\n\n",
"return",
"bot",
".",
"Handshake",
"(",
")",
"\n",
"}"
] | // New creates a new bot | [
"New",
"creates",
"a",
"new",
"bot"
] | 0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c | https://github.com/sbstjn/hanu/blob/0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c/main.go#L33-L39 |
1,079 | sbstjn/hanu | main.go | Handshake | func (b *Bot) Handshake() (*Bot, error) {
// Check for HTTP error on connection
res, err := http.Get(fmt.Sprintf("https://slack.com/api/rtm.start?token=%s", b.Token))
if err != nil {
return nil, errors.New("Failed to connect to Slack RTM API")
}
// Check for HTTP status code
if res.StatusCode != 200 {
return nil, fmt.Errorf("Failed with HTTP Code: %d", res.StatusCode)
}
// Read response body
body, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
return nil, fmt.Errorf("Failed to read body from response")
}
// Parse response
var response handshakeResponse
err = json.Unmarshal(body, &response)
if err != nil {
return nil, fmt.Errorf("Failed to unmarshal JSON: %s", body)
}
// Check for Slack error
if !response.Ok {
return nil, errors.New(response.Error)
}
// Assign Slack user ID
b.ID = response.Self.ID
// Connect to websocket
b.Socket, err = websocket.Dial(response.URL, "", "https://api.slack.com/")
if err != nil {
return nil, errors.New("Failed to connect to Websocket")
}
return b, nil
} | go | func (b *Bot) Handshake() (*Bot, error) {
// Check for HTTP error on connection
res, err := http.Get(fmt.Sprintf("https://slack.com/api/rtm.start?token=%s", b.Token))
if err != nil {
return nil, errors.New("Failed to connect to Slack RTM API")
}
// Check for HTTP status code
if res.StatusCode != 200 {
return nil, fmt.Errorf("Failed with HTTP Code: %d", res.StatusCode)
}
// Read response body
body, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
return nil, fmt.Errorf("Failed to read body from response")
}
// Parse response
var response handshakeResponse
err = json.Unmarshal(body, &response)
if err != nil {
return nil, fmt.Errorf("Failed to unmarshal JSON: %s", body)
}
// Check for Slack error
if !response.Ok {
return nil, errors.New(response.Error)
}
// Assign Slack user ID
b.ID = response.Self.ID
// Connect to websocket
b.Socket, err = websocket.Dial(response.URL, "", "https://api.slack.com/")
if err != nil {
return nil, errors.New("Failed to connect to Websocket")
}
return b, nil
} | [
"func",
"(",
"b",
"*",
"Bot",
")",
"Handshake",
"(",
")",
"(",
"*",
"Bot",
",",
"error",
")",
"{",
"// Check for HTTP error on connection",
"res",
",",
"err",
":=",
"http",
".",
"Get",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"b",
".",
"Token",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Check for HTTP status code",
"if",
"res",
".",
"StatusCode",
"!=",
"200",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"res",
".",
"StatusCode",
")",
"\n",
"}",
"\n\n",
"// Read response body",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"res",
".",
"Body",
")",
"\n",
"res",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Parse response",
"var",
"response",
"handshakeResponse",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"body",
",",
"&",
"response",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"body",
")",
"\n",
"}",
"\n\n",
"// Check for Slack error",
"if",
"!",
"response",
".",
"Ok",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"response",
".",
"Error",
")",
"\n",
"}",
"\n\n",
"// Assign Slack user ID",
"b",
".",
"ID",
"=",
"response",
".",
"Self",
".",
"ID",
"\n\n",
"// Connect to websocket",
"b",
".",
"Socket",
",",
"err",
"=",
"websocket",
".",
"Dial",
"(",
"response",
".",
"URL",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"b",
",",
"nil",
"\n",
"}"
] | // Handshake connects to the Slack API to get a socket connection | [
"Handshake",
"connects",
"to",
"the",
"Slack",
"API",
"to",
"get",
"a",
"socket",
"connection"
] | 0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c | https://github.com/sbstjn/hanu/blob/0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c/main.go#L42-L83 |
1,080 | sbstjn/hanu | main.go | process | func (b *Bot) process(message Message) {
if !message.IsRelevantFor(b.ID) {
return
}
// Strip @BotName from public message
message.StripMention(b.ID)
// Strip Slack's link markup
message.StripLinkMarkup()
// Check if the message requests the auto-generated help command list
// or if we need to search for a command matching the request
if message.IsHelpRequest() {
b.sendHelp(message)
} else {
b.searchCommand(message)
}
} | go | func (b *Bot) process(message Message) {
if !message.IsRelevantFor(b.ID) {
return
}
// Strip @BotName from public message
message.StripMention(b.ID)
// Strip Slack's link markup
message.StripLinkMarkup()
// Check if the message requests the auto-generated help command list
// or if we need to search for a command matching the request
if message.IsHelpRequest() {
b.sendHelp(message)
} else {
b.searchCommand(message)
}
} | [
"func",
"(",
"b",
"*",
"Bot",
")",
"process",
"(",
"message",
"Message",
")",
"{",
"if",
"!",
"message",
".",
"IsRelevantFor",
"(",
"b",
".",
"ID",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"// Strip @BotName from public message",
"message",
".",
"StripMention",
"(",
"b",
".",
"ID",
")",
"\n",
"// Strip Slack's link markup",
"message",
".",
"StripLinkMarkup",
"(",
")",
"\n\n",
"// Check if the message requests the auto-generated help command list",
"// or if we need to search for a command matching the request",
"if",
"message",
".",
"IsHelpRequest",
"(",
")",
"{",
"b",
".",
"sendHelp",
"(",
"message",
")",
"\n",
"}",
"else",
"{",
"b",
".",
"searchCommand",
"(",
"message",
")",
"\n",
"}",
"\n",
"}"
] | // Process incoming message | [
"Process",
"incoming",
"message"
] | 0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c | https://github.com/sbstjn/hanu/blob/0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c/main.go#L86-L103 |
1,081 | sbstjn/hanu | main.go | searchCommand | func (b *Bot) searchCommand(msg Message) {
var cmd CommandInterface
for i := 0; i < len(b.Commands); i++ {
cmd = b.Commands[i]
match, err := cmd.Get().Match(msg.Text())
if err == nil {
cmd.Handle(NewConversation(match, msg, b.Socket))
}
}
} | go | func (b *Bot) searchCommand(msg Message) {
var cmd CommandInterface
for i := 0; i < len(b.Commands); i++ {
cmd = b.Commands[i]
match, err := cmd.Get().Match(msg.Text())
if err == nil {
cmd.Handle(NewConversation(match, msg, b.Socket))
}
}
} | [
"func",
"(",
"b",
"*",
"Bot",
")",
"searchCommand",
"(",
"msg",
"Message",
")",
"{",
"var",
"cmd",
"CommandInterface",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"b",
".",
"Commands",
")",
";",
"i",
"++",
"{",
"cmd",
"=",
"b",
".",
"Commands",
"[",
"i",
"]",
"\n\n",
"match",
",",
"err",
":=",
"cmd",
".",
"Get",
"(",
")",
".",
"Match",
"(",
"msg",
".",
"Text",
"(",
")",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"cmd",
".",
"Handle",
"(",
"NewConversation",
"(",
"match",
",",
"msg",
",",
"b",
".",
"Socket",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Search for a command matching the message | [
"Search",
"for",
"a",
"command",
"matching",
"the",
"message"
] | 0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c | https://github.com/sbstjn/hanu/blob/0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c/main.go#L106-L117 |
1,082 | sbstjn/hanu | main.go | sendHelp | func (b *Bot) sendHelp(msg Message) {
var cmd CommandInterface
help := "Thanks for asking! I can support you with those features:\n\n"
for i := 0; i < len(b.Commands); i++ {
cmd = b.Commands[i]
help = help + "`" + cmd.Get().Text() + "`"
if cmd.Description() != "" {
help = help + " *–* " + cmd.Description()
}
help = help + "\n"
}
if !msg.IsDirectMessage() {
help = "<@" + msg.User() + ">: " + help
}
msg.SetText(help)
websocket.JSON.Send(b.Socket, msg)
} | go | func (b *Bot) sendHelp(msg Message) {
var cmd CommandInterface
help := "Thanks for asking! I can support you with those features:\n\n"
for i := 0; i < len(b.Commands); i++ {
cmd = b.Commands[i]
help = help + "`" + cmd.Get().Text() + "`"
if cmd.Description() != "" {
help = help + " *–* " + cmd.Description()
}
help = help + "\n"
}
if !msg.IsDirectMessage() {
help = "<@" + msg.User() + ">: " + help
}
msg.SetText(help)
websocket.JSON.Send(b.Socket, msg)
} | [
"func",
"(",
"b",
"*",
"Bot",
")",
"sendHelp",
"(",
"msg",
"Message",
")",
"{",
"var",
"cmd",
"CommandInterface",
"\n",
"help",
":=",
"\"",
"\\n",
"\\n",
"\"",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"b",
".",
"Commands",
")",
";",
"i",
"++",
"{",
"cmd",
"=",
"b",
".",
"Commands",
"[",
"i",
"]",
"\n\n",
"help",
"=",
"help",
"+",
"\"",
"\"",
"+",
"cmd",
".",
"Get",
"(",
")",
".",
"Text",
"(",
")",
"+",
"\"",
"\"",
"\n",
"if",
"cmd",
".",
"Description",
"(",
")",
"!=",
"\"",
"\"",
"{",
"help",
"=",
"help",
"+",
"\"",
"+",
"c",
"d.D",
"e",
"scription()",
"",
"",
"\n",
"}",
"\n\n",
"help",
"=",
"help",
"+",
"\"",
"\\n",
"\"",
"\n",
"}",
"\n\n",
"if",
"!",
"msg",
".",
"IsDirectMessage",
"(",
")",
"{",
"help",
"=",
"\"",
"\"",
"+",
"msg",
".",
"User",
"(",
")",
"+",
"\"",
"\"",
"+",
"help",
"\n",
"}",
"\n\n",
"msg",
".",
"SetText",
"(",
"help",
")",
"\n",
"websocket",
".",
"JSON",
".",
"Send",
"(",
"b",
".",
"Socket",
",",
"msg",
")",
"\n",
"}"
] | // Send the response for a help request | [
"Send",
"the",
"response",
"for",
"a",
"help",
"request"
] | 0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c | https://github.com/sbstjn/hanu/blob/0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c/main.go#L120-L141 |
1,083 | sbstjn/hanu | main.go | Listen | func (b *Bot) Listen() {
var msg Message
for {
if websocket.JSON.Receive(b.Socket, &msg) == nil {
go b.process(msg)
// Clean up message after processign it
msg = Message{}
}
}
} | go | func (b *Bot) Listen() {
var msg Message
for {
if websocket.JSON.Receive(b.Socket, &msg) == nil {
go b.process(msg)
// Clean up message after processign it
msg = Message{}
}
}
} | [
"func",
"(",
"b",
"*",
"Bot",
")",
"Listen",
"(",
")",
"{",
"var",
"msg",
"Message",
"\n\n",
"for",
"{",
"if",
"websocket",
".",
"JSON",
".",
"Receive",
"(",
"b",
".",
"Socket",
",",
"&",
"msg",
")",
"==",
"nil",
"{",
"go",
"b",
".",
"process",
"(",
"msg",
")",
"\n\n",
"// Clean up message after processign it",
"msg",
"=",
"Message",
"{",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Listen for message on socket | [
"Listen",
"for",
"message",
"on",
"socket"
] | 0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c | https://github.com/sbstjn/hanu/blob/0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c/main.go#L144-L155 |
1,084 | sbstjn/hanu | main.go | Command | func (b *Bot) Command(cmd string, handler Handler) {
b.Commands = append(b.Commands, NewCommand(cmd, "", handler))
} | go | func (b *Bot) Command(cmd string, handler Handler) {
b.Commands = append(b.Commands, NewCommand(cmd, "", handler))
} | [
"func",
"(",
"b",
"*",
"Bot",
")",
"Command",
"(",
"cmd",
"string",
",",
"handler",
"Handler",
")",
"{",
"b",
".",
"Commands",
"=",
"append",
"(",
"b",
".",
"Commands",
",",
"NewCommand",
"(",
"cmd",
",",
"\"",
"\"",
",",
"handler",
")",
")",
"\n",
"}"
] | // Command adds a new command with custom handler | [
"Command",
"adds",
"a",
"new",
"command",
"with",
"custom",
"handler"
] | 0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c | https://github.com/sbstjn/hanu/blob/0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c/main.go#L158-L160 |
1,085 | sbstjn/hanu | main.go | Register | func (b *Bot) Register(cmd CommandInterface) {
b.Commands = append(b.Commands, cmd)
} | go | func (b *Bot) Register(cmd CommandInterface) {
b.Commands = append(b.Commands, cmd)
} | [
"func",
"(",
"b",
"*",
"Bot",
")",
"Register",
"(",
"cmd",
"CommandInterface",
")",
"{",
"b",
".",
"Commands",
"=",
"append",
"(",
"b",
".",
"Commands",
",",
"cmd",
")",
"\n",
"}"
] | // Register registers a Command | [
"Register",
"registers",
"a",
"Command"
] | 0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c | https://github.com/sbstjn/hanu/blob/0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c/main.go#L163-L165 |
1,086 | sbstjn/hanu | conversation.go | Reply | func (c *Conversation) Reply(text string, a ...interface{}) {
prefix := ""
if !c.message.IsDirectMessage() {
prefix = "<@" + c.message.User() + ">: "
}
msg := c.message
msg.SetText(prefix + fmt.Sprintf(text, a...))
c.send(msg)
} | go | func (c *Conversation) Reply(text string, a ...interface{}) {
prefix := ""
if !c.message.IsDirectMessage() {
prefix = "<@" + c.message.User() + ">: "
}
msg := c.message
msg.SetText(prefix + fmt.Sprintf(text, a...))
c.send(msg)
} | [
"func",
"(",
"c",
"*",
"Conversation",
")",
"Reply",
"(",
"text",
"string",
",",
"a",
"...",
"interface",
"{",
"}",
")",
"{",
"prefix",
":=",
"\"",
"\"",
"\n\n",
"if",
"!",
"c",
".",
"message",
".",
"IsDirectMessage",
"(",
")",
"{",
"prefix",
"=",
"\"",
"\"",
"+",
"c",
".",
"message",
".",
"User",
"(",
")",
"+",
"\"",
"\"",
"\n",
"}",
"\n\n",
"msg",
":=",
"c",
".",
"message",
"\n",
"msg",
".",
"SetText",
"(",
"prefix",
"+",
"fmt",
".",
"Sprintf",
"(",
"text",
",",
"a",
"...",
")",
")",
"\n\n",
"c",
".",
"send",
"(",
"msg",
")",
"\n",
"}"
] | // Reply sends message using the socket to Slack | [
"Reply",
"sends",
"message",
"using",
"the",
"socket",
"to",
"Slack"
] | 0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c | https://github.com/sbstjn/hanu/blob/0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c/conversation.go#L55-L66 |
1,087 | sbstjn/hanu | conversation.go | String | func (c Conversation) String(name string) (string, error) {
return c.match.String(name)
} | go | func (c Conversation) String(name string) (string, error) {
return c.match.String(name)
} | [
"func",
"(",
"c",
"Conversation",
")",
"String",
"(",
"name",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"c",
".",
"match",
".",
"String",
"(",
"name",
")",
"\n",
"}"
] | // String return string paramter | [
"String",
"return",
"string",
"paramter"
] | 0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c | https://github.com/sbstjn/hanu/blob/0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c/conversation.go#L69-L71 |
1,088 | sbstjn/hanu | conversation.go | Integer | func (c Conversation) Integer(name string) (int, error) {
return c.match.Integer(name)
} | go | func (c Conversation) Integer(name string) (int, error) {
return c.match.Integer(name)
} | [
"func",
"(",
"c",
"Conversation",
")",
"Integer",
"(",
"name",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"return",
"c",
".",
"match",
".",
"Integer",
"(",
"name",
")",
"\n",
"}"
] | // Integer returns integer parameter | [
"Integer",
"returns",
"integer",
"parameter"
] | 0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c | https://github.com/sbstjn/hanu/blob/0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c/conversation.go#L74-L76 |
1,089 | sbstjn/hanu | conversation.go | Match | func (c Conversation) Match(position int) (string, error) {
return c.match.Match(position)
} | go | func (c Conversation) Match(position int) (string, error) {
return c.match.Match(position)
} | [
"func",
"(",
"c",
"Conversation",
")",
"Match",
"(",
"position",
"int",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"c",
".",
"match",
".",
"Match",
"(",
"position",
")",
"\n",
"}"
] | // Match returns the parameter at the position | [
"Match",
"returns",
"the",
"parameter",
"at",
"the",
"position"
] | 0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c | https://github.com/sbstjn/hanu/blob/0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c/conversation.go#L79-L81 |
1,090 | sbstjn/hanu | conversation.go | NewConversation | func NewConversation(match allot.MatchInterface, msg Message, socket *websocket.Conn) ConversationInterface {
conv := &Conversation{
message: msg,
match: match,
socket: socket,
}
conv.SetConnection(websocket.JSON)
return conv
} | go | func NewConversation(match allot.MatchInterface, msg Message, socket *websocket.Conn) ConversationInterface {
conv := &Conversation{
message: msg,
match: match,
socket: socket,
}
conv.SetConnection(websocket.JSON)
return conv
} | [
"func",
"NewConversation",
"(",
"match",
"allot",
".",
"MatchInterface",
",",
"msg",
"Message",
",",
"socket",
"*",
"websocket",
".",
"Conn",
")",
"ConversationInterface",
"{",
"conv",
":=",
"&",
"Conversation",
"{",
"message",
":",
"msg",
",",
"match",
":",
"match",
",",
"socket",
":",
"socket",
",",
"}",
"\n\n",
"conv",
".",
"SetConnection",
"(",
"websocket",
".",
"JSON",
")",
"\n\n",
"return",
"conv",
"\n",
"}"
] | // NewConversation returns a Conversation struct | [
"NewConversation",
"returns",
"a",
"Conversation",
"struct"
] | 0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c | https://github.com/sbstjn/hanu/blob/0ed9132ce4437563a9eb3ea0454ae94a7a5ac39c/conversation.go#L84-L94 |
1,091 | dgryski/go-jump | jump.go | Hash | func Hash(key uint64, numBuckets int) int32 {
var b int64 = -1
var j int64
for j < int64(numBuckets) {
b = j
key = key*2862933555777941757 + 1
j = int64(float64(b+1) * (float64(int64(1)<<31) / float64((key>>33)+1)))
}
return int32(b)
} | go | func Hash(key uint64, numBuckets int) int32 {
var b int64 = -1
var j int64
for j < int64(numBuckets) {
b = j
key = key*2862933555777941757 + 1
j = int64(float64(b+1) * (float64(int64(1)<<31) / float64((key>>33)+1)))
}
return int32(b)
} | [
"func",
"Hash",
"(",
"key",
"uint64",
",",
"numBuckets",
"int",
")",
"int32",
"{",
"var",
"b",
"int64",
"=",
"-",
"1",
"\n",
"var",
"j",
"int64",
"\n\n",
"for",
"j",
"<",
"int64",
"(",
"numBuckets",
")",
"{",
"b",
"=",
"j",
"\n",
"key",
"=",
"key",
"*",
"2862933555777941757",
"+",
"1",
"\n",
"j",
"=",
"int64",
"(",
"float64",
"(",
"b",
"+",
"1",
")",
"*",
"(",
"float64",
"(",
"int64",
"(",
"1",
")",
"<<",
"31",
")",
"/",
"float64",
"(",
"(",
"key",
">>",
"33",
")",
"+",
"1",
")",
")",
")",
"\n",
"}",
"\n\n",
"return",
"int32",
"(",
"b",
")",
"\n",
"}"
] | // Hash consistently chooses a hash bucket number in the range [0, numBuckets) for the given key. numBuckets must be >= 1. | [
"Hash",
"consistently",
"chooses",
"a",
"hash",
"bucket",
"number",
"in",
"the",
"range",
"[",
"0",
"numBuckets",
")",
"for",
"the",
"given",
"key",
".",
"numBuckets",
"must",
"be",
">",
"=",
"1",
"."
] | e1f439676b570800a863c37b78d1f868f51a85fc | https://github.com/dgryski/go-jump/blob/e1f439676b570800a863c37b78d1f868f51a85fc/jump.go#L11-L23 |
1,092 | gorilla/securecookie | securecookie.go | MaxLength | func (s *SecureCookie) MaxLength(value int) *SecureCookie {
s.maxLength = value
return s
} | go | func (s *SecureCookie) MaxLength(value int) *SecureCookie {
s.maxLength = value
return s
} | [
"func",
"(",
"s",
"*",
"SecureCookie",
")",
"MaxLength",
"(",
"value",
"int",
")",
"*",
"SecureCookie",
"{",
"s",
".",
"maxLength",
"=",
"value",
"\n",
"return",
"s",
"\n",
"}"
] | // MaxLength restricts the maximum length, in bytes, for the cookie value.
//
// Default is 4096, which is the maximum value accepted by Internet Explorer. | [
"MaxLength",
"restricts",
"the",
"maximum",
"length",
"in",
"bytes",
"for",
"the",
"cookie",
"value",
".",
"Default",
"is",
"4096",
"which",
"is",
"the",
"maximum",
"value",
"accepted",
"by",
"Internet",
"Explorer",
"."
] | e65cf8c5df817c89aeb47ecb46064e802e2de943 | https://github.com/gorilla/securecookie/blob/e65cf8c5df817c89aeb47ecb46064e802e2de943/securecookie.go#L194-L197 |
1,093 | gorilla/securecookie | securecookie.go | Decode | func (s *SecureCookie) Decode(name, value string, dst interface{}) error {
if s.err != nil {
return s.err
}
if s.hashKey == nil {
s.err = errHashKeyNotSet
return s.err
}
// 1. Check length.
if s.maxLength != 0 && len(value) > s.maxLength {
return errValueToDecodeTooLong
}
// 2. Decode from base64.
b, err := decode([]byte(value))
if err != nil {
return err
}
// 3. Verify MAC. Value is "date|value|mac".
parts := bytes.SplitN(b, []byte("|"), 3)
if len(parts) != 3 {
return ErrMacInvalid
}
h := hmac.New(s.hashFunc, s.hashKey)
b = append([]byte(name+"|"), b[:len(b)-len(parts[2])-1]...)
if err = verifyMac(h, b, parts[2]); err != nil {
return err
}
// 4. Verify date ranges.
var t1 int64
if t1, err = strconv.ParseInt(string(parts[0]), 10, 64); err != nil {
return errTimestampInvalid
}
t2 := s.timestamp()
if s.minAge != 0 && t1 > t2-s.minAge {
return errTimestampTooNew
}
if s.maxAge != 0 && t1 < t2-s.maxAge {
return errTimestampExpired
}
// 5. Decrypt (optional).
b, err = decode(parts[1])
if err != nil {
return err
}
if s.block != nil {
if b, err = decrypt(s.block, b); err != nil {
return err
}
}
// 6. Deserialize.
if err = s.sz.Deserialize(b, dst); err != nil {
return cookieError{cause: err, typ: decodeError}
}
// Done.
return nil
} | go | func (s *SecureCookie) Decode(name, value string, dst interface{}) error {
if s.err != nil {
return s.err
}
if s.hashKey == nil {
s.err = errHashKeyNotSet
return s.err
}
// 1. Check length.
if s.maxLength != 0 && len(value) > s.maxLength {
return errValueToDecodeTooLong
}
// 2. Decode from base64.
b, err := decode([]byte(value))
if err != nil {
return err
}
// 3. Verify MAC. Value is "date|value|mac".
parts := bytes.SplitN(b, []byte("|"), 3)
if len(parts) != 3 {
return ErrMacInvalid
}
h := hmac.New(s.hashFunc, s.hashKey)
b = append([]byte(name+"|"), b[:len(b)-len(parts[2])-1]...)
if err = verifyMac(h, b, parts[2]); err != nil {
return err
}
// 4. Verify date ranges.
var t1 int64
if t1, err = strconv.ParseInt(string(parts[0]), 10, 64); err != nil {
return errTimestampInvalid
}
t2 := s.timestamp()
if s.minAge != 0 && t1 > t2-s.minAge {
return errTimestampTooNew
}
if s.maxAge != 0 && t1 < t2-s.maxAge {
return errTimestampExpired
}
// 5. Decrypt (optional).
b, err = decode(parts[1])
if err != nil {
return err
}
if s.block != nil {
if b, err = decrypt(s.block, b); err != nil {
return err
}
}
// 6. Deserialize.
if err = s.sz.Deserialize(b, dst); err != nil {
return cookieError{cause: err, typ: decodeError}
}
// Done.
return nil
} | [
"func",
"(",
"s",
"*",
"SecureCookie",
")",
"Decode",
"(",
"name",
",",
"value",
"string",
",",
"dst",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"s",
".",
"err",
"!=",
"nil",
"{",
"return",
"s",
".",
"err",
"\n",
"}",
"\n",
"if",
"s",
".",
"hashKey",
"==",
"nil",
"{",
"s",
".",
"err",
"=",
"errHashKeyNotSet",
"\n",
"return",
"s",
".",
"err",
"\n",
"}",
"\n",
"// 1. Check length.",
"if",
"s",
".",
"maxLength",
"!=",
"0",
"&&",
"len",
"(",
"value",
")",
">",
"s",
".",
"maxLength",
"{",
"return",
"errValueToDecodeTooLong",
"\n",
"}",
"\n",
"// 2. Decode from base64.",
"b",
",",
"err",
":=",
"decode",
"(",
"[",
"]",
"byte",
"(",
"value",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// 3. Verify MAC. Value is \"date|value|mac\".",
"parts",
":=",
"bytes",
".",
"SplitN",
"(",
"b",
",",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
",",
"3",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"!=",
"3",
"{",
"return",
"ErrMacInvalid",
"\n",
"}",
"\n",
"h",
":=",
"hmac",
".",
"New",
"(",
"s",
".",
"hashFunc",
",",
"s",
".",
"hashKey",
")",
"\n",
"b",
"=",
"append",
"(",
"[",
"]",
"byte",
"(",
"name",
"+",
"\"",
"\"",
")",
",",
"b",
"[",
":",
"len",
"(",
"b",
")",
"-",
"len",
"(",
"parts",
"[",
"2",
"]",
")",
"-",
"1",
"]",
"...",
")",
"\n",
"if",
"err",
"=",
"verifyMac",
"(",
"h",
",",
"b",
",",
"parts",
"[",
"2",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// 4. Verify date ranges.",
"var",
"t1",
"int64",
"\n",
"if",
"t1",
",",
"err",
"=",
"strconv",
".",
"ParseInt",
"(",
"string",
"(",
"parts",
"[",
"0",
"]",
")",
",",
"10",
",",
"64",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errTimestampInvalid",
"\n",
"}",
"\n",
"t2",
":=",
"s",
".",
"timestamp",
"(",
")",
"\n",
"if",
"s",
".",
"minAge",
"!=",
"0",
"&&",
"t1",
">",
"t2",
"-",
"s",
".",
"minAge",
"{",
"return",
"errTimestampTooNew",
"\n",
"}",
"\n",
"if",
"s",
".",
"maxAge",
"!=",
"0",
"&&",
"t1",
"<",
"t2",
"-",
"s",
".",
"maxAge",
"{",
"return",
"errTimestampExpired",
"\n",
"}",
"\n",
"// 5. Decrypt (optional).",
"b",
",",
"err",
"=",
"decode",
"(",
"parts",
"[",
"1",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"s",
".",
"block",
"!=",
"nil",
"{",
"if",
"b",
",",
"err",
"=",
"decrypt",
"(",
"s",
".",
"block",
",",
"b",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"// 6. Deserialize.",
"if",
"err",
"=",
"s",
".",
"sz",
".",
"Deserialize",
"(",
"b",
",",
"dst",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"cookieError",
"{",
"cause",
":",
"err",
",",
"typ",
":",
"decodeError",
"}",
"\n",
"}",
"\n",
"// Done.",
"return",
"nil",
"\n",
"}"
] | // Decode decodes a cookie value.
//
// It decodes, verifies a message authentication code, optionally decrypts and
// finally deserializes the value.
//
// The name argument is the cookie name. It must be the same name used when
// it was stored. The value argument is the encoded cookie value. The dst
// argument is where the cookie will be decoded. It must be a pointer. | [
"Decode",
"decodes",
"a",
"cookie",
"value",
".",
"It",
"decodes",
"verifies",
"a",
"message",
"authentication",
"code",
"optionally",
"decrypts",
"and",
"finally",
"deserializes",
"the",
"value",
".",
"The",
"name",
"argument",
"is",
"the",
"cookie",
"name",
".",
"It",
"must",
"be",
"the",
"same",
"name",
"used",
"when",
"it",
"was",
"stored",
".",
"The",
"value",
"argument",
"is",
"the",
"encoded",
"cookie",
"value",
".",
"The",
"dst",
"argument",
"is",
"where",
"the",
"cookie",
"will",
"be",
"decoded",
".",
"It",
"must",
"be",
"a",
"pointer",
"."
] | e65cf8c5df817c89aeb47ecb46064e802e2de943 | https://github.com/gorilla/securecookie/blob/e65cf8c5df817c89aeb47ecb46064e802e2de943/securecookie.go#L303-L358 |
1,094 | gorilla/securecookie | securecookie.go | Deserialize | func (e GobEncoder) Deserialize(src []byte, dst interface{}) error {
dec := gob.NewDecoder(bytes.NewBuffer(src))
if err := dec.Decode(dst); err != nil {
return cookieError{cause: err, typ: decodeError}
}
return nil
} | go | func (e GobEncoder) Deserialize(src []byte, dst interface{}) error {
dec := gob.NewDecoder(bytes.NewBuffer(src))
if err := dec.Decode(dst); err != nil {
return cookieError{cause: err, typ: decodeError}
}
return nil
} | [
"func",
"(",
"e",
"GobEncoder",
")",
"Deserialize",
"(",
"src",
"[",
"]",
"byte",
",",
"dst",
"interface",
"{",
"}",
")",
"error",
"{",
"dec",
":=",
"gob",
".",
"NewDecoder",
"(",
"bytes",
".",
"NewBuffer",
"(",
"src",
")",
")",
"\n",
"if",
"err",
":=",
"dec",
".",
"Decode",
"(",
"dst",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"cookieError",
"{",
"cause",
":",
"err",
",",
"typ",
":",
"decodeError",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Deserialize decodes a value using gob. | [
"Deserialize",
"decodes",
"a",
"value",
"using",
"gob",
"."
] | e65cf8c5df817c89aeb47ecb46064e802e2de943 | https://github.com/gorilla/securecookie/blob/e65cf8c5df817c89aeb47ecb46064e802e2de943/securecookie.go#L440-L446 |
1,095 | gorilla/securecookie | securecookie.go | EncodeMulti | func EncodeMulti(name string, value interface{}, codecs ...Codec) (string, error) {
if len(codecs) == 0 {
return "", errNoCodecs
}
var errors MultiError
for _, codec := range codecs {
encoded, err := codec.Encode(name, value)
if err == nil {
return encoded, nil
}
errors = append(errors, err)
}
return "", errors
} | go | func EncodeMulti(name string, value interface{}, codecs ...Codec) (string, error) {
if len(codecs) == 0 {
return "", errNoCodecs
}
var errors MultiError
for _, codec := range codecs {
encoded, err := codec.Encode(name, value)
if err == nil {
return encoded, nil
}
errors = append(errors, err)
}
return "", errors
} | [
"func",
"EncodeMulti",
"(",
"name",
"string",
",",
"value",
"interface",
"{",
"}",
",",
"codecs",
"...",
"Codec",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"len",
"(",
"codecs",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
",",
"errNoCodecs",
"\n",
"}",
"\n\n",
"var",
"errors",
"MultiError",
"\n",
"for",
"_",
",",
"codec",
":=",
"range",
"codecs",
"{",
"encoded",
",",
"err",
":=",
"codec",
".",
"Encode",
"(",
"name",
",",
"value",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"encoded",
",",
"nil",
"\n",
"}",
"\n",
"errors",
"=",
"append",
"(",
"errors",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"errors",
"\n",
"}"
] | // EncodeMulti encodes a cookie value using a group of codecs.
//
// The codecs are tried in order. Multiple codecs are accepted to allow
// key rotation.
//
// On error, may return a MultiError. | [
"EncodeMulti",
"encodes",
"a",
"cookie",
"value",
"using",
"a",
"group",
"of",
"codecs",
".",
"The",
"codecs",
"are",
"tried",
"in",
"order",
".",
"Multiple",
"codecs",
"are",
"accepted",
"to",
"allow",
"key",
"rotation",
".",
"On",
"error",
"may",
"return",
"a",
"MultiError",
"."
] | e65cf8c5df817c89aeb47ecb46064e802e2de943 | https://github.com/gorilla/securecookie/blob/e65cf8c5df817c89aeb47ecb46064e802e2de943/securecookie.go#L566-L580 |
1,096 | gorilla/securecookie | securecookie.go | DecodeMulti | func DecodeMulti(name string, value string, dst interface{}, codecs ...Codec) error {
if len(codecs) == 0 {
return errNoCodecs
}
var errors MultiError
for _, codec := range codecs {
err := codec.Decode(name, value, dst)
if err == nil {
return nil
}
errors = append(errors, err)
}
return errors
} | go | func DecodeMulti(name string, value string, dst interface{}, codecs ...Codec) error {
if len(codecs) == 0 {
return errNoCodecs
}
var errors MultiError
for _, codec := range codecs {
err := codec.Decode(name, value, dst)
if err == nil {
return nil
}
errors = append(errors, err)
}
return errors
} | [
"func",
"DecodeMulti",
"(",
"name",
"string",
",",
"value",
"string",
",",
"dst",
"interface",
"{",
"}",
",",
"codecs",
"...",
"Codec",
")",
"error",
"{",
"if",
"len",
"(",
"codecs",
")",
"==",
"0",
"{",
"return",
"errNoCodecs",
"\n",
"}",
"\n\n",
"var",
"errors",
"MultiError",
"\n",
"for",
"_",
",",
"codec",
":=",
"range",
"codecs",
"{",
"err",
":=",
"codec",
".",
"Decode",
"(",
"name",
",",
"value",
",",
"dst",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"errors",
"=",
"append",
"(",
"errors",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"errors",
"\n",
"}"
] | // DecodeMulti decodes a cookie value using a group of codecs.
//
// The codecs are tried in order. Multiple codecs are accepted to allow
// key rotation.
//
// On error, may return a MultiError. | [
"DecodeMulti",
"decodes",
"a",
"cookie",
"value",
"using",
"a",
"group",
"of",
"codecs",
".",
"The",
"codecs",
"are",
"tried",
"in",
"order",
".",
"Multiple",
"codecs",
"are",
"accepted",
"to",
"allow",
"key",
"rotation",
".",
"On",
"error",
"may",
"return",
"a",
"MultiError",
"."
] | e65cf8c5df817c89aeb47ecb46064e802e2de943 | https://github.com/gorilla/securecookie/blob/e65cf8c5df817c89aeb47ecb46064e802e2de943/securecookie.go#L588-L602 |
1,097 | gorilla/securecookie | securecookie.go | any | func (m MultiError) any(pred func(Error) bool) bool {
for _, e := range m {
if ourErr, ok := e.(Error); ok && pred(ourErr) {
return true
}
}
return false
} | go | func (m MultiError) any(pred func(Error) bool) bool {
for _, e := range m {
if ourErr, ok := e.(Error); ok && pred(ourErr) {
return true
}
}
return false
} | [
"func",
"(",
"m",
"MultiError",
")",
"any",
"(",
"pred",
"func",
"(",
"Error",
")",
"bool",
")",
"bool",
"{",
"for",
"_",
",",
"e",
":=",
"range",
"m",
"{",
"if",
"ourErr",
",",
"ok",
":=",
"e",
".",
"(",
"Error",
")",
";",
"ok",
"&&",
"pred",
"(",
"ourErr",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // any returns true if any element of m is an Error for which pred returns true. | [
"any",
"returns",
"true",
"if",
"any",
"element",
"of",
"m",
"is",
"an",
"Error",
"for",
"which",
"pred",
"returns",
"true",
"."
] | e65cf8c5df817c89aeb47ecb46064e802e2de943 | https://github.com/gorilla/securecookie/blob/e65cf8c5df817c89aeb47ecb46064e802e2de943/securecookie.go#L643-L650 |
1,098 | pborman/uuid | uuid.go | ParseBytes | func ParseBytes(b []byte) (UUID, error) {
gu, err := guuid.ParseBytes(b)
if err == nil {
return gu[:], nil
}
return nil, err
} | go | func ParseBytes(b []byte) (UUID, error) {
gu, err := guuid.ParseBytes(b)
if err == nil {
return gu[:], nil
}
return nil, err
} | [
"func",
"ParseBytes",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"UUID",
",",
"error",
")",
"{",
"gu",
",",
"err",
":=",
"guuid",
".",
"ParseBytes",
"(",
"b",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"gu",
"[",
":",
"]",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}"
] | // ParseBytes is like Parse, except it parses a byte slice instead of a string. | [
"ParseBytes",
"is",
"like",
"Parse",
"except",
"it",
"parses",
"a",
"byte",
"slice",
"instead",
"of",
"a",
"string",
"."
] | 8b1b92947f46224e3b97bb1a3a5b0382be00d31e | https://github.com/pborman/uuid/blob/8b1b92947f46224e3b97bb1a3a5b0382be00d31e/uuid.go#L68-L74 |
1,099 | pborman/uuid | uuid.go | Array | func (uuid UUID) Array() Array {
if len(uuid) != 16 {
panic("invalid uuid")
}
var a Array
copy(a[:], uuid)
return a
} | go | func (uuid UUID) Array() Array {
if len(uuid) != 16 {
panic("invalid uuid")
}
var a Array
copy(a[:], uuid)
return a
} | [
"func",
"(",
"uuid",
"UUID",
")",
"Array",
"(",
")",
"Array",
"{",
"if",
"len",
"(",
"uuid",
")",
"!=",
"16",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"var",
"a",
"Array",
"\n",
"copy",
"(",
"a",
"[",
":",
"]",
",",
"uuid",
")",
"\n",
"return",
"a",
"\n",
"}"
] | // Array returns an array representation of uuid that can be used as a map key.
// Array panics if uuid is not valid. | [
"Array",
"returns",
"an",
"array",
"representation",
"of",
"uuid",
"that",
"can",
"be",
"used",
"as",
"a",
"map",
"key",
".",
"Array",
"panics",
"if",
"uuid",
"is",
"not",
"valid",
"."
] | 8b1b92947f46224e3b97bb1a3a5b0382be00d31e | https://github.com/pborman/uuid/blob/8b1b92947f46224e3b97bb1a3a5b0382be00d31e/uuid.go#L83-L90 |