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
sequencelengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
sequencelengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
151,200 | uber-go/fx | internal/lifecycle/lifecycle.go | Start | func (l *Lifecycle) Start(ctx context.Context) error {
for _, hook := range l.hooks {
if hook.OnStart != nil {
l.logger.Printf("START\t\t%s()", hook.caller)
if err := hook.OnStart(ctx); err != nil {
return err
}
}
l.numStarted++
}
return nil
} | go | func (l *Lifecycle) Start(ctx context.Context) error {
for _, hook := range l.hooks {
if hook.OnStart != nil {
l.logger.Printf("START\t\t%s()", hook.caller)
if err := hook.OnStart(ctx); err != nil {
return err
}
}
l.numStarted++
}
return nil
} | [
"func",
"(",
"l",
"*",
"Lifecycle",
")",
"Start",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"for",
"_",
",",
"hook",
":=",
"range",
"l",
".",
"hooks",
"{",
"if",
"hook",
".",
"OnStart",
"!=",
"nil",
"{",
"l",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\\t",
"\\t",
"\"",
",",
"hook",
".",
"caller",
")",
"\n",
"if",
"err",
":=",
"hook",
".",
"OnStart",
"(",
"ctx",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"l",
".",
"numStarted",
"++",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Start runs all OnStart hooks, returning immediately if it encounters an
// error. | [
"Start",
"runs",
"all",
"OnStart",
"hooks",
"returning",
"immediately",
"if",
"it",
"encounters",
"an",
"error",
"."
] | 544d97a6e020226621cefffcbc38a9e2d320584c | https://github.com/uber-go/fx/blob/544d97a6e020226621cefffcbc38a9e2d320584c/internal/lifecycle/lifecycle.go#L62-L73 |
151,201 | uber-go/fx | internal/lifecycle/lifecycle.go | Stop | func (l *Lifecycle) Stop(ctx context.Context) error {
var errs []error
// Run backward from last successful OnStart.
for ; l.numStarted > 0; l.numStarted-- {
hook := l.hooks[l.numStarted-1]
if hook.OnStop == nil {
continue
}
l.logger.Printf("STOP\t\t%s()", hook.caller)
if err := hook.OnStop(ctx); err != nil {
// For best-effort cleanup, keep going after errors.
errs = append(errs, err)
}
}
return multierr.Combine(errs...)
} | go | func (l *Lifecycle) Stop(ctx context.Context) error {
var errs []error
// Run backward from last successful OnStart.
for ; l.numStarted > 0; l.numStarted-- {
hook := l.hooks[l.numStarted-1]
if hook.OnStop == nil {
continue
}
l.logger.Printf("STOP\t\t%s()", hook.caller)
if err := hook.OnStop(ctx); err != nil {
// For best-effort cleanup, keep going after errors.
errs = append(errs, err)
}
}
return multierr.Combine(errs...)
} | [
"func",
"(",
"l",
"*",
"Lifecycle",
")",
"Stop",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"var",
"errs",
"[",
"]",
"error",
"\n",
"// Run backward from last successful OnStart.",
"for",
";",
"l",
".",
"numStarted",
">",
"0",
";",
"l",
".",
"numStarted",
"--",
"{",
"hook",
":=",
"l",
".",
"hooks",
"[",
"l",
".",
"numStarted",
"-",
"1",
"]",
"\n",
"if",
"hook",
".",
"OnStop",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"l",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\\t",
"\\t",
"\"",
",",
"hook",
".",
"caller",
")",
"\n",
"if",
"err",
":=",
"hook",
".",
"OnStop",
"(",
"ctx",
")",
";",
"err",
"!=",
"nil",
"{",
"// For best-effort cleanup, keep going after errors.",
"errs",
"=",
"append",
"(",
"errs",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"multierr",
".",
"Combine",
"(",
"errs",
"...",
")",
"\n",
"}"
] | // Stop runs any OnStop hooks whose OnStart counterpart succeeded. OnStop
// hooks run in reverse order. | [
"Stop",
"runs",
"any",
"OnStop",
"hooks",
"whose",
"OnStart",
"counterpart",
"succeeded",
".",
"OnStop",
"hooks",
"run",
"in",
"reverse",
"order",
"."
] | 544d97a6e020226621cefffcbc38a9e2d320584c | https://github.com/uber-go/fx/blob/544d97a6e020226621cefffcbc38a9e2d320584c/internal/lifecycle/lifecycle.go#L77-L92 |
151,202 | uber-go/fx | internal/fxlog/fxlog.go | PrintProvide | func (l *Logger) PrintProvide(t interface{}) {
for _, rtype := range fxreflect.ReturnTypes(t) {
l.Printf("PROVIDE\t%s <= %s", rtype, fxreflect.FuncName(t))
}
} | go | func (l *Logger) PrintProvide(t interface{}) {
for _, rtype := range fxreflect.ReturnTypes(t) {
l.Printf("PROVIDE\t%s <= %s", rtype, fxreflect.FuncName(t))
}
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"PrintProvide",
"(",
"t",
"interface",
"{",
"}",
")",
"{",
"for",
"_",
",",
"rtype",
":=",
"range",
"fxreflect",
".",
"ReturnTypes",
"(",
"t",
")",
"{",
"l",
".",
"Printf",
"(",
"\"",
"\\t",
"\"",
",",
"rtype",
",",
"fxreflect",
".",
"FuncName",
"(",
"t",
")",
")",
"\n",
"}",
"\n",
"}"
] | // PrintProvide logs a type provided into the dig.Container. | [
"PrintProvide",
"logs",
"a",
"type",
"provided",
"into",
"the",
"dig",
".",
"Container",
"."
] | 544d97a6e020226621cefffcbc38a9e2d320584c | https://github.com/uber-go/fx/blob/544d97a6e020226621cefffcbc38a9e2d320584c/internal/fxlog/fxlog.go#L55-L59 |
151,203 | uber-go/fx | internal/fxlog/fxlog.go | PrintSignal | func (l *Logger) PrintSignal(signal os.Signal) {
l.Printf(strings.ToUpper(signal.String()))
} | go | func (l *Logger) PrintSignal(signal os.Signal) {
l.Printf(strings.ToUpper(signal.String()))
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"PrintSignal",
"(",
"signal",
"os",
".",
"Signal",
")",
"{",
"l",
".",
"Printf",
"(",
"strings",
".",
"ToUpper",
"(",
"signal",
".",
"String",
"(",
")",
")",
")",
"\n",
"}"
] | // PrintSignal logs an os.Signal. | [
"PrintSignal",
"logs",
"an",
"os",
".",
"Signal",
"."
] | 544d97a6e020226621cefffcbc38a9e2d320584c | https://github.com/uber-go/fx/blob/544d97a6e020226621cefffcbc38a9e2d320584c/internal/fxlog/fxlog.go#L62-L64 |
151,204 | uber-go/fx | internal/fxlog/fxlog.go | Panic | func (l *Logger) Panic(err error) {
l.Printer.Printf(prepend(err.Error()))
panic(err)
} | go | func (l *Logger) Panic(err error) {
l.Printer.Printf(prepend(err.Error()))
panic(err)
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"Panic",
"(",
"err",
"error",
")",
"{",
"l",
".",
"Printer",
".",
"Printf",
"(",
"prepend",
"(",
"err",
".",
"Error",
"(",
")",
")",
")",
"\n",
"panic",
"(",
"err",
")",
"\n",
"}"
] | // Panic logs an Fx line then panics. | [
"Panic",
"logs",
"an",
"Fx",
"line",
"then",
"panics",
"."
] | 544d97a6e020226621cefffcbc38a9e2d320584c | https://github.com/uber-go/fx/blob/544d97a6e020226621cefffcbc38a9e2d320584c/internal/fxlog/fxlog.go#L67-L70 |
151,205 | uber-go/fx | internal/fxlog/fxlog.go | Fatalf | func (l *Logger) Fatalf(format string, v ...interface{}) {
l.Printer.Printf(prepend(format), v...)
_exit()
} | go | func (l *Logger) Fatalf(format string, v ...interface{}) {
l.Printer.Printf(prepend(format), v...)
_exit()
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"Fatalf",
"(",
"format",
"string",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"Printer",
".",
"Printf",
"(",
"prepend",
"(",
"format",
")",
",",
"v",
"...",
")",
"\n",
"_exit",
"(",
")",
"\n",
"}"
] | // Fatalf logs an Fx line then fatals. | [
"Fatalf",
"logs",
"an",
"Fx",
"line",
"then",
"fatals",
"."
] | 544d97a6e020226621cefffcbc38a9e2d320584c | https://github.com/uber-go/fx/blob/544d97a6e020226621cefffcbc38a9e2d320584c/internal/fxlog/fxlog.go#L73-L76 |
151,206 | uber-go/fx | internal/fxreflect/fxreflect.go | ReturnTypes | func ReturnTypes(t interface{}) []string {
if reflect.TypeOf(t).Kind() != reflect.Func {
// Invalid provide, will be logged as an error.
return []string{}
}
rtypes := []string{}
ft := reflect.ValueOf(t).Type()
for i := 0; i < ft.NumOut(); i++ {
t := ft.Out(i)
traverseOuts(key{t: t}, func(s string) {
rtypes = append(rtypes, s)
})
}
return rtypes
} | go | func ReturnTypes(t interface{}) []string {
if reflect.TypeOf(t).Kind() != reflect.Func {
// Invalid provide, will be logged as an error.
return []string{}
}
rtypes := []string{}
ft := reflect.ValueOf(t).Type()
for i := 0; i < ft.NumOut(); i++ {
t := ft.Out(i)
traverseOuts(key{t: t}, func(s string) {
rtypes = append(rtypes, s)
})
}
return rtypes
} | [
"func",
"ReturnTypes",
"(",
"t",
"interface",
"{",
"}",
")",
"[",
"]",
"string",
"{",
"if",
"reflect",
".",
"TypeOf",
"(",
"t",
")",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Func",
"{",
"// Invalid provide, will be logged as an error.",
"return",
"[",
"]",
"string",
"{",
"}",
"\n",
"}",
"\n\n",
"rtypes",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"ft",
":=",
"reflect",
".",
"ValueOf",
"(",
"t",
")",
".",
"Type",
"(",
")",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"ft",
".",
"NumOut",
"(",
")",
";",
"i",
"++",
"{",
"t",
":=",
"ft",
".",
"Out",
"(",
"i",
")",
"\n\n",
"traverseOuts",
"(",
"key",
"{",
"t",
":",
"t",
"}",
",",
"func",
"(",
"s",
"string",
")",
"{",
"rtypes",
"=",
"append",
"(",
"rtypes",
",",
"s",
")",
"\n",
"}",
")",
"\n",
"}",
"\n\n",
"return",
"rtypes",
"\n",
"}"
] | // ReturnTypes takes a func and returns a slice of string'd types. | [
"ReturnTypes",
"takes",
"a",
"func",
"and",
"returns",
"a",
"slice",
"of",
"string",
"d",
"types",
"."
] | 544d97a6e020226621cefffcbc38a9e2d320584c | https://github.com/uber-go/fx/blob/544d97a6e020226621cefffcbc38a9e2d320584c/internal/fxreflect/fxreflect.go#L38-L56 |
151,207 | uber-go/fx | internal/fxreflect/fxreflect.go | sanitize | func sanitize(function string) string {
// Use the stdlib to un-escape any package import paths which can happen
// in the case of the "dot-git" postfix. Seems like a bug in stdlib =/
if unescaped, err := url.QueryUnescape(function); err == nil {
function = unescaped
}
// strip everything prior to the vendor
return vendorRe.ReplaceAllString(function, "vendor/")
} | go | func sanitize(function string) string {
// Use the stdlib to un-escape any package import paths which can happen
// in the case of the "dot-git" postfix. Seems like a bug in stdlib =/
if unescaped, err := url.QueryUnescape(function); err == nil {
function = unescaped
}
// strip everything prior to the vendor
return vendorRe.ReplaceAllString(function, "vendor/")
} | [
"func",
"sanitize",
"(",
"function",
"string",
")",
"string",
"{",
"// Use the stdlib to un-escape any package import paths which can happen",
"// in the case of the \"dot-git\" postfix. Seems like a bug in stdlib =/",
"if",
"unescaped",
",",
"err",
":=",
"url",
".",
"QueryUnescape",
"(",
"function",
")",
";",
"err",
"==",
"nil",
"{",
"function",
"=",
"unescaped",
"\n",
"}",
"\n\n",
"// strip everything prior to the vendor",
"return",
"vendorRe",
".",
"ReplaceAllString",
"(",
"function",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // sanitize makes the function name suitable for logging display. It removes
// url-encoded elements from the `dot.git` package names and shortens the
// vendored paths. | [
"sanitize",
"makes",
"the",
"function",
"name",
"suitable",
"for",
"logging",
"display",
".",
"It",
"removes",
"url",
"-",
"encoded",
"elements",
"from",
"the",
"dot",
".",
"git",
"package",
"names",
"and",
"shortens",
"the",
"vendored",
"paths",
"."
] | 544d97a6e020226621cefffcbc38a9e2d320584c | https://github.com/uber-go/fx/blob/544d97a6e020226621cefffcbc38a9e2d320584c/internal/fxreflect/fxreflect.go#L104-L113 |
151,208 | uber-go/fx | internal/fxreflect/fxreflect.go | Caller | func Caller() string {
// Ascend at most 8 frames looking for a caller outside fx.
pcs := make([]uintptr, 8)
// Don't include this frame.
n := runtime.Callers(2, pcs)
if n == 0 {
return "n/a"
}
frames := runtime.CallersFrames(pcs)
for f, more := frames.Next(); more; f, more = frames.Next() {
if shouldIgnoreFrame(f) {
continue
}
return sanitize(f.Function)
}
return "n/a"
} | go | func Caller() string {
// Ascend at most 8 frames looking for a caller outside fx.
pcs := make([]uintptr, 8)
// Don't include this frame.
n := runtime.Callers(2, pcs)
if n == 0 {
return "n/a"
}
frames := runtime.CallersFrames(pcs)
for f, more := frames.Next(); more; f, more = frames.Next() {
if shouldIgnoreFrame(f) {
continue
}
return sanitize(f.Function)
}
return "n/a"
} | [
"func",
"Caller",
"(",
")",
"string",
"{",
"// Ascend at most 8 frames looking for a caller outside fx.",
"pcs",
":=",
"make",
"(",
"[",
"]",
"uintptr",
",",
"8",
")",
"\n\n",
"// Don't include this frame.",
"n",
":=",
"runtime",
".",
"Callers",
"(",
"2",
",",
"pcs",
")",
"\n",
"if",
"n",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"frames",
":=",
"runtime",
".",
"CallersFrames",
"(",
"pcs",
")",
"\n",
"for",
"f",
",",
"more",
":=",
"frames",
".",
"Next",
"(",
")",
";",
"more",
";",
"f",
",",
"more",
"=",
"frames",
".",
"Next",
"(",
")",
"{",
"if",
"shouldIgnoreFrame",
"(",
"f",
")",
"{",
"continue",
"\n",
"}",
"\n",
"return",
"sanitize",
"(",
"f",
".",
"Function",
")",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // Caller returns the formatted calling func name | [
"Caller",
"returns",
"the",
"formatted",
"calling",
"func",
"name"
] | 544d97a6e020226621cefffcbc38a9e2d320584c | https://github.com/uber-go/fx/blob/544d97a6e020226621cefffcbc38a9e2d320584c/internal/fxreflect/fxreflect.go#L116-L134 |
151,209 | uber-go/fx | internal/fxreflect/fxreflect.go | FuncName | func FuncName(fn interface{}) string {
fnV := reflect.ValueOf(fn)
if fnV.Kind() != reflect.Func {
return "n/a"
}
function := runtime.FuncForPC(fnV.Pointer()).Name()
return fmt.Sprintf("%s()", sanitize(function))
} | go | func FuncName(fn interface{}) string {
fnV := reflect.ValueOf(fn)
if fnV.Kind() != reflect.Func {
return "n/a"
}
function := runtime.FuncForPC(fnV.Pointer()).Name()
return fmt.Sprintf("%s()", sanitize(function))
} | [
"func",
"FuncName",
"(",
"fn",
"interface",
"{",
"}",
")",
"string",
"{",
"fnV",
":=",
"reflect",
".",
"ValueOf",
"(",
"fn",
")",
"\n",
"if",
"fnV",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Func",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"function",
":=",
"runtime",
".",
"FuncForPC",
"(",
"fnV",
".",
"Pointer",
"(",
")",
")",
".",
"Name",
"(",
")",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"sanitize",
"(",
"function",
")",
")",
"\n",
"}"
] | // FuncName returns a funcs formatted name | [
"FuncName",
"returns",
"a",
"funcs",
"formatted",
"name"
] | 544d97a6e020226621cefffcbc38a9e2d320584c | https://github.com/uber-go/fx/blob/544d97a6e020226621cefffcbc38a9e2d320584c/internal/fxreflect/fxreflect.go#L137-L145 |
151,210 | uber-go/fx | internal/fxreflect/fxreflect.go | shouldIgnoreFrame | func shouldIgnoreFrame(f runtime.Frame) bool {
if strings.Contains(f.File, "_test.go") {
return false
}
if strings.Contains(f.File, "go.uber.org/fx") {
return true
}
return false
} | go | func shouldIgnoreFrame(f runtime.Frame) bool {
if strings.Contains(f.File, "_test.go") {
return false
}
if strings.Contains(f.File, "go.uber.org/fx") {
return true
}
return false
} | [
"func",
"shouldIgnoreFrame",
"(",
"f",
"runtime",
".",
"Frame",
")",
"bool",
"{",
"if",
"strings",
".",
"Contains",
"(",
"f",
".",
"File",
",",
"\"",
"\"",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"strings",
".",
"Contains",
"(",
"f",
".",
"File",
",",
"\"",
"\"",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // Ascend the call stack until we leave the Fx production code. This allows us
// to avoid hard-coding a frame skip, which makes this code work well even
// when it's wrapped. | [
"Ascend",
"the",
"call",
"stack",
"until",
"we",
"leave",
"the",
"Fx",
"production",
"code",
".",
"This",
"allows",
"us",
"to",
"avoid",
"hard",
"-",
"coding",
"a",
"frame",
"skip",
"which",
"makes",
"this",
"code",
"work",
"well",
"even",
"when",
"it",
"s",
"wrapped",
"."
] | 544d97a6e020226621cefffcbc38a9e2d320584c | https://github.com/uber-go/fx/blob/544d97a6e020226621cefffcbc38a9e2d320584c/internal/fxreflect/fxreflect.go#L155-L163 |
151,211 | uber-go/fx | app.go | Error | func Error(errs ...error) Option {
return optionFunc(func(app *App) {
app.err = multierr.Append(app.err, multierr.Combine(errs...))
})
} | go | func Error(errs ...error) Option {
return optionFunc(func(app *App) {
app.err = multierr.Append(app.err, multierr.Combine(errs...))
})
} | [
"func",
"Error",
"(",
"errs",
"...",
"error",
")",
"Option",
"{",
"return",
"optionFunc",
"(",
"func",
"(",
"app",
"*",
"App",
")",
"{",
"app",
".",
"err",
"=",
"multierr",
".",
"Append",
"(",
"app",
".",
"err",
",",
"multierr",
".",
"Combine",
"(",
"errs",
"...",
")",
")",
"\n",
"}",
")",
"\n",
"}"
] | // Error registers any number of errors with the application to short-circuit
// startup. If more than one error is given, the errors are combined into a
// single error.
//
// Similar to invocations, errors are applied in order. All Provide and Invoke
// options registered before or after an Error option will not be applied. | [
"Error",
"registers",
"any",
"number",
"of",
"errors",
"with",
"the",
"application",
"to",
"short",
"-",
"circuit",
"startup",
".",
"If",
"more",
"than",
"one",
"error",
"is",
"given",
"the",
"errors",
"are",
"combined",
"into",
"a",
"single",
"error",
".",
"Similar",
"to",
"invocations",
"errors",
"are",
"applied",
"in",
"order",
".",
"All",
"Provide",
"and",
"Invoke",
"options",
"registered",
"before",
"or",
"after",
"an",
"Error",
"option",
"will",
"not",
"be",
"applied",
"."
] | 544d97a6e020226621cefffcbc38a9e2d320584c | https://github.com/uber-go/fx/blob/544d97a6e020226621cefffcbc38a9e2d320584c/app.go#L149-L153 |
151,212 | uber-go/fx | app.go | StartTimeout | func StartTimeout(v time.Duration) Option {
return optionFunc(func(app *App) {
app.startTimeout = v
})
} | go | func StartTimeout(v time.Duration) Option {
return optionFunc(func(app *App) {
app.startTimeout = v
})
} | [
"func",
"StartTimeout",
"(",
"v",
"time",
".",
"Duration",
")",
"Option",
"{",
"return",
"optionFunc",
"(",
"func",
"(",
"app",
"*",
"App",
")",
"{",
"app",
".",
"startTimeout",
"=",
"v",
"\n",
"}",
")",
"\n",
"}"
] | // StartTimeout changes the application's start timeout. | [
"StartTimeout",
"changes",
"the",
"application",
"s",
"start",
"timeout",
"."
] | 544d97a6e020226621cefffcbc38a9e2d320584c | https://github.com/uber-go/fx/blob/544d97a6e020226621cefffcbc38a9e2d320584c/app.go#L207-L211 |
151,213 | uber-go/fx | app.go | StopTimeout | func StopTimeout(v time.Duration) Option {
return optionFunc(func(app *App) {
app.stopTimeout = v
})
} | go | func StopTimeout(v time.Duration) Option {
return optionFunc(func(app *App) {
app.stopTimeout = v
})
} | [
"func",
"StopTimeout",
"(",
"v",
"time",
".",
"Duration",
")",
"Option",
"{",
"return",
"optionFunc",
"(",
"func",
"(",
"app",
"*",
"App",
")",
"{",
"app",
".",
"stopTimeout",
"=",
"v",
"\n",
"}",
")",
"\n",
"}"
] | // StopTimeout changes the application's stop timeout. | [
"StopTimeout",
"changes",
"the",
"application",
"s",
"stop",
"timeout",
"."
] | 544d97a6e020226621cefffcbc38a9e2d320584c | https://github.com/uber-go/fx/blob/544d97a6e020226621cefffcbc38a9e2d320584c/app.go#L214-L218 |
151,214 | uber-go/fx | app.go | Logger | func Logger(p Printer) Option {
return optionFunc(func(app *App) {
app.logger = &fxlog.Logger{Printer: p}
app.lifecycle = &lifecycleWrapper{lifecycle.New(app.logger)}
})
} | go | func Logger(p Printer) Option {
return optionFunc(func(app *App) {
app.logger = &fxlog.Logger{Printer: p}
app.lifecycle = &lifecycleWrapper{lifecycle.New(app.logger)}
})
} | [
"func",
"Logger",
"(",
"p",
"Printer",
")",
"Option",
"{",
"return",
"optionFunc",
"(",
"func",
"(",
"app",
"*",
"App",
")",
"{",
"app",
".",
"logger",
"=",
"&",
"fxlog",
".",
"Logger",
"{",
"Printer",
":",
"p",
"}",
"\n",
"app",
".",
"lifecycle",
"=",
"&",
"lifecycleWrapper",
"{",
"lifecycle",
".",
"New",
"(",
"app",
".",
"logger",
")",
"}",
"\n",
"}",
")",
"\n",
"}"
] | // Logger redirects the application's log output to the provided printer. | [
"Logger",
"redirects",
"the",
"application",
"s",
"log",
"output",
"to",
"the",
"provided",
"printer",
"."
] | 544d97a6e020226621cefffcbc38a9e2d320584c | https://github.com/uber-go/fx/blob/544d97a6e020226621cefffcbc38a9e2d320584c/app.go#L227-L232 |
151,215 | uber-go/fx | app.go | New | func New(opts ...Option) *App {
logger := fxlog.New()
lc := &lifecycleWrapper{lifecycle.New(logger)}
app := &App{
container: dig.New(dig.DeferAcyclicVerification()),
lifecycle: lc,
logger: logger,
startTimeout: DefaultTimeout,
stopTimeout: DefaultTimeout,
}
for _, opt := range opts {
opt.apply(app)
}
for _, p := range app.provides {
app.provide(p)
}
app.provide(func() Lifecycle { return app.lifecycle })
app.provide(app.shutdowner)
app.provide(app.dotGraph)
if app.err != nil {
app.logger.Printf("Error after options were applied: %v", app.err)
return app
}
if err := app.executeInvokes(); err != nil {
app.err = err
if dig.CanVisualizeError(err) {
var b bytes.Buffer
dig.Visualize(app.container, &b, dig.VisualizeError(err))
err = errorWithGraph{
graph: b.String(),
err: err,
}
}
errorHandlerList(app.errorHooks).HandleError(err)
}
return app
} | go | func New(opts ...Option) *App {
logger := fxlog.New()
lc := &lifecycleWrapper{lifecycle.New(logger)}
app := &App{
container: dig.New(dig.DeferAcyclicVerification()),
lifecycle: lc,
logger: logger,
startTimeout: DefaultTimeout,
stopTimeout: DefaultTimeout,
}
for _, opt := range opts {
opt.apply(app)
}
for _, p := range app.provides {
app.provide(p)
}
app.provide(func() Lifecycle { return app.lifecycle })
app.provide(app.shutdowner)
app.provide(app.dotGraph)
if app.err != nil {
app.logger.Printf("Error after options were applied: %v", app.err)
return app
}
if err := app.executeInvokes(); err != nil {
app.err = err
if dig.CanVisualizeError(err) {
var b bytes.Buffer
dig.Visualize(app.container, &b, dig.VisualizeError(err))
err = errorWithGraph{
graph: b.String(),
err: err,
}
}
errorHandlerList(app.errorHooks).HandleError(err)
}
return app
} | [
"func",
"New",
"(",
"opts",
"...",
"Option",
")",
"*",
"App",
"{",
"logger",
":=",
"fxlog",
".",
"New",
"(",
")",
"\n",
"lc",
":=",
"&",
"lifecycleWrapper",
"{",
"lifecycle",
".",
"New",
"(",
"logger",
")",
"}",
"\n\n",
"app",
":=",
"&",
"App",
"{",
"container",
":",
"dig",
".",
"New",
"(",
"dig",
".",
"DeferAcyclicVerification",
"(",
")",
")",
",",
"lifecycle",
":",
"lc",
",",
"logger",
":",
"logger",
",",
"startTimeout",
":",
"DefaultTimeout",
",",
"stopTimeout",
":",
"DefaultTimeout",
",",
"}",
"\n\n",
"for",
"_",
",",
"opt",
":=",
"range",
"opts",
"{",
"opt",
".",
"apply",
"(",
"app",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"p",
":=",
"range",
"app",
".",
"provides",
"{",
"app",
".",
"provide",
"(",
"p",
")",
"\n",
"}",
"\n",
"app",
".",
"provide",
"(",
"func",
"(",
")",
"Lifecycle",
"{",
"return",
"app",
".",
"lifecycle",
"}",
")",
"\n",
"app",
".",
"provide",
"(",
"app",
".",
"shutdowner",
")",
"\n",
"app",
".",
"provide",
"(",
"app",
".",
"dotGraph",
")",
"\n\n",
"if",
"app",
".",
"err",
"!=",
"nil",
"{",
"app",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"app",
".",
"err",
")",
"\n",
"return",
"app",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"app",
".",
"executeInvokes",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"app",
".",
"err",
"=",
"err",
"\n\n",
"if",
"dig",
".",
"CanVisualizeError",
"(",
"err",
")",
"{",
"var",
"b",
"bytes",
".",
"Buffer",
"\n",
"dig",
".",
"Visualize",
"(",
"app",
".",
"container",
",",
"&",
"b",
",",
"dig",
".",
"VisualizeError",
"(",
"err",
")",
")",
"\n",
"err",
"=",
"errorWithGraph",
"{",
"graph",
":",
"b",
".",
"String",
"(",
")",
",",
"err",
":",
"err",
",",
"}",
"\n",
"}",
"\n",
"errorHandlerList",
"(",
"app",
".",
"errorHooks",
")",
".",
"HandleError",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"app",
"\n",
"}"
] | // New creates and initializes an App, immediately executing any functions
// registered via Invoke options. See the documentation of the App struct for
// details on the application's initialization, startup, and shutdown logic. | [
"New",
"creates",
"and",
"initializes",
"an",
"App",
"immediately",
"executing",
"any",
"functions",
"registered",
"via",
"Invoke",
"options",
".",
"See",
"the",
"documentation",
"of",
"the",
"App",
"struct",
"for",
"details",
"on",
"the",
"application",
"s",
"initialization",
"startup",
"and",
"shutdown",
"logic",
"."
] | 544d97a6e020226621cefffcbc38a9e2d320584c | https://github.com/uber-go/fx/blob/544d97a6e020226621cefffcbc38a9e2d320584c/app.go#L322-L364 |
151,216 | uber-go/fx | app.go | VisualizeError | func VisualizeError(err error) (string, error) {
if e, ok := err.(errWithGraph); ok && e.Graph() != "" {
return string(e.Graph()), nil
}
return "", errors.New("unable to visualize error")
} | go | func VisualizeError(err error) (string, error) {
if e, ok := err.(errWithGraph); ok && e.Graph() != "" {
return string(e.Graph()), nil
}
return "", errors.New("unable to visualize error")
} | [
"func",
"VisualizeError",
"(",
"err",
"error",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"e",
",",
"ok",
":=",
"err",
".",
"(",
"errWithGraph",
")",
";",
"ok",
"&&",
"e",
".",
"Graph",
"(",
")",
"!=",
"\"",
"\"",
"{",
"return",
"string",
"(",
"e",
".",
"Graph",
"(",
")",
")",
",",
"nil",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // VisualizeError returns the visualization of the error if available. | [
"VisualizeError",
"returns",
"the",
"visualization",
"of",
"the",
"error",
"if",
"available",
"."
] | 544d97a6e020226621cefffcbc38a9e2d320584c | https://github.com/uber-go/fx/blob/544d97a6e020226621cefffcbc38a9e2d320584c/app.go#L391-L396 |
151,217 | uber-go/fx | app.go | Start | func (app *App) Start(ctx context.Context) error {
return withTimeout(ctx, app.start)
} | go | func (app *App) Start(ctx context.Context) error {
return withTimeout(ctx, app.start)
} | [
"func",
"(",
"app",
"*",
"App",
")",
"Start",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"return",
"withTimeout",
"(",
"ctx",
",",
"app",
".",
"start",
")",
"\n",
"}"
] | // Start kicks off all long-running goroutines, like network servers or
// message queue consumers. It does this by interacting with the application's
// Lifecycle.
//
// By taking a dependency on the Lifecycle type, some of the user-supplied
// functions called during initialization may have registered start and stop
// hooks. Because initialization calls constructors serially and in dependency
// order, hooks are naturally registered in dependency order too.
//
// Start executes all OnStart hooks registered with the application's
// Lifecycle, one at a time and in order. This ensures that each constructor's
// start hooks aren't executed until all its dependencies' start hooks
// complete. If any of the start hooks return an error, Start short-circuits,
// calls Stop, and returns the inciting error.
//
// Note that Start short-circuits immediately if the New constructor
// encountered any errors in application initialization. | [
"Start",
"kicks",
"off",
"all",
"long",
"-",
"running",
"goroutines",
"like",
"network",
"servers",
"or",
"message",
"queue",
"consumers",
".",
"It",
"does",
"this",
"by",
"interacting",
"with",
"the",
"application",
"s",
"Lifecycle",
".",
"By",
"taking",
"a",
"dependency",
"on",
"the",
"Lifecycle",
"type",
"some",
"of",
"the",
"user",
"-",
"supplied",
"functions",
"called",
"during",
"initialization",
"may",
"have",
"registered",
"start",
"and",
"stop",
"hooks",
".",
"Because",
"initialization",
"calls",
"constructors",
"serially",
"and",
"in",
"dependency",
"order",
"hooks",
"are",
"naturally",
"registered",
"in",
"dependency",
"order",
"too",
".",
"Start",
"executes",
"all",
"OnStart",
"hooks",
"registered",
"with",
"the",
"application",
"s",
"Lifecycle",
"one",
"at",
"a",
"time",
"and",
"in",
"order",
".",
"This",
"ensures",
"that",
"each",
"constructor",
"s",
"start",
"hooks",
"aren",
"t",
"executed",
"until",
"all",
"its",
"dependencies",
"start",
"hooks",
"complete",
".",
"If",
"any",
"of",
"the",
"start",
"hooks",
"return",
"an",
"error",
"Start",
"short",
"-",
"circuits",
"calls",
"Stop",
"and",
"returns",
"the",
"inciting",
"error",
".",
"Note",
"that",
"Start",
"short",
"-",
"circuits",
"immediately",
"if",
"the",
"New",
"constructor",
"encountered",
"any",
"errors",
"in",
"application",
"initialization",
"."
] | 544d97a6e020226621cefffcbc38a9e2d320584c | https://github.com/uber-go/fx/blob/544d97a6e020226621cefffcbc38a9e2d320584c/app.go#L439-L441 |
151,218 | uber-go/fx | app.go | Stop | func (app *App) Stop(ctx context.Context) error {
return withTimeout(ctx, app.lifecycle.Stop)
} | go | func (app *App) Stop(ctx context.Context) error {
return withTimeout(ctx, app.lifecycle.Stop)
} | [
"func",
"(",
"app",
"*",
"App",
")",
"Stop",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"return",
"withTimeout",
"(",
"ctx",
",",
"app",
".",
"lifecycle",
".",
"Stop",
")",
"\n",
"}"
] | // Stop gracefully stops the application. It executes any registered OnStop
// hooks in reverse order, so that each constructor's stop hooks are called
// before its dependencies' stop hooks.
//
// If the application didn't start cleanly, only hooks whose OnStart phase was
// called are executed. However, all those hooks are executed, even if some
// fail. | [
"Stop",
"gracefully",
"stops",
"the",
"application",
".",
"It",
"executes",
"any",
"registered",
"OnStop",
"hooks",
"in",
"reverse",
"order",
"so",
"that",
"each",
"constructor",
"s",
"stop",
"hooks",
"are",
"called",
"before",
"its",
"dependencies",
"stop",
"hooks",
".",
"If",
"the",
"application",
"didn",
"t",
"start",
"cleanly",
"only",
"hooks",
"whose",
"OnStart",
"phase",
"was",
"called",
"are",
"executed",
".",
"However",
"all",
"those",
"hooks",
"are",
"executed",
"even",
"if",
"some",
"fail",
"."
] | 544d97a6e020226621cefffcbc38a9e2d320584c | https://github.com/uber-go/fx/blob/544d97a6e020226621cefffcbc38a9e2d320584c/app.go#L450-L452 |
151,219 | uber-go/fx | app.go | executeInvokes | func (app *App) executeInvokes() error {
// TODO: consider taking a context to limit the time spent running invocations.
var err error
for _, fn := range app.invokes {
fname := fxreflect.FuncName(fn)
app.logger.Printf("INVOKE\t\t%s", fname)
if _, ok := fn.(Option); ok {
err = fmt.Errorf("fx.Option should be passed to fx.New directly, not to fx.Invoke: fx.Invoke received %v", fn)
} else {
err = app.container.Invoke(fn)
}
if err != nil {
app.logger.Printf("Error during %q invoke: %v", fname, err)
break
}
}
return err
} | go | func (app *App) executeInvokes() error {
// TODO: consider taking a context to limit the time spent running invocations.
var err error
for _, fn := range app.invokes {
fname := fxreflect.FuncName(fn)
app.logger.Printf("INVOKE\t\t%s", fname)
if _, ok := fn.(Option); ok {
err = fmt.Errorf("fx.Option should be passed to fx.New directly, not to fx.Invoke: fx.Invoke received %v", fn)
} else {
err = app.container.Invoke(fn)
}
if err != nil {
app.logger.Printf("Error during %q invoke: %v", fname, err)
break
}
}
return err
} | [
"func",
"(",
"app",
"*",
"App",
")",
"executeInvokes",
"(",
")",
"error",
"{",
"// TODO: consider taking a context to limit the time spent running invocations.",
"var",
"err",
"error",
"\n\n",
"for",
"_",
",",
"fn",
":=",
"range",
"app",
".",
"invokes",
"{",
"fname",
":=",
"fxreflect",
".",
"FuncName",
"(",
"fn",
")",
"\n",
"app",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\\t",
"\\t",
"\"",
",",
"fname",
")",
"\n\n",
"if",
"_",
",",
"ok",
":=",
"fn",
".",
"(",
"Option",
")",
";",
"ok",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"fn",
")",
"\n",
"}",
"else",
"{",
"err",
"=",
"app",
".",
"container",
".",
"Invoke",
"(",
"fn",
")",
"\n",
"}",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"app",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"fname",
",",
"err",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"err",
"\n",
"}"
] | // Execute invokes in order supplied to New, returning the first error
// encountered. | [
"Execute",
"invokes",
"in",
"order",
"supplied",
"to",
"New",
"returning",
"the",
"first",
"error",
"encountered",
"."
] | 544d97a6e020226621cefffcbc38a9e2d320584c | https://github.com/uber-go/fx/blob/544d97a6e020226621cefffcbc38a9e2d320584c/app.go#L541-L562 |
151,220 | fatih/pool | channel.go | put | func (c *channelPool) put(conn net.Conn) error {
if conn == nil {
return errors.New("connection is nil. rejecting")
}
c.mu.RLock()
defer c.mu.RUnlock()
if c.conns == nil {
// pool is closed, close passed connection
return conn.Close()
}
// put the resource back into the pool. If the pool is full, this will
// block and the default case will be executed.
select {
case c.conns <- conn:
return nil
default:
// pool is full, close passed connection
return conn.Close()
}
} | go | func (c *channelPool) put(conn net.Conn) error {
if conn == nil {
return errors.New("connection is nil. rejecting")
}
c.mu.RLock()
defer c.mu.RUnlock()
if c.conns == nil {
// pool is closed, close passed connection
return conn.Close()
}
// put the resource back into the pool. If the pool is full, this will
// block and the default case will be executed.
select {
case c.conns <- conn:
return nil
default:
// pool is full, close passed connection
return conn.Close()
}
} | [
"func",
"(",
"c",
"*",
"channelPool",
")",
"put",
"(",
"conn",
"net",
".",
"Conn",
")",
"error",
"{",
"if",
"conn",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"c",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"c",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"c",
".",
"conns",
"==",
"nil",
"{",
"// pool is closed, close passed connection",
"return",
"conn",
".",
"Close",
"(",
")",
"\n",
"}",
"\n\n",
"// put the resource back into the pool. If the pool is full, this will",
"// block and the default case will be executed.",
"select",
"{",
"case",
"c",
".",
"conns",
"<-",
"conn",
":",
"return",
"nil",
"\n",
"default",
":",
"// pool is full, close passed connection",
"return",
"conn",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // put puts the connection back to the pool. If the pool is full or closed,
// conn is simply closed. A nil conn will be rejected. | [
"put",
"puts",
"the",
"connection",
"back",
"to",
"the",
"pool",
".",
"If",
"the",
"pool",
"is",
"full",
"or",
"closed",
"conn",
"is",
"simply",
"closed",
".",
"A",
"nil",
"conn",
"will",
"be",
"rejected",
"."
] | d817ebe42acfb2147a68af2007324c3492260c4a | https://github.com/fatih/pool/blob/d817ebe42acfb2147a68af2007324c3492260c4a/channel.go#L91-L113 |
151,221 | fatih/pool | conn.go | wrapConn | func (c *channelPool) wrapConn(conn net.Conn) net.Conn {
p := &PoolConn{c: c}
p.Conn = conn
return p
} | go | func (c *channelPool) wrapConn(conn net.Conn) net.Conn {
p := &PoolConn{c: c}
p.Conn = conn
return p
} | [
"func",
"(",
"c",
"*",
"channelPool",
")",
"wrapConn",
"(",
"conn",
"net",
".",
"Conn",
")",
"net",
".",
"Conn",
"{",
"p",
":=",
"&",
"PoolConn",
"{",
"c",
":",
"c",
"}",
"\n",
"p",
".",
"Conn",
"=",
"conn",
"\n",
"return",
"p",
"\n",
"}"
] | // newConn wraps a standard net.Conn to a poolConn net.Conn. | [
"newConn",
"wraps",
"a",
"standard",
"net",
".",
"Conn",
"to",
"a",
"poolConn",
"net",
".",
"Conn",
"."
] | d817ebe42acfb2147a68af2007324c3492260c4a | https://github.com/fatih/pool/blob/d817ebe42acfb2147a68af2007324c3492260c4a/conn.go#L39-L43 |
151,222 | imroc/req | resp.go | String | func (r *Resp) String() string {
data, _ := r.ToBytes()
return string(data)
} | go | func (r *Resp) String() string {
data, _ := r.ToBytes()
return string(data)
} | [
"func",
"(",
"r",
"*",
"Resp",
")",
"String",
"(",
")",
"string",
"{",
"data",
",",
"_",
":=",
"r",
".",
"ToBytes",
"(",
")",
"\n",
"return",
"string",
"(",
"data",
")",
"\n",
"}"
] | // String returns response body as string | [
"String",
"returns",
"response",
"body",
"as",
"string"
] | b355b6f6842fbda1bee879f2846cb79424cad4de | https://github.com/imroc/req/blob/b355b6f6842fbda1bee879f2846cb79424cad4de/resp.go#L66-L69 |
151,223 | imroc/req | resp.go | ToString | func (r *Resp) ToString() (string, error) {
data, err := r.ToBytes()
return string(data), err
} | go | func (r *Resp) ToString() (string, error) {
data, err := r.ToBytes()
return string(data), err
} | [
"func",
"(",
"r",
"*",
"Resp",
")",
"ToString",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"data",
",",
"err",
":=",
"r",
".",
"ToBytes",
"(",
")",
"\n",
"return",
"string",
"(",
"data",
")",
",",
"err",
"\n",
"}"
] | // ToString returns response body as string,
// return error if error happend when reading
// the response body | [
"ToString",
"returns",
"response",
"body",
"as",
"string",
"return",
"error",
"if",
"error",
"happend",
"when",
"reading",
"the",
"response",
"body"
] | b355b6f6842fbda1bee879f2846cb79424cad4de | https://github.com/imroc/req/blob/b355b6f6842fbda1bee879f2846cb79424cad4de/resp.go#L74-L77 |
151,224 | imroc/req | resp.go | ToJSON | func (r *Resp) ToJSON(v interface{}) error {
data, err := r.ToBytes()
if err != nil {
return err
}
return json.Unmarshal(data, v)
} | go | func (r *Resp) ToJSON(v interface{}) error {
data, err := r.ToBytes()
if err != nil {
return err
}
return json.Unmarshal(data, v)
} | [
"func",
"(",
"r",
"*",
"Resp",
")",
"ToJSON",
"(",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"data",
",",
"err",
":=",
"r",
".",
"ToBytes",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"v",
")",
"\n",
"}"
] | // ToJSON convert json response body to struct or map | [
"ToJSON",
"convert",
"json",
"response",
"body",
"to",
"struct",
"or",
"map"
] | b355b6f6842fbda1bee879f2846cb79424cad4de | https://github.com/imroc/req/blob/b355b6f6842fbda1bee879f2846cb79424cad4de/resp.go#L80-L86 |
151,225 | imroc/req | resp.go | ToXML | func (r *Resp) ToXML(v interface{}) error {
data, err := r.ToBytes()
if err != nil {
return err
}
return xml.Unmarshal(data, v)
} | go | func (r *Resp) ToXML(v interface{}) error {
data, err := r.ToBytes()
if err != nil {
return err
}
return xml.Unmarshal(data, v)
} | [
"func",
"(",
"r",
"*",
"Resp",
")",
"ToXML",
"(",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"data",
",",
"err",
":=",
"r",
".",
"ToBytes",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"xml",
".",
"Unmarshal",
"(",
"data",
",",
"v",
")",
"\n",
"}"
] | // ToXML convert xml response body to struct or map | [
"ToXML",
"convert",
"xml",
"response",
"body",
"to",
"struct",
"or",
"map"
] | b355b6f6842fbda1bee879f2846cb79424cad4de | https://github.com/imroc/req/blob/b355b6f6842fbda1bee879f2846cb79424cad4de/resp.go#L89-L95 |
151,226 | imroc/req | resp.go | ToFile | func (r *Resp) ToFile(name string) error {
//TODO set name to the suffix of url path if name == ""
file, err := os.Create(name)
if err != nil {
return err
}
defer file.Close()
if r.respBody != nil {
_, err = file.Write(r.respBody)
return err
}
if r.downloadProgress != nil && r.resp.ContentLength > 0 {
return r.download(file)
}
defer r.resp.Body.Close()
_, err = io.Copy(file, r.resp.Body)
return err
} | go | func (r *Resp) ToFile(name string) error {
//TODO set name to the suffix of url path if name == ""
file, err := os.Create(name)
if err != nil {
return err
}
defer file.Close()
if r.respBody != nil {
_, err = file.Write(r.respBody)
return err
}
if r.downloadProgress != nil && r.resp.ContentLength > 0 {
return r.download(file)
}
defer r.resp.Body.Close()
_, err = io.Copy(file, r.resp.Body)
return err
} | [
"func",
"(",
"r",
"*",
"Resp",
")",
"ToFile",
"(",
"name",
"string",
")",
"error",
"{",
"//TODO set name to the suffix of url path if name == \"\"",
"file",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"file",
".",
"Close",
"(",
")",
"\n\n",
"if",
"r",
".",
"respBody",
"!=",
"nil",
"{",
"_",
",",
"err",
"=",
"file",
".",
"Write",
"(",
"r",
".",
"respBody",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"r",
".",
"downloadProgress",
"!=",
"nil",
"&&",
"r",
".",
"resp",
".",
"ContentLength",
">",
"0",
"{",
"return",
"r",
".",
"download",
"(",
"file",
")",
"\n",
"}",
"\n\n",
"defer",
"r",
".",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"file",
",",
"r",
".",
"resp",
".",
"Body",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // ToFile download the response body to file with optional download callback | [
"ToFile",
"download",
"the",
"response",
"body",
"to",
"file",
"with",
"optional",
"download",
"callback"
] | b355b6f6842fbda1bee879f2846cb79424cad4de | https://github.com/imroc/req/blob/b355b6f6842fbda1bee879f2846cb79424cad4de/resp.go#L98-L118 |
151,227 | imroc/req | resp.go | Format | func (r *Resp) Format(s fmt.State, verb rune) {
if r == nil || r.req == nil {
return
}
if s.Flag('+') { // include header and format pretty.
fmt.Fprint(s, r.Dump())
} else if s.Flag('-') { // keep all informations in one line.
r.miniFormat(s)
} else { // auto
r.autoFormat(s)
}
} | go | func (r *Resp) Format(s fmt.State, verb rune) {
if r == nil || r.req == nil {
return
}
if s.Flag('+') { // include header and format pretty.
fmt.Fprint(s, r.Dump())
} else if s.Flag('-') { // keep all informations in one line.
r.miniFormat(s)
} else { // auto
r.autoFormat(s)
}
} | [
"func",
"(",
"r",
"*",
"Resp",
")",
"Format",
"(",
"s",
"fmt",
".",
"State",
",",
"verb",
"rune",
")",
"{",
"if",
"r",
"==",
"nil",
"||",
"r",
".",
"req",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"s",
".",
"Flag",
"(",
"'+'",
")",
"{",
"// include header and format pretty.",
"fmt",
".",
"Fprint",
"(",
"s",
",",
"r",
".",
"Dump",
"(",
")",
")",
"\n",
"}",
"else",
"if",
"s",
".",
"Flag",
"(",
"'-'",
")",
"{",
"// keep all informations in one line.",
"r",
".",
"miniFormat",
"(",
"s",
")",
"\n",
"}",
"else",
"{",
"// auto",
"r",
".",
"autoFormat",
"(",
"s",
")",
"\n",
"}",
"\n",
"}"
] | // Format fort the response | [
"Format",
"fort",
"the",
"response"
] | b355b6f6842fbda1bee879f2846cb79424cad4de | https://github.com/imroc/req/blob/b355b6f6842fbda1bee879f2846cb79424cad4de/resp.go#L204-L215 |
151,228 | imroc/req | setting.go | newClient | func newClient() *http.Client {
jar, _ := cookiejar.New(nil)
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
return &http.Client{
Jar: jar,
Transport: transport,
Timeout: 2 * time.Minute,
}
} | go | func newClient() *http.Client {
jar, _ := cookiejar.New(nil)
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
return &http.Client{
Jar: jar,
Transport: transport,
Timeout: 2 * time.Minute,
}
} | [
"func",
"newClient",
"(",
")",
"*",
"http",
".",
"Client",
"{",
"jar",
",",
"_",
":=",
"cookiejar",
".",
"New",
"(",
"nil",
")",
"\n",
"transport",
":=",
"&",
"http",
".",
"Transport",
"{",
"Proxy",
":",
"http",
".",
"ProxyFromEnvironment",
",",
"DialContext",
":",
"(",
"&",
"net",
".",
"Dialer",
"{",
"Timeout",
":",
"30",
"*",
"time",
".",
"Second",
",",
"KeepAlive",
":",
"30",
"*",
"time",
".",
"Second",
",",
"DualStack",
":",
"true",
",",
"}",
")",
".",
"DialContext",
",",
"MaxIdleConns",
":",
"100",
",",
"IdleConnTimeout",
":",
"90",
"*",
"time",
".",
"Second",
",",
"TLSHandshakeTimeout",
":",
"10",
"*",
"time",
".",
"Second",
",",
"ExpectContinueTimeout",
":",
"1",
"*",
"time",
".",
"Second",
",",
"}",
"\n",
"return",
"&",
"http",
".",
"Client",
"{",
"Jar",
":",
"jar",
",",
"Transport",
":",
"transport",
",",
"Timeout",
":",
"2",
"*",
"time",
".",
"Minute",
",",
"}",
"\n",
"}"
] | // create a default client | [
"create",
"a",
"default",
"client"
] | b355b6f6842fbda1bee879f2846cb79424cad4de | https://github.com/imroc/req/blob/b355b6f6842fbda1bee879f2846cb79424cad4de/setting.go#L14-L33 |
151,229 | imroc/req | setting.go | Client | func (r *Req) Client() *http.Client {
if r.client == nil {
r.client = newClient()
}
return r.client
} | go | func (r *Req) Client() *http.Client {
if r.client == nil {
r.client = newClient()
}
return r.client
} | [
"func",
"(",
"r",
"*",
"Req",
")",
"Client",
"(",
")",
"*",
"http",
".",
"Client",
"{",
"if",
"r",
".",
"client",
"==",
"nil",
"{",
"r",
".",
"client",
"=",
"newClient",
"(",
")",
"\n",
"}",
"\n",
"return",
"r",
".",
"client",
"\n",
"}"
] | // Client return the default underlying http client | [
"Client",
"return",
"the",
"default",
"underlying",
"http",
"client"
] | b355b6f6842fbda1bee879f2846cb79424cad4de | https://github.com/imroc/req/blob/b355b6f6842fbda1bee879f2846cb79424cad4de/setting.go#L36-L41 |
151,230 | imroc/req | setting.go | EnableInsecureTLS | func (r *Req) EnableInsecureTLS(enable bool) {
trans := r.getTransport()
if trans == nil {
return
}
if trans.TLSClientConfig == nil {
trans.TLSClientConfig = &tls.Config{}
}
trans.TLSClientConfig.InsecureSkipVerify = enable
} | go | func (r *Req) EnableInsecureTLS(enable bool) {
trans := r.getTransport()
if trans == nil {
return
}
if trans.TLSClientConfig == nil {
trans.TLSClientConfig = &tls.Config{}
}
trans.TLSClientConfig.InsecureSkipVerify = enable
} | [
"func",
"(",
"r",
"*",
"Req",
")",
"EnableInsecureTLS",
"(",
"enable",
"bool",
")",
"{",
"trans",
":=",
"r",
".",
"getTransport",
"(",
")",
"\n",
"if",
"trans",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"trans",
".",
"TLSClientConfig",
"==",
"nil",
"{",
"trans",
".",
"TLSClientConfig",
"=",
"&",
"tls",
".",
"Config",
"{",
"}",
"\n",
"}",
"\n",
"trans",
".",
"TLSClientConfig",
".",
"InsecureSkipVerify",
"=",
"enable",
"\n",
"}"
] | // EnableInsecureTLS allows insecure https | [
"EnableInsecureTLS",
"allows",
"insecure",
"https"
] | b355b6f6842fbda1bee879f2846cb79424cad4de | https://github.com/imroc/req/blob/b355b6f6842fbda1bee879f2846cb79424cad4de/setting.go#L84-L93 |
151,231 | imroc/req | setting.go | EnableCookie | func (r *Req) EnableCookie(enable bool) {
if enable {
jar, _ := cookiejar.New(nil)
r.Client().Jar = jar
} else {
r.Client().Jar = nil
}
} | go | func (r *Req) EnableCookie(enable bool) {
if enable {
jar, _ := cookiejar.New(nil)
r.Client().Jar = jar
} else {
r.Client().Jar = nil
}
} | [
"func",
"(",
"r",
"*",
"Req",
")",
"EnableCookie",
"(",
"enable",
"bool",
")",
"{",
"if",
"enable",
"{",
"jar",
",",
"_",
":=",
"cookiejar",
".",
"New",
"(",
"nil",
")",
"\n",
"r",
".",
"Client",
"(",
")",
".",
"Jar",
"=",
"jar",
"\n",
"}",
"else",
"{",
"r",
".",
"Client",
"(",
")",
".",
"Jar",
"=",
"nil",
"\n",
"}",
"\n",
"}"
] | // EnableCookieenable or disable cookie manager | [
"EnableCookieenable",
"or",
"disable",
"cookie",
"manager"
] | b355b6f6842fbda1bee879f2846cb79424cad4de | https://github.com/imroc/req/blob/b355b6f6842fbda1bee879f2846cb79424cad4de/setting.go#L100-L107 |
151,232 | imroc/req | setting.go | SetTimeout | func (r *Req) SetTimeout(d time.Duration) {
r.Client().Timeout = d
} | go | func (r *Req) SetTimeout(d time.Duration) {
r.Client().Timeout = d
} | [
"func",
"(",
"r",
"*",
"Req",
")",
"SetTimeout",
"(",
"d",
"time",
".",
"Duration",
")",
"{",
"r",
".",
"Client",
"(",
")",
".",
"Timeout",
"=",
"d",
"\n",
"}"
] | // SetTimeout sets the timeout for every request | [
"SetTimeout",
"sets",
"the",
"timeout",
"for",
"every",
"request"
] | b355b6f6842fbda1bee879f2846cb79424cad4de | https://github.com/imroc/req/blob/b355b6f6842fbda1bee879f2846cb79424cad4de/setting.go#L115-L117 |
151,233 | imroc/req | setting.go | SetProxyUrl | func (r *Req) SetProxyUrl(rawurl string) error {
trans := r.getTransport()
if trans == nil {
return errors.New("req: no transport")
}
u, err := url.Parse(rawurl)
if err != nil {
return err
}
trans.Proxy = http.ProxyURL(u)
return nil
} | go | func (r *Req) SetProxyUrl(rawurl string) error {
trans := r.getTransport()
if trans == nil {
return errors.New("req: no transport")
}
u, err := url.Parse(rawurl)
if err != nil {
return err
}
trans.Proxy = http.ProxyURL(u)
return nil
} | [
"func",
"(",
"r",
"*",
"Req",
")",
"SetProxyUrl",
"(",
"rawurl",
"string",
")",
"error",
"{",
"trans",
":=",
"r",
".",
"getTransport",
"(",
")",
"\n",
"if",
"trans",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"u",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"rawurl",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"trans",
".",
"Proxy",
"=",
"http",
".",
"ProxyURL",
"(",
"u",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // SetProxyUrl set the simple proxy with fixed proxy url | [
"SetProxyUrl",
"set",
"the",
"simple",
"proxy",
"with",
"fixed",
"proxy",
"url"
] | b355b6f6842fbda1bee879f2846cb79424cad4de | https://github.com/imroc/req/blob/b355b6f6842fbda1bee879f2846cb79424cad4de/setting.go#L125-L136 |
151,234 | imroc/req | setting.go | SetXMLIndent | func (r *Req) SetXMLIndent(prefix, indent string) {
opts := r.getXMLEncOpts()
opts.prefix = prefix
opts.indent = indent
} | go | func (r *Req) SetXMLIndent(prefix, indent string) {
opts := r.getXMLEncOpts()
opts.prefix = prefix
opts.indent = indent
} | [
"func",
"(",
"r",
"*",
"Req",
")",
"SetXMLIndent",
"(",
"prefix",
",",
"indent",
"string",
")",
"{",
"opts",
":=",
"r",
".",
"getXMLEncOpts",
"(",
")",
"\n",
"opts",
".",
"prefix",
"=",
"prefix",
"\n",
"opts",
".",
"indent",
"=",
"indent",
"\n",
"}"
] | // SetXMLIndent sets the encoder to generate XML in which each element
// begins on a new indented line that starts with prefix and is followed by
// one or more copies of indent according to the nesting depth. | [
"SetXMLIndent",
"sets",
"the",
"encoder",
"to",
"generate",
"XML",
"in",
"which",
"each",
"element",
"begins",
"on",
"a",
"new",
"indented",
"line",
"that",
"starts",
"with",
"prefix",
"and",
"is",
"followed",
"by",
"one",
"or",
"more",
"copies",
"of",
"indent",
"according",
"to",
"the",
"nesting",
"depth",
"."
] | b355b6f6842fbda1bee879f2846cb79424cad4de | https://github.com/imroc/req/blob/b355b6f6842fbda1bee879f2846cb79424cad4de/setting.go#L225-L229 |
151,235 | imroc/req | dump.go | Dump | func (r *Resp) Dump() string {
dump := new(dumpBuffer)
if r.r.flag&Lcost != 0 {
dump.WriteString(fmt.Sprint(r.cost))
}
r.dumpRequest(dump)
l := dump.Len()
if l > 0 {
dump.WriteString("=================================")
l = dump.Len()
}
r.dumpResponse(dump)
return dump.String()
} | go | func (r *Resp) Dump() string {
dump := new(dumpBuffer)
if r.r.flag&Lcost != 0 {
dump.WriteString(fmt.Sprint(r.cost))
}
r.dumpRequest(dump)
l := dump.Len()
if l > 0 {
dump.WriteString("=================================")
l = dump.Len()
}
r.dumpResponse(dump)
return dump.String()
} | [
"func",
"(",
"r",
"*",
"Resp",
")",
"Dump",
"(",
")",
"string",
"{",
"dump",
":=",
"new",
"(",
"dumpBuffer",
")",
"\n",
"if",
"r",
".",
"r",
".",
"flag",
"&",
"Lcost",
"!=",
"0",
"{",
"dump",
".",
"WriteString",
"(",
"fmt",
".",
"Sprint",
"(",
"r",
".",
"cost",
")",
")",
"\n",
"}",
"\n",
"r",
".",
"dumpRequest",
"(",
"dump",
")",
"\n",
"l",
":=",
"dump",
".",
"Len",
"(",
")",
"\n",
"if",
"l",
">",
"0",
"{",
"dump",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"l",
"=",
"dump",
".",
"Len",
"(",
")",
"\n",
"}",
"\n\n",
"r",
".",
"dumpResponse",
"(",
"dump",
")",
"\n\n",
"return",
"dump",
".",
"String",
"(",
")",
"\n",
"}"
] | // Dump dump the request | [
"Dump",
"dump",
"the",
"request"
] | b355b6f6842fbda1bee879f2846cb79424cad4de | https://github.com/imroc/req/blob/b355b6f6842fbda1bee879f2846cb79424cad4de/dump.go#L201-L216 |
151,236 | imroc/req | req.go | Post | func Post(url string, v ...interface{}) (*Resp, error) {
return std.Post(url, v...)
} | go | func Post(url string, v ...interface{}) (*Resp, error) {
return std.Post(url, v...)
} | [
"func",
"Post",
"(",
"url",
"string",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"(",
"*",
"Resp",
",",
"error",
")",
"{",
"return",
"std",
".",
"Post",
"(",
"url",
",",
"v",
"...",
")",
"\n",
"}"
] | // Post execute a http POST request | [
"Post",
"execute",
"a",
"http",
"POST",
"request"
] | b355b6f6842fbda1bee879f2846cb79424cad4de | https://github.com/imroc/req/blob/b355b6f6842fbda1bee879f2846cb79424cad4de/req.go#L655-L657 |
151,237 | imroc/req | req.go | Put | func Put(url string, v ...interface{}) (*Resp, error) {
return std.Put(url, v...)
} | go | func Put(url string, v ...interface{}) (*Resp, error) {
return std.Put(url, v...)
} | [
"func",
"Put",
"(",
"url",
"string",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"(",
"*",
"Resp",
",",
"error",
")",
"{",
"return",
"std",
".",
"Put",
"(",
"url",
",",
"v",
"...",
")",
"\n",
"}"
] | // Put execute a http PUT request | [
"Put",
"execute",
"a",
"http",
"PUT",
"request"
] | b355b6f6842fbda1bee879f2846cb79424cad4de | https://github.com/imroc/req/blob/b355b6f6842fbda1bee879f2846cb79424cad4de/req.go#L660-L662 |
151,238 | imroc/req | req.go | Head | func Head(url string, v ...interface{}) (*Resp, error) {
return std.Head(url, v...)
} | go | func Head(url string, v ...interface{}) (*Resp, error) {
return std.Head(url, v...)
} | [
"func",
"Head",
"(",
"url",
"string",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"(",
"*",
"Resp",
",",
"error",
")",
"{",
"return",
"std",
".",
"Head",
"(",
"url",
",",
"v",
"...",
")",
"\n",
"}"
] | // Head execute a http HEAD request | [
"Head",
"execute",
"a",
"http",
"HEAD",
"request"
] | b355b6f6842fbda1bee879f2846cb79424cad4de | https://github.com/imroc/req/blob/b355b6f6842fbda1bee879f2846cb79424cad4de/req.go#L665-L667 |
151,239 | imroc/req | req.go | Options | func Options(url string, v ...interface{}) (*Resp, error) {
return std.Options(url, v...)
} | go | func Options(url string, v ...interface{}) (*Resp, error) {
return std.Options(url, v...)
} | [
"func",
"Options",
"(",
"url",
"string",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"(",
"*",
"Resp",
",",
"error",
")",
"{",
"return",
"std",
".",
"Options",
"(",
"url",
",",
"v",
"...",
")",
"\n",
"}"
] | // Options execute a http OPTIONS request | [
"Options",
"execute",
"a",
"http",
"OPTIONS",
"request"
] | b355b6f6842fbda1bee879f2846cb79424cad4de | https://github.com/imroc/req/blob/b355b6f6842fbda1bee879f2846cb79424cad4de/req.go#L670-L672 |
151,240 | imroc/req | req.go | Delete | func Delete(url string, v ...interface{}) (*Resp, error) {
return std.Delete(url, v...)
} | go | func Delete(url string, v ...interface{}) (*Resp, error) {
return std.Delete(url, v...)
} | [
"func",
"Delete",
"(",
"url",
"string",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"(",
"*",
"Resp",
",",
"error",
")",
"{",
"return",
"std",
".",
"Delete",
"(",
"url",
",",
"v",
"...",
")",
"\n",
"}"
] | // Delete execute a http DELETE request | [
"Delete",
"execute",
"a",
"http",
"DELETE",
"request"
] | b355b6f6842fbda1bee879f2846cb79424cad4de | https://github.com/imroc/req/blob/b355b6f6842fbda1bee879f2846cb79424cad4de/req.go#L675-L677 |
151,241 | imroc/req | req.go | Patch | func Patch(url string, v ...interface{}) (*Resp, error) {
return std.Patch(url, v...)
} | go | func Patch(url string, v ...interface{}) (*Resp, error) {
return std.Patch(url, v...)
} | [
"func",
"Patch",
"(",
"url",
"string",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"(",
"*",
"Resp",
",",
"error",
")",
"{",
"return",
"std",
".",
"Patch",
"(",
"url",
",",
"v",
"...",
")",
"\n",
"}"
] | // Patch execute a http PATCH request | [
"Patch",
"execute",
"a",
"http",
"PATCH",
"request"
] | b355b6f6842fbda1bee879f2846cb79424cad4de | https://github.com/imroc/req/blob/b355b6f6842fbda1bee879f2846cb79424cad4de/req.go#L680-L682 |
151,242 | imroc/req | req.go | Do | func Do(method, url string, v ...interface{}) (*Resp, error) {
return std.Do(method, url, v...)
} | go | func Do(method, url string, v ...interface{}) (*Resp, error) {
return std.Do(method, url, v...)
} | [
"func",
"Do",
"(",
"method",
",",
"url",
"string",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"(",
"*",
"Resp",
",",
"error",
")",
"{",
"return",
"std",
".",
"Do",
"(",
"method",
",",
"url",
",",
"v",
"...",
")",
"\n",
"}"
] | // Do execute request. | [
"Do",
"execute",
"request",
"."
] | b355b6f6842fbda1bee879f2846cb79424cad4de | https://github.com/imroc/req/blob/b355b6f6842fbda1bee879f2846cb79424cad4de/req.go#L685-L687 |
151,243 | armon/go-metrics | circonus/circonus.go | SetGauge | func (s *CirconusSink) SetGauge(key []string, val float32) {
flatKey := s.flattenKey(key)
s.metrics.SetGauge(flatKey, int64(val))
} | go | func (s *CirconusSink) SetGauge(key []string, val float32) {
flatKey := s.flattenKey(key)
s.metrics.SetGauge(flatKey, int64(val))
} | [
"func",
"(",
"s",
"*",
"CirconusSink",
")",
"SetGauge",
"(",
"key",
"[",
"]",
"string",
",",
"val",
"float32",
")",
"{",
"flatKey",
":=",
"s",
".",
"flattenKey",
"(",
"key",
")",
"\n",
"s",
".",
"metrics",
".",
"SetGauge",
"(",
"flatKey",
",",
"int64",
"(",
"val",
")",
")",
"\n",
"}"
] | // SetGauge sets value for a gauge metric | [
"SetGauge",
"sets",
"value",
"for",
"a",
"gauge",
"metric"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/circonus/circonus.go#L60-L63 |
151,244 | armon/go-metrics | circonus/circonus.go | SetGaugeWithLabels | func (s *CirconusSink) SetGaugeWithLabels(key []string, val float32, labels []metrics.Label) {
flatKey := s.flattenKeyLabels(key, labels)
s.metrics.SetGauge(flatKey, int64(val))
} | go | func (s *CirconusSink) SetGaugeWithLabels(key []string, val float32, labels []metrics.Label) {
flatKey := s.flattenKeyLabels(key, labels)
s.metrics.SetGauge(flatKey, int64(val))
} | [
"func",
"(",
"s",
"*",
"CirconusSink",
")",
"SetGaugeWithLabels",
"(",
"key",
"[",
"]",
"string",
",",
"val",
"float32",
",",
"labels",
"[",
"]",
"metrics",
".",
"Label",
")",
"{",
"flatKey",
":=",
"s",
".",
"flattenKeyLabels",
"(",
"key",
",",
"labels",
")",
"\n",
"s",
".",
"metrics",
".",
"SetGauge",
"(",
"flatKey",
",",
"int64",
"(",
"val",
")",
")",
"\n",
"}"
] | // SetGaugeWithLabels sets value for a gauge metric with the given labels | [
"SetGaugeWithLabels",
"sets",
"value",
"for",
"a",
"gauge",
"metric",
"with",
"the",
"given",
"labels"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/circonus/circonus.go#L66-L69 |
151,245 | armon/go-metrics | circonus/circonus.go | IncrCounter | func (s *CirconusSink) IncrCounter(key []string, val float32) {
flatKey := s.flattenKey(key)
s.metrics.IncrementByValue(flatKey, uint64(val))
} | go | func (s *CirconusSink) IncrCounter(key []string, val float32) {
flatKey := s.flattenKey(key)
s.metrics.IncrementByValue(flatKey, uint64(val))
} | [
"func",
"(",
"s",
"*",
"CirconusSink",
")",
"IncrCounter",
"(",
"key",
"[",
"]",
"string",
",",
"val",
"float32",
")",
"{",
"flatKey",
":=",
"s",
".",
"flattenKey",
"(",
"key",
")",
"\n",
"s",
".",
"metrics",
".",
"IncrementByValue",
"(",
"flatKey",
",",
"uint64",
"(",
"val",
")",
")",
"\n",
"}"
] | // IncrCounter increments a counter metric | [
"IncrCounter",
"increments",
"a",
"counter",
"metric"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/circonus/circonus.go#L77-L80 |
151,246 | armon/go-metrics | circonus/circonus.go | IncrCounterWithLabels | func (s *CirconusSink) IncrCounterWithLabels(key []string, val float32, labels []metrics.Label) {
flatKey := s.flattenKeyLabels(key, labels)
s.metrics.IncrementByValue(flatKey, uint64(val))
} | go | func (s *CirconusSink) IncrCounterWithLabels(key []string, val float32, labels []metrics.Label) {
flatKey := s.flattenKeyLabels(key, labels)
s.metrics.IncrementByValue(flatKey, uint64(val))
} | [
"func",
"(",
"s",
"*",
"CirconusSink",
")",
"IncrCounterWithLabels",
"(",
"key",
"[",
"]",
"string",
",",
"val",
"float32",
",",
"labels",
"[",
"]",
"metrics",
".",
"Label",
")",
"{",
"flatKey",
":=",
"s",
".",
"flattenKeyLabels",
"(",
"key",
",",
"labels",
")",
"\n",
"s",
".",
"metrics",
".",
"IncrementByValue",
"(",
"flatKey",
",",
"uint64",
"(",
"val",
")",
")",
"\n",
"}"
] | // IncrCounterWithLabels increments a counter metric with the given labels | [
"IncrCounterWithLabels",
"increments",
"a",
"counter",
"metric",
"with",
"the",
"given",
"labels"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/circonus/circonus.go#L83-L86 |
151,247 | armon/go-metrics | circonus/circonus.go | AddSample | func (s *CirconusSink) AddSample(key []string, val float32) {
flatKey := s.flattenKey(key)
s.metrics.RecordValue(flatKey, float64(val))
} | go | func (s *CirconusSink) AddSample(key []string, val float32) {
flatKey := s.flattenKey(key)
s.metrics.RecordValue(flatKey, float64(val))
} | [
"func",
"(",
"s",
"*",
"CirconusSink",
")",
"AddSample",
"(",
"key",
"[",
"]",
"string",
",",
"val",
"float32",
")",
"{",
"flatKey",
":=",
"s",
".",
"flattenKey",
"(",
"key",
")",
"\n",
"s",
".",
"metrics",
".",
"RecordValue",
"(",
"flatKey",
",",
"float64",
"(",
"val",
")",
")",
"\n",
"}"
] | // AddSample adds a sample to a histogram metric | [
"AddSample",
"adds",
"a",
"sample",
"to",
"a",
"histogram",
"metric"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/circonus/circonus.go#L89-L92 |
151,248 | armon/go-metrics | circonus/circonus.go | AddSampleWithLabels | func (s *CirconusSink) AddSampleWithLabels(key []string, val float32, labels []metrics.Label) {
flatKey := s.flattenKeyLabels(key, labels)
s.metrics.RecordValue(flatKey, float64(val))
} | go | func (s *CirconusSink) AddSampleWithLabels(key []string, val float32, labels []metrics.Label) {
flatKey := s.flattenKeyLabels(key, labels)
s.metrics.RecordValue(flatKey, float64(val))
} | [
"func",
"(",
"s",
"*",
"CirconusSink",
")",
"AddSampleWithLabels",
"(",
"key",
"[",
"]",
"string",
",",
"val",
"float32",
",",
"labels",
"[",
"]",
"metrics",
".",
"Label",
")",
"{",
"flatKey",
":=",
"s",
".",
"flattenKeyLabels",
"(",
"key",
",",
"labels",
")",
"\n",
"s",
".",
"metrics",
".",
"RecordValue",
"(",
"flatKey",
",",
"float64",
"(",
"val",
")",
")",
"\n",
"}"
] | // AddSampleWithLabels adds a sample to a histogram metric with the given labels | [
"AddSampleWithLabels",
"adds",
"a",
"sample",
"to",
"a",
"histogram",
"metric",
"with",
"the",
"given",
"labels"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/circonus/circonus.go#L95-L98 |
151,249 | armon/go-metrics | statsite.go | NewStatsiteSink | func NewStatsiteSink(addr string) (*StatsiteSink, error) {
s := &StatsiteSink{
addr: addr,
metricQueue: make(chan string, 4096),
}
go s.flushMetrics()
return s, nil
} | go | func NewStatsiteSink(addr string) (*StatsiteSink, error) {
s := &StatsiteSink{
addr: addr,
metricQueue: make(chan string, 4096),
}
go s.flushMetrics()
return s, nil
} | [
"func",
"NewStatsiteSink",
"(",
"addr",
"string",
")",
"(",
"*",
"StatsiteSink",
",",
"error",
")",
"{",
"s",
":=",
"&",
"StatsiteSink",
"{",
"addr",
":",
"addr",
",",
"metricQueue",
":",
"make",
"(",
"chan",
"string",
",",
"4096",
")",
",",
"}",
"\n",
"go",
"s",
".",
"flushMetrics",
"(",
")",
"\n",
"return",
"s",
",",
"nil",
"\n",
"}"
] | // NewStatsiteSink is used to create a new StatsiteSink | [
"NewStatsiteSink",
"is",
"used",
"to",
"create",
"a",
"new",
"StatsiteSink"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/statsite.go#L34-L41 |
151,250 | armon/go-metrics | datadog/dogstatsd.go | NewDogStatsdSink | func NewDogStatsdSink(addr string, hostName string) (*DogStatsdSink, error) {
client, err := statsd.New(addr)
if err != nil {
return nil, err
}
sink := &DogStatsdSink{
client: client,
hostName: hostName,
propagateHostname: false,
}
return sink, nil
} | go | func NewDogStatsdSink(addr string, hostName string) (*DogStatsdSink, error) {
client, err := statsd.New(addr)
if err != nil {
return nil, err
}
sink := &DogStatsdSink{
client: client,
hostName: hostName,
propagateHostname: false,
}
return sink, nil
} | [
"func",
"NewDogStatsdSink",
"(",
"addr",
"string",
",",
"hostName",
"string",
")",
"(",
"*",
"DogStatsdSink",
",",
"error",
")",
"{",
"client",
",",
"err",
":=",
"statsd",
".",
"New",
"(",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"sink",
":=",
"&",
"DogStatsdSink",
"{",
"client",
":",
"client",
",",
"hostName",
":",
"hostName",
",",
"propagateHostname",
":",
"false",
",",
"}",
"\n",
"return",
"sink",
",",
"nil",
"\n",
"}"
] | // NewDogStatsdSink is used to create a new DogStatsdSink with sane defaults | [
"NewDogStatsdSink",
"is",
"used",
"to",
"create",
"a",
"new",
"DogStatsdSink",
"with",
"sane",
"defaults"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/datadog/dogstatsd.go#L20-L31 |
151,251 | armon/go-metrics | datadog/dogstatsd.go | SetGauge | func (s *DogStatsdSink) SetGauge(key []string, val float32) {
s.SetGaugeWithLabels(key, val, nil)
} | go | func (s *DogStatsdSink) SetGauge(key []string, val float32) {
s.SetGaugeWithLabels(key, val, nil)
} | [
"func",
"(",
"s",
"*",
"DogStatsdSink",
")",
"SetGauge",
"(",
"key",
"[",
"]",
"string",
",",
"val",
"float32",
")",
"{",
"s",
".",
"SetGaugeWithLabels",
"(",
"key",
",",
"val",
",",
"nil",
")",
"\n",
"}"
] | // Implementation of methods in the MetricSink interface | [
"Implementation",
"of",
"methods",
"in",
"the",
"MetricSink",
"interface"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/datadog/dogstatsd.go#L86-L88 |
151,252 | armon/go-metrics | inmem_signal.go | NewInmemSignal | func NewInmemSignal(inmem *InmemSink, sig syscall.Signal, w io.Writer) *InmemSignal {
i := &InmemSignal{
signal: sig,
inm: inmem,
w: w,
sigCh: make(chan os.Signal, 1),
stopCh: make(chan struct{}),
}
signal.Notify(i.sigCh, sig)
go i.run()
return i
} | go | func NewInmemSignal(inmem *InmemSink, sig syscall.Signal, w io.Writer) *InmemSignal {
i := &InmemSignal{
signal: sig,
inm: inmem,
w: w,
sigCh: make(chan os.Signal, 1),
stopCh: make(chan struct{}),
}
signal.Notify(i.sigCh, sig)
go i.run()
return i
} | [
"func",
"NewInmemSignal",
"(",
"inmem",
"*",
"InmemSink",
",",
"sig",
"syscall",
".",
"Signal",
",",
"w",
"io",
".",
"Writer",
")",
"*",
"InmemSignal",
"{",
"i",
":=",
"&",
"InmemSignal",
"{",
"signal",
":",
"sig",
",",
"inm",
":",
"inmem",
",",
"w",
":",
"w",
",",
"sigCh",
":",
"make",
"(",
"chan",
"os",
".",
"Signal",
",",
"1",
")",
",",
"stopCh",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"}",
"\n",
"signal",
".",
"Notify",
"(",
"i",
".",
"sigCh",
",",
"sig",
")",
"\n",
"go",
"i",
".",
"run",
"(",
")",
"\n",
"return",
"i",
"\n",
"}"
] | // NewInmemSignal creates a new InmemSignal which listens for a given signal,
// and dumps the current metrics out to a writer | [
"NewInmemSignal",
"creates",
"a",
"new",
"InmemSignal",
"which",
"listens",
"for",
"a",
"given",
"signal",
"and",
"dumps",
"the",
"current",
"metrics",
"out",
"to",
"a",
"writer"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/inmem_signal.go#L29-L40 |
151,253 | armon/go-metrics | inmem_signal.go | Stop | func (i *InmemSignal) Stop() {
i.stopLock.Lock()
defer i.stopLock.Unlock()
if i.stop {
return
}
i.stop = true
close(i.stopCh)
signal.Stop(i.sigCh)
} | go | func (i *InmemSignal) Stop() {
i.stopLock.Lock()
defer i.stopLock.Unlock()
if i.stop {
return
}
i.stop = true
close(i.stopCh)
signal.Stop(i.sigCh)
} | [
"func",
"(",
"i",
"*",
"InmemSignal",
")",
"Stop",
"(",
")",
"{",
"i",
".",
"stopLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"i",
".",
"stopLock",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"i",
".",
"stop",
"{",
"return",
"\n",
"}",
"\n",
"i",
".",
"stop",
"=",
"true",
"\n",
"close",
"(",
"i",
".",
"stopCh",
")",
"\n",
"signal",
".",
"Stop",
"(",
"i",
".",
"sigCh",
")",
"\n",
"}"
] | // Stop is used to stop the InmemSignal from listening | [
"Stop",
"is",
"used",
"to",
"stop",
"the",
"InmemSignal",
"from",
"listening"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/inmem_signal.go#L49-L59 |
151,254 | armon/go-metrics | inmem_signal.go | dumpStats | func (i *InmemSignal) dumpStats() {
buf := bytes.NewBuffer(nil)
data := i.inm.Data()
// Skip the last period which is still being aggregated
for j := 0; j < len(data)-1; j++ {
intv := data[j]
intv.RLock()
for _, val := range intv.Gauges {
name := i.flattenLabels(val.Name, val.Labels)
fmt.Fprintf(buf, "[%v][G] '%s': %0.3f\n", intv.Interval, name, val.Value)
}
for name, vals := range intv.Points {
for _, val := range vals {
fmt.Fprintf(buf, "[%v][P] '%s': %0.3f\n", intv.Interval, name, val)
}
}
for _, agg := range intv.Counters {
name := i.flattenLabels(agg.Name, agg.Labels)
fmt.Fprintf(buf, "[%v][C] '%s': %s\n", intv.Interval, name, agg.AggregateSample)
}
for _, agg := range intv.Samples {
name := i.flattenLabels(agg.Name, agg.Labels)
fmt.Fprintf(buf, "[%v][S] '%s': %s\n", intv.Interval, name, agg.AggregateSample)
}
intv.RUnlock()
}
// Write out the bytes
i.w.Write(buf.Bytes())
} | go | func (i *InmemSignal) dumpStats() {
buf := bytes.NewBuffer(nil)
data := i.inm.Data()
// Skip the last period which is still being aggregated
for j := 0; j < len(data)-1; j++ {
intv := data[j]
intv.RLock()
for _, val := range intv.Gauges {
name := i.flattenLabels(val.Name, val.Labels)
fmt.Fprintf(buf, "[%v][G] '%s': %0.3f\n", intv.Interval, name, val.Value)
}
for name, vals := range intv.Points {
for _, val := range vals {
fmt.Fprintf(buf, "[%v][P] '%s': %0.3f\n", intv.Interval, name, val)
}
}
for _, agg := range intv.Counters {
name := i.flattenLabels(agg.Name, agg.Labels)
fmt.Fprintf(buf, "[%v][C] '%s': %s\n", intv.Interval, name, agg.AggregateSample)
}
for _, agg := range intv.Samples {
name := i.flattenLabels(agg.Name, agg.Labels)
fmt.Fprintf(buf, "[%v][S] '%s': %s\n", intv.Interval, name, agg.AggregateSample)
}
intv.RUnlock()
}
// Write out the bytes
i.w.Write(buf.Bytes())
} | [
"func",
"(",
"i",
"*",
"InmemSignal",
")",
"dumpStats",
"(",
")",
"{",
"buf",
":=",
"bytes",
".",
"NewBuffer",
"(",
"nil",
")",
"\n\n",
"data",
":=",
"i",
".",
"inm",
".",
"Data",
"(",
")",
"\n",
"// Skip the last period which is still being aggregated",
"for",
"j",
":=",
"0",
";",
"j",
"<",
"len",
"(",
"data",
")",
"-",
"1",
";",
"j",
"++",
"{",
"intv",
":=",
"data",
"[",
"j",
"]",
"\n",
"intv",
".",
"RLock",
"(",
")",
"\n",
"for",
"_",
",",
"val",
":=",
"range",
"intv",
".",
"Gauges",
"{",
"name",
":=",
"i",
".",
"flattenLabels",
"(",
"val",
".",
"Name",
",",
"val",
".",
"Labels",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"buf",
",",
"\"",
"\\n",
"\"",
",",
"intv",
".",
"Interval",
",",
"name",
",",
"val",
".",
"Value",
")",
"\n",
"}",
"\n",
"for",
"name",
",",
"vals",
":=",
"range",
"intv",
".",
"Points",
"{",
"for",
"_",
",",
"val",
":=",
"range",
"vals",
"{",
"fmt",
".",
"Fprintf",
"(",
"buf",
",",
"\"",
"\\n",
"\"",
",",
"intv",
".",
"Interval",
",",
"name",
",",
"val",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"agg",
":=",
"range",
"intv",
".",
"Counters",
"{",
"name",
":=",
"i",
".",
"flattenLabels",
"(",
"agg",
".",
"Name",
",",
"agg",
".",
"Labels",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"buf",
",",
"\"",
"\\n",
"\"",
",",
"intv",
".",
"Interval",
",",
"name",
",",
"agg",
".",
"AggregateSample",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"agg",
":=",
"range",
"intv",
".",
"Samples",
"{",
"name",
":=",
"i",
".",
"flattenLabels",
"(",
"agg",
".",
"Name",
",",
"agg",
".",
"Labels",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"buf",
",",
"\"",
"\\n",
"\"",
",",
"intv",
".",
"Interval",
",",
"name",
",",
"agg",
".",
"AggregateSample",
")",
"\n",
"}",
"\n",
"intv",
".",
"RUnlock",
"(",
")",
"\n",
"}",
"\n\n",
"// Write out the bytes",
"i",
".",
"w",
".",
"Write",
"(",
"buf",
".",
"Bytes",
"(",
")",
")",
"\n",
"}"
] | // dumpStats is used to dump the data to output writer | [
"dumpStats",
"is",
"used",
"to",
"dump",
"the",
"data",
"to",
"output",
"writer"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/inmem_signal.go#L74-L104 |
151,255 | armon/go-metrics | metrics.go | UpdateFilter | func (m *Metrics) UpdateFilter(allow, block []string) {
m.UpdateFilterAndLabels(allow, block, m.AllowedLabels, m.BlockedLabels)
} | go | func (m *Metrics) UpdateFilter(allow, block []string) {
m.UpdateFilterAndLabels(allow, block, m.AllowedLabels, m.BlockedLabels)
} | [
"func",
"(",
"m",
"*",
"Metrics",
")",
"UpdateFilter",
"(",
"allow",
",",
"block",
"[",
"]",
"string",
")",
"{",
"m",
".",
"UpdateFilterAndLabels",
"(",
"allow",
",",
"block",
",",
"m",
".",
"AllowedLabels",
",",
"m",
".",
"BlockedLabels",
")",
"\n",
"}"
] | // UpdateFilter overwrites the existing filter with the given rules. | [
"UpdateFilter",
"overwrites",
"the",
"existing",
"filter",
"with",
"the",
"given",
"rules",
"."
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/metrics.go#L138-L140 |
151,256 | armon/go-metrics | metrics.go | UpdateFilterAndLabels | func (m *Metrics) UpdateFilterAndLabels(allow, block, allowedLabels, blockedLabels []string) {
m.filterLock.Lock()
defer m.filterLock.Unlock()
m.AllowedPrefixes = allow
m.BlockedPrefixes = block
if allowedLabels == nil {
// Having a white list means we take only elements from it
m.allowedLabels = nil
} else {
m.allowedLabels = make(map[string]bool)
for _, v := range allowedLabels {
m.allowedLabels[v] = true
}
}
m.blockedLabels = make(map[string]bool)
for _, v := range blockedLabels {
m.blockedLabels[v] = true
}
m.AllowedLabels = allowedLabels
m.BlockedLabels = blockedLabels
m.filter = iradix.New()
for _, prefix := range m.AllowedPrefixes {
m.filter, _, _ = m.filter.Insert([]byte(prefix), true)
}
for _, prefix := range m.BlockedPrefixes {
m.filter, _, _ = m.filter.Insert([]byte(prefix), false)
}
} | go | func (m *Metrics) UpdateFilterAndLabels(allow, block, allowedLabels, blockedLabels []string) {
m.filterLock.Lock()
defer m.filterLock.Unlock()
m.AllowedPrefixes = allow
m.BlockedPrefixes = block
if allowedLabels == nil {
// Having a white list means we take only elements from it
m.allowedLabels = nil
} else {
m.allowedLabels = make(map[string]bool)
for _, v := range allowedLabels {
m.allowedLabels[v] = true
}
}
m.blockedLabels = make(map[string]bool)
for _, v := range blockedLabels {
m.blockedLabels[v] = true
}
m.AllowedLabels = allowedLabels
m.BlockedLabels = blockedLabels
m.filter = iradix.New()
for _, prefix := range m.AllowedPrefixes {
m.filter, _, _ = m.filter.Insert([]byte(prefix), true)
}
for _, prefix := range m.BlockedPrefixes {
m.filter, _, _ = m.filter.Insert([]byte(prefix), false)
}
} | [
"func",
"(",
"m",
"*",
"Metrics",
")",
"UpdateFilterAndLabels",
"(",
"allow",
",",
"block",
",",
"allowedLabels",
",",
"blockedLabels",
"[",
"]",
"string",
")",
"{",
"m",
".",
"filterLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"filterLock",
".",
"Unlock",
"(",
")",
"\n\n",
"m",
".",
"AllowedPrefixes",
"=",
"allow",
"\n",
"m",
".",
"BlockedPrefixes",
"=",
"block",
"\n\n",
"if",
"allowedLabels",
"==",
"nil",
"{",
"// Having a white list means we take only elements from it",
"m",
".",
"allowedLabels",
"=",
"nil",
"\n",
"}",
"else",
"{",
"m",
".",
"allowedLabels",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"allowedLabels",
"{",
"m",
".",
"allowedLabels",
"[",
"v",
"]",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"m",
".",
"blockedLabels",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"blockedLabels",
"{",
"m",
".",
"blockedLabels",
"[",
"v",
"]",
"=",
"true",
"\n",
"}",
"\n",
"m",
".",
"AllowedLabels",
"=",
"allowedLabels",
"\n",
"m",
".",
"BlockedLabels",
"=",
"blockedLabels",
"\n\n",
"m",
".",
"filter",
"=",
"iradix",
".",
"New",
"(",
")",
"\n",
"for",
"_",
",",
"prefix",
":=",
"range",
"m",
".",
"AllowedPrefixes",
"{",
"m",
".",
"filter",
",",
"_",
",",
"_",
"=",
"m",
".",
"filter",
".",
"Insert",
"(",
"[",
"]",
"byte",
"(",
"prefix",
")",
",",
"true",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"prefix",
":=",
"range",
"m",
".",
"BlockedPrefixes",
"{",
"m",
".",
"filter",
",",
"_",
",",
"_",
"=",
"m",
".",
"filter",
".",
"Insert",
"(",
"[",
"]",
"byte",
"(",
"prefix",
")",
",",
"false",
")",
"\n",
"}",
"\n",
"}"
] | // UpdateFilterAndLabels overwrites the existing filter with the given rules. | [
"UpdateFilterAndLabels",
"overwrites",
"the",
"existing",
"filter",
"with",
"the",
"given",
"rules",
"."
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/metrics.go#L143-L173 |
151,257 | armon/go-metrics | metrics.go | labelIsAllowed | func (m *Metrics) labelIsAllowed(label *Label) bool {
labelName := (*label).Name
if m.blockedLabels != nil {
_, ok := m.blockedLabels[labelName]
if ok {
// If present, let's remove this label
return false
}
}
if m.allowedLabels != nil {
_, ok := m.allowedLabels[labelName]
return ok
}
// Allow by default
return true
} | go | func (m *Metrics) labelIsAllowed(label *Label) bool {
labelName := (*label).Name
if m.blockedLabels != nil {
_, ok := m.blockedLabels[labelName]
if ok {
// If present, let's remove this label
return false
}
}
if m.allowedLabels != nil {
_, ok := m.allowedLabels[labelName]
return ok
}
// Allow by default
return true
} | [
"func",
"(",
"m",
"*",
"Metrics",
")",
"labelIsAllowed",
"(",
"label",
"*",
"Label",
")",
"bool",
"{",
"labelName",
":=",
"(",
"*",
"label",
")",
".",
"Name",
"\n",
"if",
"m",
".",
"blockedLabels",
"!=",
"nil",
"{",
"_",
",",
"ok",
":=",
"m",
".",
"blockedLabels",
"[",
"labelName",
"]",
"\n",
"if",
"ok",
"{",
"// If present, let's remove this label",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"m",
".",
"allowedLabels",
"!=",
"nil",
"{",
"_",
",",
"ok",
":=",
"m",
".",
"allowedLabels",
"[",
"labelName",
"]",
"\n",
"return",
"ok",
"\n",
"}",
"\n",
"// Allow by default",
"return",
"true",
"\n",
"}"
] | // labelIsAllowed return true if a should be included in metric
// the caller should lock m.filterLock while calling this method | [
"labelIsAllowed",
"return",
"true",
"if",
"a",
"should",
"be",
"included",
"in",
"metric",
"the",
"caller",
"should",
"lock",
"m",
".",
"filterLock",
"while",
"calling",
"this",
"method"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/metrics.go#L177-L192 |
151,258 | armon/go-metrics | metrics.go | filterLabels | func (m *Metrics) filterLabels(labels []Label) []Label {
if labels == nil {
return nil
}
toReturn := []Label{}
for _, label := range labels {
if m.labelIsAllowed(&label) {
toReturn = append(toReturn, label)
}
}
return toReturn
} | go | func (m *Metrics) filterLabels(labels []Label) []Label {
if labels == nil {
return nil
}
toReturn := []Label{}
for _, label := range labels {
if m.labelIsAllowed(&label) {
toReturn = append(toReturn, label)
}
}
return toReturn
} | [
"func",
"(",
"m",
"*",
"Metrics",
")",
"filterLabels",
"(",
"labels",
"[",
"]",
"Label",
")",
"[",
"]",
"Label",
"{",
"if",
"labels",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"toReturn",
":=",
"[",
"]",
"Label",
"{",
"}",
"\n",
"for",
"_",
",",
"label",
":=",
"range",
"labels",
"{",
"if",
"m",
".",
"labelIsAllowed",
"(",
"&",
"label",
")",
"{",
"toReturn",
"=",
"append",
"(",
"toReturn",
",",
"label",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"toReturn",
"\n",
"}"
] | // filterLabels return only allowed labels
// the caller should lock m.filterLock while calling this method | [
"filterLabels",
"return",
"only",
"allowed",
"labels",
"the",
"caller",
"should",
"lock",
"m",
".",
"filterLock",
"while",
"calling",
"this",
"method"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/metrics.go#L196-L207 |
151,259 | armon/go-metrics | metrics.go | allowMetric | func (m *Metrics) allowMetric(key []string, labels []Label) (bool, []Label) {
m.filterLock.RLock()
defer m.filterLock.RUnlock()
if m.filter == nil || m.filter.Len() == 0 {
return m.Config.FilterDefault, m.filterLabels(labels)
}
_, allowed, ok := m.filter.Root().LongestPrefix([]byte(strings.Join(key, ".")))
if !ok {
return m.Config.FilterDefault, m.filterLabels(labels)
}
return allowed.(bool), m.filterLabels(labels)
} | go | func (m *Metrics) allowMetric(key []string, labels []Label) (bool, []Label) {
m.filterLock.RLock()
defer m.filterLock.RUnlock()
if m.filter == nil || m.filter.Len() == 0 {
return m.Config.FilterDefault, m.filterLabels(labels)
}
_, allowed, ok := m.filter.Root().LongestPrefix([]byte(strings.Join(key, ".")))
if !ok {
return m.Config.FilterDefault, m.filterLabels(labels)
}
return allowed.(bool), m.filterLabels(labels)
} | [
"func",
"(",
"m",
"*",
"Metrics",
")",
"allowMetric",
"(",
"key",
"[",
"]",
"string",
",",
"labels",
"[",
"]",
"Label",
")",
"(",
"bool",
",",
"[",
"]",
"Label",
")",
"{",
"m",
".",
"filterLock",
".",
"RLock",
"(",
")",
"\n",
"defer",
"m",
".",
"filterLock",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"m",
".",
"filter",
"==",
"nil",
"||",
"m",
".",
"filter",
".",
"Len",
"(",
")",
"==",
"0",
"{",
"return",
"m",
".",
"Config",
".",
"FilterDefault",
",",
"m",
".",
"filterLabels",
"(",
"labels",
")",
"\n",
"}",
"\n\n",
"_",
",",
"allowed",
",",
"ok",
":=",
"m",
".",
"filter",
".",
"Root",
"(",
")",
".",
"LongestPrefix",
"(",
"[",
"]",
"byte",
"(",
"strings",
".",
"Join",
"(",
"key",
",",
"\"",
"\"",
")",
")",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"m",
".",
"Config",
".",
"FilterDefault",
",",
"m",
".",
"filterLabels",
"(",
"labels",
")",
"\n",
"}",
"\n\n",
"return",
"allowed",
".",
"(",
"bool",
")",
",",
"m",
".",
"filterLabels",
"(",
"labels",
")",
"\n",
"}"
] | // Returns whether the metric should be allowed based on configured prefix filters
// Also return the applicable labels | [
"Returns",
"whether",
"the",
"metric",
"should",
"be",
"allowed",
"based",
"on",
"configured",
"prefix",
"filters",
"Also",
"return",
"the",
"applicable",
"labels"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/metrics.go#L211-L225 |
151,260 | armon/go-metrics | metrics.go | emitRuntimeStats | func (m *Metrics) emitRuntimeStats() {
// Export number of Goroutines
numRoutines := runtime.NumGoroutine()
m.SetGauge([]string{"runtime", "num_goroutines"}, float32(numRoutines))
// Export memory stats
var stats runtime.MemStats
runtime.ReadMemStats(&stats)
m.SetGauge([]string{"runtime", "alloc_bytes"}, float32(stats.Alloc))
m.SetGauge([]string{"runtime", "sys_bytes"}, float32(stats.Sys))
m.SetGauge([]string{"runtime", "malloc_count"}, float32(stats.Mallocs))
m.SetGauge([]string{"runtime", "free_count"}, float32(stats.Frees))
m.SetGauge([]string{"runtime", "heap_objects"}, float32(stats.HeapObjects))
m.SetGauge([]string{"runtime", "total_gc_pause_ns"}, float32(stats.PauseTotalNs))
m.SetGauge([]string{"runtime", "total_gc_runs"}, float32(stats.NumGC))
// Export info about the last few GC runs
num := stats.NumGC
// Handle wrap around
if num < m.lastNumGC {
m.lastNumGC = 0
}
// Ensure we don't scan more than 256
if num-m.lastNumGC >= 256 {
m.lastNumGC = num - 255
}
for i := m.lastNumGC; i < num; i++ {
pause := stats.PauseNs[i%256]
m.AddSample([]string{"runtime", "gc_pause_ns"}, float32(pause))
}
m.lastNumGC = num
} | go | func (m *Metrics) emitRuntimeStats() {
// Export number of Goroutines
numRoutines := runtime.NumGoroutine()
m.SetGauge([]string{"runtime", "num_goroutines"}, float32(numRoutines))
// Export memory stats
var stats runtime.MemStats
runtime.ReadMemStats(&stats)
m.SetGauge([]string{"runtime", "alloc_bytes"}, float32(stats.Alloc))
m.SetGauge([]string{"runtime", "sys_bytes"}, float32(stats.Sys))
m.SetGauge([]string{"runtime", "malloc_count"}, float32(stats.Mallocs))
m.SetGauge([]string{"runtime", "free_count"}, float32(stats.Frees))
m.SetGauge([]string{"runtime", "heap_objects"}, float32(stats.HeapObjects))
m.SetGauge([]string{"runtime", "total_gc_pause_ns"}, float32(stats.PauseTotalNs))
m.SetGauge([]string{"runtime", "total_gc_runs"}, float32(stats.NumGC))
// Export info about the last few GC runs
num := stats.NumGC
// Handle wrap around
if num < m.lastNumGC {
m.lastNumGC = 0
}
// Ensure we don't scan more than 256
if num-m.lastNumGC >= 256 {
m.lastNumGC = num - 255
}
for i := m.lastNumGC; i < num; i++ {
pause := stats.PauseNs[i%256]
m.AddSample([]string{"runtime", "gc_pause_ns"}, float32(pause))
}
m.lastNumGC = num
} | [
"func",
"(",
"m",
"*",
"Metrics",
")",
"emitRuntimeStats",
"(",
")",
"{",
"// Export number of Goroutines",
"numRoutines",
":=",
"runtime",
".",
"NumGoroutine",
"(",
")",
"\n",
"m",
".",
"SetGauge",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"float32",
"(",
"numRoutines",
")",
")",
"\n\n",
"// Export memory stats",
"var",
"stats",
"runtime",
".",
"MemStats",
"\n",
"runtime",
".",
"ReadMemStats",
"(",
"&",
"stats",
")",
"\n",
"m",
".",
"SetGauge",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"float32",
"(",
"stats",
".",
"Alloc",
")",
")",
"\n",
"m",
".",
"SetGauge",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"float32",
"(",
"stats",
".",
"Sys",
")",
")",
"\n",
"m",
".",
"SetGauge",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"float32",
"(",
"stats",
".",
"Mallocs",
")",
")",
"\n",
"m",
".",
"SetGauge",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"float32",
"(",
"stats",
".",
"Frees",
")",
")",
"\n",
"m",
".",
"SetGauge",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"float32",
"(",
"stats",
".",
"HeapObjects",
")",
")",
"\n",
"m",
".",
"SetGauge",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"float32",
"(",
"stats",
".",
"PauseTotalNs",
")",
")",
"\n",
"m",
".",
"SetGauge",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"float32",
"(",
"stats",
".",
"NumGC",
")",
")",
"\n\n",
"// Export info about the last few GC runs",
"num",
":=",
"stats",
".",
"NumGC",
"\n\n",
"// Handle wrap around",
"if",
"num",
"<",
"m",
".",
"lastNumGC",
"{",
"m",
".",
"lastNumGC",
"=",
"0",
"\n",
"}",
"\n\n",
"// Ensure we don't scan more than 256",
"if",
"num",
"-",
"m",
".",
"lastNumGC",
">=",
"256",
"{",
"m",
".",
"lastNumGC",
"=",
"num",
"-",
"255",
"\n",
"}",
"\n\n",
"for",
"i",
":=",
"m",
".",
"lastNumGC",
";",
"i",
"<",
"num",
";",
"i",
"++",
"{",
"pause",
":=",
"stats",
".",
"PauseNs",
"[",
"i",
"%",
"256",
"]",
"\n",
"m",
".",
"AddSample",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"float32",
"(",
"pause",
")",
")",
"\n",
"}",
"\n",
"m",
".",
"lastNumGC",
"=",
"num",
"\n",
"}"
] | // Emits various runtime statsitics | [
"Emits",
"various",
"runtime",
"statsitics"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/metrics.go#L236-L270 |
151,261 | armon/go-metrics | metrics.go | insert | func insert(i int, v string, s []string) []string {
s = append(s, "")
copy(s[i+1:], s[i:])
s[i] = v
return s
} | go | func insert(i int, v string, s []string) []string {
s = append(s, "")
copy(s[i+1:], s[i:])
s[i] = v
return s
} | [
"func",
"insert",
"(",
"i",
"int",
",",
"v",
"string",
",",
"s",
"[",
"]",
"string",
")",
"[",
"]",
"string",
"{",
"s",
"=",
"append",
"(",
"s",
",",
"\"",
"\"",
")",
"\n",
"copy",
"(",
"s",
"[",
"i",
"+",
"1",
":",
"]",
",",
"s",
"[",
"i",
":",
"]",
")",
"\n",
"s",
"[",
"i",
"]",
"=",
"v",
"\n",
"return",
"s",
"\n",
"}"
] | // Inserts a string value at an index into the slice | [
"Inserts",
"a",
"string",
"value",
"at",
"an",
"index",
"into",
"the",
"slice"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/metrics.go#L273-L278 |
151,262 | armon/go-metrics | start.go | DefaultConfig | func DefaultConfig(serviceName string) *Config {
c := &Config{
ServiceName: serviceName, // Use client provided service
HostName: "",
EnableHostname: true, // Enable hostname prefix
EnableRuntimeMetrics: true, // Enable runtime profiling
EnableTypePrefix: false, // Disable type prefix
TimerGranularity: time.Millisecond, // Timers are in milliseconds
ProfileInterval: time.Second, // Poll runtime every second
FilterDefault: true, // Don't filter metrics by default
}
// Try to get the hostname
name, _ := os.Hostname()
c.HostName = name
return c
} | go | func DefaultConfig(serviceName string) *Config {
c := &Config{
ServiceName: serviceName, // Use client provided service
HostName: "",
EnableHostname: true, // Enable hostname prefix
EnableRuntimeMetrics: true, // Enable runtime profiling
EnableTypePrefix: false, // Disable type prefix
TimerGranularity: time.Millisecond, // Timers are in milliseconds
ProfileInterval: time.Second, // Poll runtime every second
FilterDefault: true, // Don't filter metrics by default
}
// Try to get the hostname
name, _ := os.Hostname()
c.HostName = name
return c
} | [
"func",
"DefaultConfig",
"(",
"serviceName",
"string",
")",
"*",
"Config",
"{",
"c",
":=",
"&",
"Config",
"{",
"ServiceName",
":",
"serviceName",
",",
"// Use client provided service",
"HostName",
":",
"\"",
"\"",
",",
"EnableHostname",
":",
"true",
",",
"// Enable hostname prefix",
"EnableRuntimeMetrics",
":",
"true",
",",
"// Enable runtime profiling",
"EnableTypePrefix",
":",
"false",
",",
"// Disable type prefix",
"TimerGranularity",
":",
"time",
".",
"Millisecond",
",",
"// Timers are in milliseconds",
"ProfileInterval",
":",
"time",
".",
"Second",
",",
"// Poll runtime every second",
"FilterDefault",
":",
"true",
",",
"// Don't filter metrics by default",
"}",
"\n\n",
"// Try to get the hostname",
"name",
",",
"_",
":=",
"os",
".",
"Hostname",
"(",
")",
"\n",
"c",
".",
"HostName",
"=",
"name",
"\n",
"return",
"c",
"\n",
"}"
] | // DefaultConfig provides a sane default configuration | [
"DefaultConfig",
"provides",
"a",
"sane",
"default",
"configuration"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/start.go#L52-L68 |
151,263 | armon/go-metrics | start.go | New | func New(conf *Config, sink MetricSink) (*Metrics, error) {
met := &Metrics{}
met.Config = *conf
met.sink = sink
met.UpdateFilterAndLabels(conf.AllowedPrefixes, conf.BlockedPrefixes, conf.AllowedLabels, conf.BlockedLabels)
// Start the runtime collector
if conf.EnableRuntimeMetrics {
go met.collectStats()
}
return met, nil
} | go | func New(conf *Config, sink MetricSink) (*Metrics, error) {
met := &Metrics{}
met.Config = *conf
met.sink = sink
met.UpdateFilterAndLabels(conf.AllowedPrefixes, conf.BlockedPrefixes, conf.AllowedLabels, conf.BlockedLabels)
// Start the runtime collector
if conf.EnableRuntimeMetrics {
go met.collectStats()
}
return met, nil
} | [
"func",
"New",
"(",
"conf",
"*",
"Config",
",",
"sink",
"MetricSink",
")",
"(",
"*",
"Metrics",
",",
"error",
")",
"{",
"met",
":=",
"&",
"Metrics",
"{",
"}",
"\n",
"met",
".",
"Config",
"=",
"*",
"conf",
"\n",
"met",
".",
"sink",
"=",
"sink",
"\n",
"met",
".",
"UpdateFilterAndLabels",
"(",
"conf",
".",
"AllowedPrefixes",
",",
"conf",
".",
"BlockedPrefixes",
",",
"conf",
".",
"AllowedLabels",
",",
"conf",
".",
"BlockedLabels",
")",
"\n\n",
"// Start the runtime collector",
"if",
"conf",
".",
"EnableRuntimeMetrics",
"{",
"go",
"met",
".",
"collectStats",
"(",
")",
"\n",
"}",
"\n",
"return",
"met",
",",
"nil",
"\n",
"}"
] | // New is used to create a new instance of Metrics | [
"New",
"is",
"used",
"to",
"create",
"a",
"new",
"instance",
"of",
"Metrics"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/start.go#L71-L82 |
151,264 | armon/go-metrics | start.go | NewGlobal | func NewGlobal(conf *Config, sink MetricSink) (*Metrics, error) {
metrics, err := New(conf, sink)
if err == nil {
globalMetrics.Store(metrics)
}
return metrics, err
} | go | func NewGlobal(conf *Config, sink MetricSink) (*Metrics, error) {
metrics, err := New(conf, sink)
if err == nil {
globalMetrics.Store(metrics)
}
return metrics, err
} | [
"func",
"NewGlobal",
"(",
"conf",
"*",
"Config",
",",
"sink",
"MetricSink",
")",
"(",
"*",
"Metrics",
",",
"error",
")",
"{",
"metrics",
",",
"err",
":=",
"New",
"(",
"conf",
",",
"sink",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"globalMetrics",
".",
"Store",
"(",
"metrics",
")",
"\n",
"}",
"\n",
"return",
"metrics",
",",
"err",
"\n",
"}"
] | // NewGlobal is the same as New, but it assigns the metrics object to be
// used globally as well as returning it. | [
"NewGlobal",
"is",
"the",
"same",
"as",
"New",
"but",
"it",
"assigns",
"the",
"metrics",
"object",
"to",
"be",
"used",
"globally",
"as",
"well",
"as",
"returning",
"it",
"."
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/start.go#L86-L92 |
151,265 | armon/go-metrics | start.go | SetGauge | func SetGauge(key []string, val float32) {
globalMetrics.Load().(*Metrics).SetGauge(key, val)
} | go | func SetGauge(key []string, val float32) {
globalMetrics.Load().(*Metrics).SetGauge(key, val)
} | [
"func",
"SetGauge",
"(",
"key",
"[",
"]",
"string",
",",
"val",
"float32",
")",
"{",
"globalMetrics",
".",
"Load",
"(",
")",
".",
"(",
"*",
"Metrics",
")",
".",
"SetGauge",
"(",
"key",
",",
"val",
")",
"\n",
"}"
] | // Proxy all the methods to the globalMetrics instance | [
"Proxy",
"all",
"the",
"methods",
"to",
"the",
"globalMetrics",
"instance"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/start.go#L95-L97 |
151,266 | armon/go-metrics | statsd.go | NewStatsdSink | func NewStatsdSink(addr string) (*StatsdSink, error) {
s := &StatsdSink{
addr: addr,
metricQueue: make(chan string, 4096),
}
go s.flushMetrics()
return s, nil
} | go | func NewStatsdSink(addr string) (*StatsdSink, error) {
s := &StatsdSink{
addr: addr,
metricQueue: make(chan string, 4096),
}
go s.flushMetrics()
return s, nil
} | [
"func",
"NewStatsdSink",
"(",
"addr",
"string",
")",
"(",
"*",
"StatsdSink",
",",
"error",
")",
"{",
"s",
":=",
"&",
"StatsdSink",
"{",
"addr",
":",
"addr",
",",
"metricQueue",
":",
"make",
"(",
"chan",
"string",
",",
"4096",
")",
",",
"}",
"\n",
"go",
"s",
".",
"flushMetrics",
"(",
")",
"\n",
"return",
"s",
",",
"nil",
"\n",
"}"
] | // NewStatsdSink is used to create a new StatsdSink | [
"NewStatsdSink",
"is",
"used",
"to",
"create",
"a",
"new",
"StatsdSink"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/statsd.go#L34-L41 |
151,267 | armon/go-metrics | prometheus/prometheus.go | NewPrometheusSinkFrom | func NewPrometheusSinkFrom(opts PrometheusOpts) (*PrometheusSink, error) {
sink := &PrometheusSink{
gauges: make(map[string]prometheus.Gauge),
summaries: make(map[string]prometheus.Summary),
counters: make(map[string]prometheus.Counter),
updates: make(map[string]time.Time),
expiration: opts.Expiration,
}
return sink, prometheus.Register(sink)
} | go | func NewPrometheusSinkFrom(opts PrometheusOpts) (*PrometheusSink, error) {
sink := &PrometheusSink{
gauges: make(map[string]prometheus.Gauge),
summaries: make(map[string]prometheus.Summary),
counters: make(map[string]prometheus.Counter),
updates: make(map[string]time.Time),
expiration: opts.Expiration,
}
return sink, prometheus.Register(sink)
} | [
"func",
"NewPrometheusSinkFrom",
"(",
"opts",
"PrometheusOpts",
")",
"(",
"*",
"PrometheusSink",
",",
"error",
")",
"{",
"sink",
":=",
"&",
"PrometheusSink",
"{",
"gauges",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"prometheus",
".",
"Gauge",
")",
",",
"summaries",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"prometheus",
".",
"Summary",
")",
",",
"counters",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"prometheus",
".",
"Counter",
")",
",",
"updates",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"time",
".",
"Time",
")",
",",
"expiration",
":",
"opts",
".",
"Expiration",
",",
"}",
"\n\n",
"return",
"sink",
",",
"prometheus",
".",
"Register",
"(",
"sink",
")",
"\n",
"}"
] | // NewPrometheusSinkFrom creates a new PrometheusSink using the passed options. | [
"NewPrometheusSinkFrom",
"creates",
"a",
"new",
"PrometheusSink",
"using",
"the",
"passed",
"options",
"."
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/prometheus/prometheus.go#L47-L57 |
151,268 | armon/go-metrics | prometheus/prometheus.go | Describe | func (p *PrometheusSink) Describe(c chan<- *prometheus.Desc) {
// We must emit some description otherwise an error is returned. This
// description isn't shown to the user!
prometheus.NewGauge(prometheus.GaugeOpts{Name: "Dummy", Help: "Dummy"}).Describe(c)
} | go | func (p *PrometheusSink) Describe(c chan<- *prometheus.Desc) {
// We must emit some description otherwise an error is returned. This
// description isn't shown to the user!
prometheus.NewGauge(prometheus.GaugeOpts{Name: "Dummy", Help: "Dummy"}).Describe(c)
} | [
"func",
"(",
"p",
"*",
"PrometheusSink",
")",
"Describe",
"(",
"c",
"chan",
"<-",
"*",
"prometheus",
".",
"Desc",
")",
"{",
"// We must emit some description otherwise an error is returned. This",
"// description isn't shown to the user!",
"prometheus",
".",
"NewGauge",
"(",
"prometheus",
".",
"GaugeOpts",
"{",
"Name",
":",
"\"",
"\"",
",",
"Help",
":",
"\"",
"\"",
"}",
")",
".",
"Describe",
"(",
"c",
")",
"\n",
"}"
] | // Describe is needed to meet the Collector interface. | [
"Describe",
"is",
"needed",
"to",
"meet",
"the",
"Collector",
"interface",
"."
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/prometheus/prometheus.go#L60-L64 |
151,269 | armon/go-metrics | prometheus/prometheus.go | Collect | func (p *PrometheusSink) Collect(c chan<- prometheus.Metric) {
p.mu.Lock()
defer p.mu.Unlock()
expire := p.expiration != 0
now := time.Now()
for k, v := range p.gauges {
last := p.updates[k]
if expire && last.Add(p.expiration).Before(now) {
delete(p.updates, k)
delete(p.gauges, k)
} else {
v.Collect(c)
}
}
for k, v := range p.summaries {
last := p.updates[k]
if expire && last.Add(p.expiration).Before(now) {
delete(p.updates, k)
delete(p.summaries, k)
} else {
v.Collect(c)
}
}
for k, v := range p.counters {
last := p.updates[k]
if expire && last.Add(p.expiration).Before(now) {
delete(p.updates, k)
delete(p.counters, k)
} else {
v.Collect(c)
}
}
} | go | func (p *PrometheusSink) Collect(c chan<- prometheus.Metric) {
p.mu.Lock()
defer p.mu.Unlock()
expire := p.expiration != 0
now := time.Now()
for k, v := range p.gauges {
last := p.updates[k]
if expire && last.Add(p.expiration).Before(now) {
delete(p.updates, k)
delete(p.gauges, k)
} else {
v.Collect(c)
}
}
for k, v := range p.summaries {
last := p.updates[k]
if expire && last.Add(p.expiration).Before(now) {
delete(p.updates, k)
delete(p.summaries, k)
} else {
v.Collect(c)
}
}
for k, v := range p.counters {
last := p.updates[k]
if expire && last.Add(p.expiration).Before(now) {
delete(p.updates, k)
delete(p.counters, k)
} else {
v.Collect(c)
}
}
} | [
"func",
"(",
"p",
"*",
"PrometheusSink",
")",
"Collect",
"(",
"c",
"chan",
"<-",
"prometheus",
".",
"Metric",
")",
"{",
"p",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"expire",
":=",
"p",
".",
"expiration",
"!=",
"0",
"\n",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"p",
".",
"gauges",
"{",
"last",
":=",
"p",
".",
"updates",
"[",
"k",
"]",
"\n",
"if",
"expire",
"&&",
"last",
".",
"Add",
"(",
"p",
".",
"expiration",
")",
".",
"Before",
"(",
"now",
")",
"{",
"delete",
"(",
"p",
".",
"updates",
",",
"k",
")",
"\n",
"delete",
"(",
"p",
".",
"gauges",
",",
"k",
")",
"\n",
"}",
"else",
"{",
"v",
".",
"Collect",
"(",
"c",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"p",
".",
"summaries",
"{",
"last",
":=",
"p",
".",
"updates",
"[",
"k",
"]",
"\n",
"if",
"expire",
"&&",
"last",
".",
"Add",
"(",
"p",
".",
"expiration",
")",
".",
"Before",
"(",
"now",
")",
"{",
"delete",
"(",
"p",
".",
"updates",
",",
"k",
")",
"\n",
"delete",
"(",
"p",
".",
"summaries",
",",
"k",
")",
"\n",
"}",
"else",
"{",
"v",
".",
"Collect",
"(",
"c",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"p",
".",
"counters",
"{",
"last",
":=",
"p",
".",
"updates",
"[",
"k",
"]",
"\n",
"if",
"expire",
"&&",
"last",
".",
"Add",
"(",
"p",
".",
"expiration",
")",
".",
"Before",
"(",
"now",
")",
"{",
"delete",
"(",
"p",
".",
"updates",
",",
"k",
")",
"\n",
"delete",
"(",
"p",
".",
"counters",
",",
"k",
")",
"\n",
"}",
"else",
"{",
"v",
".",
"Collect",
"(",
"c",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Collect meets the collection interface and allows us to enforce our expiration
// logic to clean up ephemeral metrics if their value haven't been set for a
// duration exceeding our allowed expiration time. | [
"Collect",
"meets",
"the",
"collection",
"interface",
"and",
"allows",
"us",
"to",
"enforce",
"our",
"expiration",
"logic",
"to",
"clean",
"up",
"ephemeral",
"metrics",
"if",
"their",
"value",
"haven",
"t",
"been",
"set",
"for",
"a",
"duration",
"exceeding",
"our",
"allowed",
"expiration",
"time",
"."
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/prometheus/prometheus.go#L69-L102 |
151,270 | armon/go-metrics | inmem.go | NewIntervalMetrics | func NewIntervalMetrics(intv time.Time) *IntervalMetrics {
return &IntervalMetrics{
Interval: intv,
Gauges: make(map[string]GaugeValue),
Points: make(map[string][]float32),
Counters: make(map[string]SampledValue),
Samples: make(map[string]SampledValue),
}
} | go | func NewIntervalMetrics(intv time.Time) *IntervalMetrics {
return &IntervalMetrics{
Interval: intv,
Gauges: make(map[string]GaugeValue),
Points: make(map[string][]float32),
Counters: make(map[string]SampledValue),
Samples: make(map[string]SampledValue),
}
} | [
"func",
"NewIntervalMetrics",
"(",
"intv",
"time",
".",
"Time",
")",
"*",
"IntervalMetrics",
"{",
"return",
"&",
"IntervalMetrics",
"{",
"Interval",
":",
"intv",
",",
"Gauges",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"GaugeValue",
")",
",",
"Points",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"float32",
")",
",",
"Counters",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"SampledValue",
")",
",",
"Samples",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"SampledValue",
")",
",",
"}",
"\n",
"}"
] | // NewIntervalMetrics creates a new IntervalMetrics for a given interval | [
"NewIntervalMetrics",
"creates",
"a",
"new",
"IntervalMetrics",
"for",
"a",
"given",
"interval"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/inmem.go#L59-L67 |
151,271 | armon/go-metrics | inmem.go | Stddev | func (a *AggregateSample) Stddev() float64 {
num := (float64(a.Count) * a.SumSq) - math.Pow(a.Sum, 2)
div := float64(a.Count * (a.Count - 1))
if div == 0 {
return 0
}
return math.Sqrt(num / div)
} | go | func (a *AggregateSample) Stddev() float64 {
num := (float64(a.Count) * a.SumSq) - math.Pow(a.Sum, 2)
div := float64(a.Count * (a.Count - 1))
if div == 0 {
return 0
}
return math.Sqrt(num / div)
} | [
"func",
"(",
"a",
"*",
"AggregateSample",
")",
"Stddev",
"(",
")",
"float64",
"{",
"num",
":=",
"(",
"float64",
"(",
"a",
".",
"Count",
")",
"*",
"a",
".",
"SumSq",
")",
"-",
"math",
".",
"Pow",
"(",
"a",
".",
"Sum",
",",
"2",
")",
"\n",
"div",
":=",
"float64",
"(",
"a",
".",
"Count",
"*",
"(",
"a",
".",
"Count",
"-",
"1",
")",
")",
"\n",
"if",
"div",
"==",
"0",
"{",
"return",
"0",
"\n",
"}",
"\n",
"return",
"math",
".",
"Sqrt",
"(",
"num",
"/",
"div",
")",
"\n",
"}"
] | // Computes a Stddev of the values | [
"Computes",
"a",
"Stddev",
"of",
"the",
"values"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/inmem.go#L82-L89 |
151,272 | armon/go-metrics | inmem.go | Mean | func (a *AggregateSample) Mean() float64 {
if a.Count == 0 {
return 0
}
return a.Sum / float64(a.Count)
} | go | func (a *AggregateSample) Mean() float64 {
if a.Count == 0 {
return 0
}
return a.Sum / float64(a.Count)
} | [
"func",
"(",
"a",
"*",
"AggregateSample",
")",
"Mean",
"(",
")",
"float64",
"{",
"if",
"a",
".",
"Count",
"==",
"0",
"{",
"return",
"0",
"\n",
"}",
"\n",
"return",
"a",
".",
"Sum",
"/",
"float64",
"(",
"a",
".",
"Count",
")",
"\n",
"}"
] | // Computes a mean of the values | [
"Computes",
"a",
"mean",
"of",
"the",
"values"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/inmem.go#L92-L97 |
151,273 | armon/go-metrics | inmem.go | Ingest | func (a *AggregateSample) Ingest(v float64, rateDenom float64) {
a.Count++
a.Sum += v
a.SumSq += (v * v)
if v < a.Min || a.Count == 1 {
a.Min = v
}
if v > a.Max || a.Count == 1 {
a.Max = v
}
a.Rate = float64(a.Sum) / rateDenom
a.LastUpdated = time.Now()
} | go | func (a *AggregateSample) Ingest(v float64, rateDenom float64) {
a.Count++
a.Sum += v
a.SumSq += (v * v)
if v < a.Min || a.Count == 1 {
a.Min = v
}
if v > a.Max || a.Count == 1 {
a.Max = v
}
a.Rate = float64(a.Sum) / rateDenom
a.LastUpdated = time.Now()
} | [
"func",
"(",
"a",
"*",
"AggregateSample",
")",
"Ingest",
"(",
"v",
"float64",
",",
"rateDenom",
"float64",
")",
"{",
"a",
".",
"Count",
"++",
"\n",
"a",
".",
"Sum",
"+=",
"v",
"\n",
"a",
".",
"SumSq",
"+=",
"(",
"v",
"*",
"v",
")",
"\n",
"if",
"v",
"<",
"a",
".",
"Min",
"||",
"a",
".",
"Count",
"==",
"1",
"{",
"a",
".",
"Min",
"=",
"v",
"\n",
"}",
"\n",
"if",
"v",
">",
"a",
".",
"Max",
"||",
"a",
".",
"Count",
"==",
"1",
"{",
"a",
".",
"Max",
"=",
"v",
"\n",
"}",
"\n",
"a",
".",
"Rate",
"=",
"float64",
"(",
"a",
".",
"Sum",
")",
"/",
"rateDenom",
"\n",
"a",
".",
"LastUpdated",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"}"
] | // Ingest is used to update a sample | [
"Ingest",
"is",
"used",
"to",
"update",
"a",
"sample"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/inmem.go#L100-L112 |
151,274 | armon/go-metrics | inmem.go | NewInmemSink | func NewInmemSink(interval, retain time.Duration) *InmemSink {
rateTimeUnit := time.Second
i := &InmemSink{
interval: interval,
retain: retain,
maxIntervals: int(retain / interval),
rateDenom: float64(interval.Nanoseconds()) / float64(rateTimeUnit.Nanoseconds()),
}
i.intervals = make([]*IntervalMetrics, 0, i.maxIntervals)
return i
} | go | func NewInmemSink(interval, retain time.Duration) *InmemSink {
rateTimeUnit := time.Second
i := &InmemSink{
interval: interval,
retain: retain,
maxIntervals: int(retain / interval),
rateDenom: float64(interval.Nanoseconds()) / float64(rateTimeUnit.Nanoseconds()),
}
i.intervals = make([]*IntervalMetrics, 0, i.maxIntervals)
return i
} | [
"func",
"NewInmemSink",
"(",
"interval",
",",
"retain",
"time",
".",
"Duration",
")",
"*",
"InmemSink",
"{",
"rateTimeUnit",
":=",
"time",
".",
"Second",
"\n",
"i",
":=",
"&",
"InmemSink",
"{",
"interval",
":",
"interval",
",",
"retain",
":",
"retain",
",",
"maxIntervals",
":",
"int",
"(",
"retain",
"/",
"interval",
")",
",",
"rateDenom",
":",
"float64",
"(",
"interval",
".",
"Nanoseconds",
"(",
")",
")",
"/",
"float64",
"(",
"rateTimeUnit",
".",
"Nanoseconds",
"(",
")",
")",
",",
"}",
"\n",
"i",
".",
"intervals",
"=",
"make",
"(",
"[",
"]",
"*",
"IntervalMetrics",
",",
"0",
",",
"i",
".",
"maxIntervals",
")",
"\n",
"return",
"i",
"\n",
"}"
] | // NewInmemSink is used to construct a new in-memory sink.
// Uses an aggregation interval and maximum retention period. | [
"NewInmemSink",
"is",
"used",
"to",
"construct",
"a",
"new",
"in",
"-",
"memory",
"sink",
".",
"Uses",
"an",
"aggregation",
"interval",
"and",
"maximum",
"retention",
"period",
"."
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/inmem.go#L145-L155 |
151,275 | armon/go-metrics | inmem.go | Data | func (i *InmemSink) Data() []*IntervalMetrics {
// Get the current interval, forces creation
i.getInterval()
i.intervalLock.RLock()
defer i.intervalLock.RUnlock()
n := len(i.intervals)
intervals := make([]*IntervalMetrics, n)
copy(intervals[:n-1], i.intervals[:n-1])
current := i.intervals[n-1]
// make its own copy for current interval
intervals[n-1] = &IntervalMetrics{}
copyCurrent := intervals[n-1]
current.RLock()
*copyCurrent = *current
copyCurrent.Gauges = make(map[string]GaugeValue, len(current.Gauges))
for k, v := range current.Gauges {
copyCurrent.Gauges[k] = v
}
// saved values will be not change, just copy its link
copyCurrent.Points = make(map[string][]float32, len(current.Points))
for k, v := range current.Points {
copyCurrent.Points[k] = v
}
copyCurrent.Counters = make(map[string]SampledValue, len(current.Counters))
for k, v := range current.Counters {
copyCurrent.Counters[k] = v.deepCopy()
}
copyCurrent.Samples = make(map[string]SampledValue, len(current.Samples))
for k, v := range current.Samples {
copyCurrent.Samples[k] = v.deepCopy()
}
current.RUnlock()
return intervals
} | go | func (i *InmemSink) Data() []*IntervalMetrics {
// Get the current interval, forces creation
i.getInterval()
i.intervalLock.RLock()
defer i.intervalLock.RUnlock()
n := len(i.intervals)
intervals := make([]*IntervalMetrics, n)
copy(intervals[:n-1], i.intervals[:n-1])
current := i.intervals[n-1]
// make its own copy for current interval
intervals[n-1] = &IntervalMetrics{}
copyCurrent := intervals[n-1]
current.RLock()
*copyCurrent = *current
copyCurrent.Gauges = make(map[string]GaugeValue, len(current.Gauges))
for k, v := range current.Gauges {
copyCurrent.Gauges[k] = v
}
// saved values will be not change, just copy its link
copyCurrent.Points = make(map[string][]float32, len(current.Points))
for k, v := range current.Points {
copyCurrent.Points[k] = v
}
copyCurrent.Counters = make(map[string]SampledValue, len(current.Counters))
for k, v := range current.Counters {
copyCurrent.Counters[k] = v.deepCopy()
}
copyCurrent.Samples = make(map[string]SampledValue, len(current.Samples))
for k, v := range current.Samples {
copyCurrent.Samples[k] = v.deepCopy()
}
current.RUnlock()
return intervals
} | [
"func",
"(",
"i",
"*",
"InmemSink",
")",
"Data",
"(",
")",
"[",
"]",
"*",
"IntervalMetrics",
"{",
"// Get the current interval, forces creation",
"i",
".",
"getInterval",
"(",
")",
"\n\n",
"i",
".",
"intervalLock",
".",
"RLock",
"(",
")",
"\n",
"defer",
"i",
".",
"intervalLock",
".",
"RUnlock",
"(",
")",
"\n\n",
"n",
":=",
"len",
"(",
"i",
".",
"intervals",
")",
"\n",
"intervals",
":=",
"make",
"(",
"[",
"]",
"*",
"IntervalMetrics",
",",
"n",
")",
"\n\n",
"copy",
"(",
"intervals",
"[",
":",
"n",
"-",
"1",
"]",
",",
"i",
".",
"intervals",
"[",
":",
"n",
"-",
"1",
"]",
")",
"\n",
"current",
":=",
"i",
".",
"intervals",
"[",
"n",
"-",
"1",
"]",
"\n\n",
"// make its own copy for current interval",
"intervals",
"[",
"n",
"-",
"1",
"]",
"=",
"&",
"IntervalMetrics",
"{",
"}",
"\n",
"copyCurrent",
":=",
"intervals",
"[",
"n",
"-",
"1",
"]",
"\n",
"current",
".",
"RLock",
"(",
")",
"\n",
"*",
"copyCurrent",
"=",
"*",
"current",
"\n\n",
"copyCurrent",
".",
"Gauges",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"GaugeValue",
",",
"len",
"(",
"current",
".",
"Gauges",
")",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"current",
".",
"Gauges",
"{",
"copyCurrent",
".",
"Gauges",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"// saved values will be not change, just copy its link",
"copyCurrent",
".",
"Points",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"float32",
",",
"len",
"(",
"current",
".",
"Points",
")",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"current",
".",
"Points",
"{",
"copyCurrent",
".",
"Points",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"copyCurrent",
".",
"Counters",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"SampledValue",
",",
"len",
"(",
"current",
".",
"Counters",
")",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"current",
".",
"Counters",
"{",
"copyCurrent",
".",
"Counters",
"[",
"k",
"]",
"=",
"v",
".",
"deepCopy",
"(",
")",
"\n",
"}",
"\n",
"copyCurrent",
".",
"Samples",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"SampledValue",
",",
"len",
"(",
"current",
".",
"Samples",
")",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"current",
".",
"Samples",
"{",
"copyCurrent",
".",
"Samples",
"[",
"k",
"]",
"=",
"v",
".",
"deepCopy",
"(",
")",
"\n",
"}",
"\n",
"current",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"intervals",
"\n",
"}"
] | // Data is used to retrieve all the aggregated metrics
// Intervals may be in use, and a read lock should be acquired | [
"Data",
"is",
"used",
"to",
"retrieve",
"all",
"the",
"aggregated",
"metrics",
"Intervals",
"may",
"be",
"in",
"use",
"and",
"a",
"read",
"lock",
"should",
"be",
"acquired"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/inmem.go#L228-L267 |
151,276 | armon/go-metrics | inmem.go | getInterval | func (i *InmemSink) getInterval() *IntervalMetrics {
intv := time.Now().Truncate(i.interval)
if m := i.getExistingInterval(intv); m != nil {
return m
}
return i.createInterval(intv)
} | go | func (i *InmemSink) getInterval() *IntervalMetrics {
intv := time.Now().Truncate(i.interval)
if m := i.getExistingInterval(intv); m != nil {
return m
}
return i.createInterval(intv)
} | [
"func",
"(",
"i",
"*",
"InmemSink",
")",
"getInterval",
"(",
")",
"*",
"IntervalMetrics",
"{",
"intv",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Truncate",
"(",
"i",
".",
"interval",
")",
"\n",
"if",
"m",
":=",
"i",
".",
"getExistingInterval",
"(",
"intv",
")",
";",
"m",
"!=",
"nil",
"{",
"return",
"m",
"\n",
"}",
"\n",
"return",
"i",
".",
"createInterval",
"(",
"intv",
")",
"\n",
"}"
] | // getInterval returns the current interval to write to | [
"getInterval",
"returns",
"the",
"current",
"interval",
"to",
"write",
"to"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/inmem.go#L304-L310 |
151,277 | armon/go-metrics | inmem_endpoint.go | deepCopy | func (source *SampledValue) deepCopy() SampledValue {
dest := *source
if source.AggregateSample != nil {
dest.AggregateSample = &AggregateSample{}
*dest.AggregateSample = *source.AggregateSample
}
return dest
} | go | func (source *SampledValue) deepCopy() SampledValue {
dest := *source
if source.AggregateSample != nil {
dest.AggregateSample = &AggregateSample{}
*dest.AggregateSample = *source.AggregateSample
}
return dest
} | [
"func",
"(",
"source",
"*",
"SampledValue",
")",
"deepCopy",
"(",
")",
"SampledValue",
"{",
"dest",
":=",
"*",
"source",
"\n",
"if",
"source",
".",
"AggregateSample",
"!=",
"nil",
"{",
"dest",
".",
"AggregateSample",
"=",
"&",
"AggregateSample",
"{",
"}",
"\n",
"*",
"dest",
".",
"AggregateSample",
"=",
"*",
"source",
".",
"AggregateSample",
"\n",
"}",
"\n",
"return",
"dest",
"\n",
"}"
] | // deepCopy allocates a new instance of AggregateSample | [
"deepCopy",
"allocates",
"a",
"new",
"instance",
"of",
"AggregateSample"
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/inmem_endpoint.go#L45-L52 |
151,278 | armon/go-metrics | inmem_endpoint.go | DisplayMetrics | func (i *InmemSink) DisplayMetrics(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
data := i.Data()
var interval *IntervalMetrics
n := len(data)
switch {
case n == 0:
return nil, fmt.Errorf("no metric intervals have been initialized yet")
case n == 1:
// Show the current interval if it's all we have
interval = data[0]
default:
// Show the most recent finished interval if we have one
interval = data[n-2]
}
interval.RLock()
defer interval.RUnlock()
summary := MetricsSummary{
Timestamp: interval.Interval.Round(time.Second).UTC().String(),
Gauges: make([]GaugeValue, 0, len(interval.Gauges)),
Points: make([]PointValue, 0, len(interval.Points)),
}
// Format and sort the output of each metric type, so it gets displayed in a
// deterministic order.
for name, points := range interval.Points {
summary.Points = append(summary.Points, PointValue{name, points})
}
sort.Slice(summary.Points, func(i, j int) bool {
return summary.Points[i].Name < summary.Points[j].Name
})
for hash, value := range interval.Gauges {
value.Hash = hash
value.DisplayLabels = make(map[string]string)
for _, label := range value.Labels {
value.DisplayLabels[label.Name] = label.Value
}
value.Labels = nil
summary.Gauges = append(summary.Gauges, value)
}
sort.Slice(summary.Gauges, func(i, j int) bool {
return summary.Gauges[i].Hash < summary.Gauges[j].Hash
})
summary.Counters = formatSamples(interval.Counters)
summary.Samples = formatSamples(interval.Samples)
return summary, nil
} | go | func (i *InmemSink) DisplayMetrics(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
data := i.Data()
var interval *IntervalMetrics
n := len(data)
switch {
case n == 0:
return nil, fmt.Errorf("no metric intervals have been initialized yet")
case n == 1:
// Show the current interval if it's all we have
interval = data[0]
default:
// Show the most recent finished interval if we have one
interval = data[n-2]
}
interval.RLock()
defer interval.RUnlock()
summary := MetricsSummary{
Timestamp: interval.Interval.Round(time.Second).UTC().String(),
Gauges: make([]GaugeValue, 0, len(interval.Gauges)),
Points: make([]PointValue, 0, len(interval.Points)),
}
// Format and sort the output of each metric type, so it gets displayed in a
// deterministic order.
for name, points := range interval.Points {
summary.Points = append(summary.Points, PointValue{name, points})
}
sort.Slice(summary.Points, func(i, j int) bool {
return summary.Points[i].Name < summary.Points[j].Name
})
for hash, value := range interval.Gauges {
value.Hash = hash
value.DisplayLabels = make(map[string]string)
for _, label := range value.Labels {
value.DisplayLabels[label.Name] = label.Value
}
value.Labels = nil
summary.Gauges = append(summary.Gauges, value)
}
sort.Slice(summary.Gauges, func(i, j int) bool {
return summary.Gauges[i].Hash < summary.Gauges[j].Hash
})
summary.Counters = formatSamples(interval.Counters)
summary.Samples = formatSamples(interval.Samples)
return summary, nil
} | [
"func",
"(",
"i",
"*",
"InmemSink",
")",
"DisplayMetrics",
"(",
"resp",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"data",
":=",
"i",
".",
"Data",
"(",
")",
"\n\n",
"var",
"interval",
"*",
"IntervalMetrics",
"\n",
"n",
":=",
"len",
"(",
"data",
")",
"\n",
"switch",
"{",
"case",
"n",
"==",
"0",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"case",
"n",
"==",
"1",
":",
"// Show the current interval if it's all we have",
"interval",
"=",
"data",
"[",
"0",
"]",
"\n",
"default",
":",
"// Show the most recent finished interval if we have one",
"interval",
"=",
"data",
"[",
"n",
"-",
"2",
"]",
"\n",
"}",
"\n\n",
"interval",
".",
"RLock",
"(",
")",
"\n",
"defer",
"interval",
".",
"RUnlock",
"(",
")",
"\n\n",
"summary",
":=",
"MetricsSummary",
"{",
"Timestamp",
":",
"interval",
".",
"Interval",
".",
"Round",
"(",
"time",
".",
"Second",
")",
".",
"UTC",
"(",
")",
".",
"String",
"(",
")",
",",
"Gauges",
":",
"make",
"(",
"[",
"]",
"GaugeValue",
",",
"0",
",",
"len",
"(",
"interval",
".",
"Gauges",
")",
")",
",",
"Points",
":",
"make",
"(",
"[",
"]",
"PointValue",
",",
"0",
",",
"len",
"(",
"interval",
".",
"Points",
")",
")",
",",
"}",
"\n\n",
"// Format and sort the output of each metric type, so it gets displayed in a",
"// deterministic order.",
"for",
"name",
",",
"points",
":=",
"range",
"interval",
".",
"Points",
"{",
"summary",
".",
"Points",
"=",
"append",
"(",
"summary",
".",
"Points",
",",
"PointValue",
"{",
"name",
",",
"points",
"}",
")",
"\n",
"}",
"\n",
"sort",
".",
"Slice",
"(",
"summary",
".",
"Points",
",",
"func",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"return",
"summary",
".",
"Points",
"[",
"i",
"]",
".",
"Name",
"<",
"summary",
".",
"Points",
"[",
"j",
"]",
".",
"Name",
"\n",
"}",
")",
"\n\n",
"for",
"hash",
",",
"value",
":=",
"range",
"interval",
".",
"Gauges",
"{",
"value",
".",
"Hash",
"=",
"hash",
"\n",
"value",
".",
"DisplayLabels",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"for",
"_",
",",
"label",
":=",
"range",
"value",
".",
"Labels",
"{",
"value",
".",
"DisplayLabels",
"[",
"label",
".",
"Name",
"]",
"=",
"label",
".",
"Value",
"\n",
"}",
"\n",
"value",
".",
"Labels",
"=",
"nil",
"\n\n",
"summary",
".",
"Gauges",
"=",
"append",
"(",
"summary",
".",
"Gauges",
",",
"value",
")",
"\n",
"}",
"\n",
"sort",
".",
"Slice",
"(",
"summary",
".",
"Gauges",
",",
"func",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"return",
"summary",
".",
"Gauges",
"[",
"i",
"]",
".",
"Hash",
"<",
"summary",
".",
"Gauges",
"[",
"j",
"]",
".",
"Hash",
"\n",
"}",
")",
"\n\n",
"summary",
".",
"Counters",
"=",
"formatSamples",
"(",
"interval",
".",
"Counters",
")",
"\n",
"summary",
".",
"Samples",
"=",
"formatSamples",
"(",
"interval",
".",
"Samples",
")",
"\n\n",
"return",
"summary",
",",
"nil",
"\n",
"}"
] | // DisplayMetrics returns a summary of the metrics from the most recent finished interval. | [
"DisplayMetrics",
"returns",
"a",
"summary",
"of",
"the",
"metrics",
"from",
"the",
"most",
"recent",
"finished",
"interval",
"."
] | ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5 | https://github.com/armon/go-metrics/blob/ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5/inmem_endpoint.go#L55-L107 |
151,279 | levigross/grequests | session.go | NewSession | func NewSession(ro *RequestOptions) *Session {
if ro == nil {
ro = &RequestOptions{}
}
ro.UseCookieJar = true
return &Session{RequestOptions: ro, HTTPClient: BuildHTTPClient(*ro)}
} | go | func NewSession(ro *RequestOptions) *Session {
if ro == nil {
ro = &RequestOptions{}
}
ro.UseCookieJar = true
return &Session{RequestOptions: ro, HTTPClient: BuildHTTPClient(*ro)}
} | [
"func",
"NewSession",
"(",
"ro",
"*",
"RequestOptions",
")",
"*",
"Session",
"{",
"if",
"ro",
"==",
"nil",
"{",
"ro",
"=",
"&",
"RequestOptions",
"{",
"}",
"\n",
"}",
"\n\n",
"ro",
".",
"UseCookieJar",
"=",
"true",
"\n\n",
"return",
"&",
"Session",
"{",
"RequestOptions",
":",
"ro",
",",
"HTTPClient",
":",
"BuildHTTPClient",
"(",
"*",
"ro",
")",
"}",
"\n",
"}"
] | // NewSession returns a session struct which enables can be used to maintain establish a persistent state with the
// server
// This function will set UseCookieJar to true as that is the purpose of using the session | [
"NewSession",
"returns",
"a",
"session",
"struct",
"which",
"enables",
"can",
"be",
"used",
"to",
"maintain",
"establish",
"a",
"persistent",
"state",
"with",
"the",
"server",
"This",
"function",
"will",
"set",
"UseCookieJar",
"to",
"true",
"as",
"that",
"is",
"the",
"purpose",
"of",
"using",
"the",
"session"
] | 37c80f76a0dae6ed656cbc830643ba53f45fc79c | https://github.com/levigross/grequests/blob/37c80f76a0dae6ed656cbc830643ba53f45fc79c/session.go#L18-L26 |
151,280 | levigross/grequests | session.go | combineRequestOptions | func (s *Session) combineRequestOptions(ro *RequestOptions) *RequestOptions {
if ro == nil {
ro = &RequestOptions{}
}
if ro.UserAgent == "" && s.RequestOptions.UserAgent != "" {
ro.UserAgent = s.RequestOptions.UserAgent
}
if ro.Host == "" && s.RequestOptions.Host != "" {
ro.Host = s.RequestOptions.Host
}
if ro.Auth == nil && s.RequestOptions.Auth != nil {
ro.Auth = s.RequestOptions.Auth
}
if len(s.RequestOptions.Headers) > 0 || len(ro.Headers) > 0 {
headers := make(map[string]string)
for k, v := range s.RequestOptions.Headers {
headers[k] = v
}
for k, v := range ro.Headers {
headers[k] = v
}
ro.Headers = headers
}
return ro
} | go | func (s *Session) combineRequestOptions(ro *RequestOptions) *RequestOptions {
if ro == nil {
ro = &RequestOptions{}
}
if ro.UserAgent == "" && s.RequestOptions.UserAgent != "" {
ro.UserAgent = s.RequestOptions.UserAgent
}
if ro.Host == "" && s.RequestOptions.Host != "" {
ro.Host = s.RequestOptions.Host
}
if ro.Auth == nil && s.RequestOptions.Auth != nil {
ro.Auth = s.RequestOptions.Auth
}
if len(s.RequestOptions.Headers) > 0 || len(ro.Headers) > 0 {
headers := make(map[string]string)
for k, v := range s.RequestOptions.Headers {
headers[k] = v
}
for k, v := range ro.Headers {
headers[k] = v
}
ro.Headers = headers
}
return ro
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"combineRequestOptions",
"(",
"ro",
"*",
"RequestOptions",
")",
"*",
"RequestOptions",
"{",
"if",
"ro",
"==",
"nil",
"{",
"ro",
"=",
"&",
"RequestOptions",
"{",
"}",
"\n",
"}",
"\n\n",
"if",
"ro",
".",
"UserAgent",
"==",
"\"",
"\"",
"&&",
"s",
".",
"RequestOptions",
".",
"UserAgent",
"!=",
"\"",
"\"",
"{",
"ro",
".",
"UserAgent",
"=",
"s",
".",
"RequestOptions",
".",
"UserAgent",
"\n",
"}",
"\n\n",
"if",
"ro",
".",
"Host",
"==",
"\"",
"\"",
"&&",
"s",
".",
"RequestOptions",
".",
"Host",
"!=",
"\"",
"\"",
"{",
"ro",
".",
"Host",
"=",
"s",
".",
"RequestOptions",
".",
"Host",
"\n",
"}",
"\n\n",
"if",
"ro",
".",
"Auth",
"==",
"nil",
"&&",
"s",
".",
"RequestOptions",
".",
"Auth",
"!=",
"nil",
"{",
"ro",
".",
"Auth",
"=",
"s",
".",
"RequestOptions",
".",
"Auth",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"s",
".",
"RequestOptions",
".",
"Headers",
")",
">",
"0",
"||",
"len",
"(",
"ro",
".",
"Headers",
")",
">",
"0",
"{",
"headers",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"s",
".",
"RequestOptions",
".",
"Headers",
"{",
"headers",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"ro",
".",
"Headers",
"{",
"headers",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"ro",
".",
"Headers",
"=",
"headers",
"\n",
"}",
"\n",
"return",
"ro",
"\n",
"}"
] | // Combine session options and request options
// 1. UserAgent
// 2. Host
// 3. Auth
// 4. Headers | [
"Combine",
"session",
"options",
"and",
"request",
"options",
"1",
".",
"UserAgent",
"2",
".",
"Host",
"3",
".",
"Auth",
"4",
".",
"Headers"
] | 37c80f76a0dae6ed656cbc830643ba53f45fc79c | https://github.com/levigross/grequests/blob/37c80f76a0dae6ed656cbc830643ba53f45fc79c/session.go#L33-L61 |
151,281 | levigross/grequests | request.go | DoRegularRequest | func DoRegularRequest(requestVerb, url string, ro *RequestOptions) (*Response, error) {
return buildResponse(buildRequest(requestVerb, url, ro, nil))
} | go | func DoRegularRequest(requestVerb, url string, ro *RequestOptions) (*Response, error) {
return buildResponse(buildRequest(requestVerb, url, ro, nil))
} | [
"func",
"DoRegularRequest",
"(",
"requestVerb",
",",
"url",
"string",
",",
"ro",
"*",
"RequestOptions",
")",
"(",
"*",
"Response",
",",
"error",
")",
"{",
"return",
"buildResponse",
"(",
"buildRequest",
"(",
"requestVerb",
",",
"url",
",",
"ro",
",",
"nil",
")",
")",
"\n",
"}"
] | // DoRegularRequest adds generic test functionality | [
"DoRegularRequest",
"adds",
"generic",
"test",
"functionality"
] | 37c80f76a0dae6ed656cbc830643ba53f45fc79c | https://github.com/levigross/grequests/blob/37c80f76a0dae6ed656cbc830643ba53f45fc79c/request.go#L144-L146 |
151,282 | levigross/grequests | request.go | buildRequest | func buildRequest(httpMethod, url string, ro *RequestOptions, httpClient *http.Client) (*http.Response, error) {
if ro == nil {
ro = &RequestOptions{}
}
if ro.CookieJar != nil {
ro.UseCookieJar = true
}
// Create our own HTTP client
if httpClient == nil {
httpClient = BuildHTTPClient(*ro)
}
var err error // we don't want to shadow url so we won't use :=
switch {
case len(ro.Params) != 0:
if url, err = buildURLParams(url, ro.Params); err != nil {
return nil, err
}
case ro.QueryStruct != nil:
if url, err = buildURLStruct(url, ro.QueryStruct); err != nil {
return nil, err
}
}
// Build the request
req, err := buildHTTPRequest(httpMethod, url, ro)
if err != nil {
return nil, err
}
// Do we need to add any HTTP headers or Basic Auth?
addHTTPHeaders(ro, req)
addCookies(ro, req)
addRedirectFunctionality(httpClient, ro)
if ro.Context != nil {
req = req.WithContext(ro.Context)
}
if ro.BeforeRequest != nil {
if err := ro.BeforeRequest(req); err != nil {
return nil, err
}
}
return httpClient.Do(req)
} | go | func buildRequest(httpMethod, url string, ro *RequestOptions, httpClient *http.Client) (*http.Response, error) {
if ro == nil {
ro = &RequestOptions{}
}
if ro.CookieJar != nil {
ro.UseCookieJar = true
}
// Create our own HTTP client
if httpClient == nil {
httpClient = BuildHTTPClient(*ro)
}
var err error // we don't want to shadow url so we won't use :=
switch {
case len(ro.Params) != 0:
if url, err = buildURLParams(url, ro.Params); err != nil {
return nil, err
}
case ro.QueryStruct != nil:
if url, err = buildURLStruct(url, ro.QueryStruct); err != nil {
return nil, err
}
}
// Build the request
req, err := buildHTTPRequest(httpMethod, url, ro)
if err != nil {
return nil, err
}
// Do we need to add any HTTP headers or Basic Auth?
addHTTPHeaders(ro, req)
addCookies(ro, req)
addRedirectFunctionality(httpClient, ro)
if ro.Context != nil {
req = req.WithContext(ro.Context)
}
if ro.BeforeRequest != nil {
if err := ro.BeforeRequest(req); err != nil {
return nil, err
}
}
return httpClient.Do(req)
} | [
"func",
"buildRequest",
"(",
"httpMethod",
",",
"url",
"string",
",",
"ro",
"*",
"RequestOptions",
",",
"httpClient",
"*",
"http",
".",
"Client",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"if",
"ro",
"==",
"nil",
"{",
"ro",
"=",
"&",
"RequestOptions",
"{",
"}",
"\n",
"}",
"\n\n",
"if",
"ro",
".",
"CookieJar",
"!=",
"nil",
"{",
"ro",
".",
"UseCookieJar",
"=",
"true",
"\n",
"}",
"\n\n",
"// Create our own HTTP client",
"if",
"httpClient",
"==",
"nil",
"{",
"httpClient",
"=",
"BuildHTTPClient",
"(",
"*",
"ro",
")",
"\n",
"}",
"\n\n",
"var",
"err",
"error",
"// we don't want to shadow url so we won't use :=",
"\n",
"switch",
"{",
"case",
"len",
"(",
"ro",
".",
"Params",
")",
"!=",
"0",
":",
"if",
"url",
",",
"err",
"=",
"buildURLParams",
"(",
"url",
",",
"ro",
".",
"Params",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"case",
"ro",
".",
"QueryStruct",
"!=",
"nil",
":",
"if",
"url",
",",
"err",
"=",
"buildURLStruct",
"(",
"url",
",",
"ro",
".",
"QueryStruct",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Build the request",
"req",
",",
"err",
":=",
"buildHTTPRequest",
"(",
"httpMethod",
",",
"url",
",",
"ro",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Do we need to add any HTTP headers or Basic Auth?",
"addHTTPHeaders",
"(",
"ro",
",",
"req",
")",
"\n",
"addCookies",
"(",
"ro",
",",
"req",
")",
"\n\n",
"addRedirectFunctionality",
"(",
"httpClient",
",",
"ro",
")",
"\n\n",
"if",
"ro",
".",
"Context",
"!=",
"nil",
"{",
"req",
"=",
"req",
".",
"WithContext",
"(",
"ro",
".",
"Context",
")",
"\n",
"}",
"\n\n",
"if",
"ro",
".",
"BeforeRequest",
"!=",
"nil",
"{",
"if",
"err",
":=",
"ro",
".",
"BeforeRequest",
"(",
"req",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"httpClient",
".",
"Do",
"(",
"req",
")",
"\n",
"}"
] | // buildRequest is where most of the magic happens for request processing | [
"buildRequest",
"is",
"where",
"most",
"of",
"the",
"magic",
"happens",
"for",
"request",
"processing"
] | 37c80f76a0dae6ed656cbc830643ba53f45fc79c | https://github.com/levigross/grequests/blob/37c80f76a0dae6ed656cbc830643ba53f45fc79c/request.go#L159-L210 |
151,283 | levigross/grequests | request.go | BuildHTTPClient | func BuildHTTPClient(ro RequestOptions) *http.Client {
if ro.HTTPClient != nil {
return ro.HTTPClient
}
// Does the user want to change the defaults?
if !ro.dontUseDefaultClient() {
return http.DefaultClient
}
// Using the user config for tls timeout or default
if ro.TLSHandshakeTimeout == 0 {
ro.TLSHandshakeTimeout = tlsHandshakeTimeout
}
// Using the user config for dial timeout or default
if ro.DialTimeout == 0 {
ro.DialTimeout = dialTimeout
}
// Using the user config for dial keep alive or default
if ro.DialKeepAlive == 0 {
ro.DialKeepAlive = dialKeepAlive
}
if ro.RequestTimeout == 0 {
ro.RequestTimeout = requestTimeout
}
var cookieJar http.CookieJar
if ro.UseCookieJar {
if ro.CookieJar != nil {
cookieJar = ro.CookieJar
} else {
// The function does not return an error ever... so we are just ignoring it
cookieJar, _ = cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
}
}
return &http.Client{
Jar: cookieJar,
Transport: createHTTPTransport(ro),
Timeout: ro.RequestTimeout,
}
} | go | func BuildHTTPClient(ro RequestOptions) *http.Client {
if ro.HTTPClient != nil {
return ro.HTTPClient
}
// Does the user want to change the defaults?
if !ro.dontUseDefaultClient() {
return http.DefaultClient
}
// Using the user config for tls timeout or default
if ro.TLSHandshakeTimeout == 0 {
ro.TLSHandshakeTimeout = tlsHandshakeTimeout
}
// Using the user config for dial timeout or default
if ro.DialTimeout == 0 {
ro.DialTimeout = dialTimeout
}
// Using the user config for dial keep alive or default
if ro.DialKeepAlive == 0 {
ro.DialKeepAlive = dialKeepAlive
}
if ro.RequestTimeout == 0 {
ro.RequestTimeout = requestTimeout
}
var cookieJar http.CookieJar
if ro.UseCookieJar {
if ro.CookieJar != nil {
cookieJar = ro.CookieJar
} else {
// The function does not return an error ever... so we are just ignoring it
cookieJar, _ = cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
}
}
return &http.Client{
Jar: cookieJar,
Transport: createHTTPTransport(ro),
Timeout: ro.RequestTimeout,
}
} | [
"func",
"BuildHTTPClient",
"(",
"ro",
"RequestOptions",
")",
"*",
"http",
".",
"Client",
"{",
"if",
"ro",
".",
"HTTPClient",
"!=",
"nil",
"{",
"return",
"ro",
".",
"HTTPClient",
"\n",
"}",
"\n\n",
"// Does the user want to change the defaults?",
"if",
"!",
"ro",
".",
"dontUseDefaultClient",
"(",
")",
"{",
"return",
"http",
".",
"DefaultClient",
"\n",
"}",
"\n\n",
"// Using the user config for tls timeout or default",
"if",
"ro",
".",
"TLSHandshakeTimeout",
"==",
"0",
"{",
"ro",
".",
"TLSHandshakeTimeout",
"=",
"tlsHandshakeTimeout",
"\n",
"}",
"\n\n",
"// Using the user config for dial timeout or default",
"if",
"ro",
".",
"DialTimeout",
"==",
"0",
"{",
"ro",
".",
"DialTimeout",
"=",
"dialTimeout",
"\n",
"}",
"\n\n",
"// Using the user config for dial keep alive or default",
"if",
"ro",
".",
"DialKeepAlive",
"==",
"0",
"{",
"ro",
".",
"DialKeepAlive",
"=",
"dialKeepAlive",
"\n",
"}",
"\n\n",
"if",
"ro",
".",
"RequestTimeout",
"==",
"0",
"{",
"ro",
".",
"RequestTimeout",
"=",
"requestTimeout",
"\n",
"}",
"\n\n",
"var",
"cookieJar",
"http",
".",
"CookieJar",
"\n\n",
"if",
"ro",
".",
"UseCookieJar",
"{",
"if",
"ro",
".",
"CookieJar",
"!=",
"nil",
"{",
"cookieJar",
"=",
"ro",
".",
"CookieJar",
"\n",
"}",
"else",
"{",
"// The function does not return an error ever... so we are just ignoring it",
"cookieJar",
",",
"_",
"=",
"cookiejar",
".",
"New",
"(",
"&",
"cookiejar",
".",
"Options",
"{",
"PublicSuffixList",
":",
"publicsuffix",
".",
"List",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"&",
"http",
".",
"Client",
"{",
"Jar",
":",
"cookieJar",
",",
"Transport",
":",
"createHTTPTransport",
"(",
"ro",
")",
",",
"Timeout",
":",
"ro",
".",
"RequestTimeout",
",",
"}",
"\n",
"}"
] | // BuildHTTPClient is a function that will return a custom HTTP client based on the request options provided
// the check is in UseDefaultClient | [
"BuildHTTPClient",
"is",
"a",
"function",
"that",
"will",
"return",
"a",
"custom",
"HTTP",
"client",
"based",
"on",
"the",
"request",
"options",
"provided",
"the",
"check",
"is",
"in",
"UseDefaultClient"
] | 37c80f76a0dae6ed656cbc830643ba53f45fc79c | https://github.com/levigross/grequests/blob/37c80f76a0dae6ed656cbc830643ba53f45fc79c/request.go#L456-L502 |
151,284 | levigross/grequests | response.go | Read | func (r *Response) Read(p []byte) (n int, err error) {
if r.Error != nil {
return -1, r.Error
}
return r.RawResponse.Body.Read(p)
} | go | func (r *Response) Read(p []byte) (n int, err error) {
if r.Error != nil {
return -1, r.Error
}
return r.RawResponse.Body.Read(p)
} | [
"func",
"(",
"r",
"*",
"Response",
")",
"Read",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"if",
"r",
".",
"Error",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"r",
".",
"Error",
"\n",
"}",
"\n\n",
"return",
"r",
".",
"RawResponse",
".",
"Body",
".",
"Read",
"(",
"p",
")",
"\n",
"}"
] | // Read is part of our ability to support io.ReadCloser if someone wants to make use of the raw body | [
"Read",
"is",
"part",
"of",
"our",
"ability",
"to",
"support",
"io",
".",
"ReadCloser",
"if",
"someone",
"wants",
"to",
"make",
"use",
"of",
"the",
"raw",
"body"
] | 37c80f76a0dae6ed656cbc830643ba53f45fc79c | https://github.com/levigross/grequests/blob/37c80f76a0dae6ed656cbc830643ba53f45fc79c/response.go#L55-L62 |
151,285 | levigross/grequests | response.go | Close | func (r *Response) Close() error {
if r.Error != nil {
return r.Error
}
io.Copy(ioutil.Discard, r)
return r.RawResponse.Body.Close()
} | go | func (r *Response) Close() error {
if r.Error != nil {
return r.Error
}
io.Copy(ioutil.Discard, r)
return r.RawResponse.Body.Close()
} | [
"func",
"(",
"r",
"*",
"Response",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"r",
".",
"Error",
"!=",
"nil",
"{",
"return",
"r",
".",
"Error",
"\n",
"}",
"\n\n",
"io",
".",
"Copy",
"(",
"ioutil",
".",
"Discard",
",",
"r",
")",
"\n\n",
"return",
"r",
".",
"RawResponse",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"}"
] | // Close is part of our ability to support io.ReadCloser if someone wants to make use of the raw body | [
"Close",
"is",
"part",
"of",
"our",
"ability",
"to",
"support",
"io",
".",
"ReadCloser",
"if",
"someone",
"wants",
"to",
"make",
"use",
"of",
"the",
"raw",
"body"
] | 37c80f76a0dae6ed656cbc830643ba53f45fc79c | https://github.com/levigross/grequests/blob/37c80f76a0dae6ed656cbc830643ba53f45fc79c/response.go#L65-L74 |
151,286 | levigross/grequests | response.go | DownloadToFile | func (r *Response) DownloadToFile(fileName string) error {
if r.Error != nil {
return r.Error
}
fd, err := os.Create(fileName)
if err != nil {
return err
}
defer r.Close() // This is a noop if we use the internal ByteBuffer
defer fd.Close()
if _, err := io.Copy(fd, r.getInternalReader()); err != nil && err != io.EOF {
return err
}
return nil
} | go | func (r *Response) DownloadToFile(fileName string) error {
if r.Error != nil {
return r.Error
}
fd, err := os.Create(fileName)
if err != nil {
return err
}
defer r.Close() // This is a noop if we use the internal ByteBuffer
defer fd.Close()
if _, err := io.Copy(fd, r.getInternalReader()); err != nil && err != io.EOF {
return err
}
return nil
} | [
"func",
"(",
"r",
"*",
"Response",
")",
"DownloadToFile",
"(",
"fileName",
"string",
")",
"error",
"{",
"if",
"r",
".",
"Error",
"!=",
"nil",
"{",
"return",
"r",
".",
"Error",
"\n",
"}",
"\n\n",
"fd",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"fileName",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"defer",
"r",
".",
"Close",
"(",
")",
"// This is a noop if we use the internal ByteBuffer",
"\n",
"defer",
"fd",
".",
"Close",
"(",
")",
"\n\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"Copy",
"(",
"fd",
",",
"r",
".",
"getInternalReader",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"io",
".",
"EOF",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // DownloadToFile allows you to download the contents of the response to a file | [
"DownloadToFile",
"allows",
"you",
"to",
"download",
"the",
"contents",
"of",
"the",
"response",
"to",
"a",
"file"
] | 37c80f76a0dae6ed656cbc830643ba53f45fc79c | https://github.com/levigross/grequests/blob/37c80f76a0dae6ed656cbc830643ba53f45fc79c/response.go#L77-L97 |
151,287 | levigross/grequests | response.go | JSON | func (r *Response) JSON(userStruct interface{}) error {
if r.Error != nil {
return r.Error
}
jsonDecoder := json.NewDecoder(r.getInternalReader())
defer r.Close()
return jsonDecoder.Decode(&userStruct)
} | go | func (r *Response) JSON(userStruct interface{}) error {
if r.Error != nil {
return r.Error
}
jsonDecoder := json.NewDecoder(r.getInternalReader())
defer r.Close()
return jsonDecoder.Decode(&userStruct)
} | [
"func",
"(",
"r",
"*",
"Response",
")",
"JSON",
"(",
"userStruct",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"r",
".",
"Error",
"!=",
"nil",
"{",
"return",
"r",
".",
"Error",
"\n",
"}",
"\n\n",
"jsonDecoder",
":=",
"json",
".",
"NewDecoder",
"(",
"r",
".",
"getInternalReader",
"(",
")",
")",
"\n",
"defer",
"r",
".",
"Close",
"(",
")",
"\n\n",
"return",
"jsonDecoder",
".",
"Decode",
"(",
"&",
"userStruct",
")",
"\n",
"}"
] | // JSON is a method that will populate a struct that is provided `userStruct` with the JSON returned within the
// response body | [
"JSON",
"is",
"a",
"method",
"that",
"will",
"populate",
"a",
"struct",
"that",
"is",
"provided",
"userStruct",
"with",
"the",
"JSON",
"returned",
"within",
"the",
"response",
"body"
] | 37c80f76a0dae6ed656cbc830643ba53f45fc79c | https://github.com/levigross/grequests/blob/37c80f76a0dae6ed656cbc830643ba53f45fc79c/response.go#L130-L140 |
151,288 | levigross/grequests | response.go | String | func (r *Response) String() string {
if r.Error != nil {
return ""
}
r.populateResponseByteBuffer()
return r.internalByteBuffer.String()
} | go | func (r *Response) String() string {
if r.Error != nil {
return ""
}
r.populateResponseByteBuffer()
return r.internalByteBuffer.String()
} | [
"func",
"(",
"r",
"*",
"Response",
")",
"String",
"(",
")",
"string",
"{",
"if",
"r",
".",
"Error",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"r",
".",
"populateResponseByteBuffer",
"(",
")",
"\n\n",
"return",
"r",
".",
"internalByteBuffer",
".",
"String",
"(",
")",
"\n",
"}"
] | // String returns the response as a string | [
"String",
"returns",
"the",
"response",
"as",
"a",
"string"
] | 37c80f76a0dae6ed656cbc830643ba53f45fc79c | https://github.com/levigross/grequests/blob/37c80f76a0dae6ed656cbc830643ba53f45fc79c/response.go#L188-L196 |
151,289 | levigross/grequests | file_upload.go | FileUploadFromDisk | func FileUploadFromDisk(fileName string) ([]FileUpload, error) {
fd, err := os.Open(fileName)
if err != nil {
return nil, err
}
return []FileUpload{{FileContents: fd, FileName: fileName}}, nil
} | go | func FileUploadFromDisk(fileName string) ([]FileUpload, error) {
fd, err := os.Open(fileName)
if err != nil {
return nil, err
}
return []FileUpload{{FileContents: fd, FileName: fileName}}, nil
} | [
"func",
"FileUploadFromDisk",
"(",
"fileName",
"string",
")",
"(",
"[",
"]",
"FileUpload",
",",
"error",
")",
"{",
"fd",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"fileName",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"[",
"]",
"FileUpload",
"{",
"{",
"FileContents",
":",
"fd",
",",
"FileName",
":",
"fileName",
"}",
"}",
",",
"nil",
"\n\n",
"}"
] | // FileUploadFromDisk allows you to create a FileUpload struct slice by just specifying a location on the disk | [
"FileUploadFromDisk",
"allows",
"you",
"to",
"create",
"a",
"FileUpload",
"struct",
"slice",
"by",
"just",
"specifying",
"a",
"location",
"on",
"the",
"disk"
] | 37c80f76a0dae6ed656cbc830643ba53f45fc79c | https://github.com/levigross/grequests/blob/37c80f76a0dae6ed656cbc830643ba53f45fc79c/file_upload.go#L28-L37 |
151,290 | levigross/grequests | file_upload.go | FileUploadFromGlob | func FileUploadFromGlob(fileSystemGlob string) ([]FileUpload, error) {
files, err := filepath.Glob(fileSystemGlob)
if err != nil {
return nil, err
}
if len(files) == 0 {
return nil, errors.New("grequests: No files have been returned in the glob")
}
filesToUpload := make([]FileUpload, 0, len(files))
for _, f := range files {
if s, err := os.Stat(f); err != nil || s.IsDir() {
continue
}
// ignoring error because I can stat the file
fd, _ := os.Open(f)
filesToUpload = append(filesToUpload, FileUpload{FileContents: fd, FileName: filepath.Base(fd.Name())})
}
return filesToUpload, nil
} | go | func FileUploadFromGlob(fileSystemGlob string) ([]FileUpload, error) {
files, err := filepath.Glob(fileSystemGlob)
if err != nil {
return nil, err
}
if len(files) == 0 {
return nil, errors.New("grequests: No files have been returned in the glob")
}
filesToUpload := make([]FileUpload, 0, len(files))
for _, f := range files {
if s, err := os.Stat(f); err != nil || s.IsDir() {
continue
}
// ignoring error because I can stat the file
fd, _ := os.Open(f)
filesToUpload = append(filesToUpload, FileUpload{FileContents: fd, FileName: filepath.Base(fd.Name())})
}
return filesToUpload, nil
} | [
"func",
"FileUploadFromGlob",
"(",
"fileSystemGlob",
"string",
")",
"(",
"[",
"]",
"FileUpload",
",",
"error",
")",
"{",
"files",
",",
"err",
":=",
"filepath",
".",
"Glob",
"(",
"fileSystemGlob",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"files",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"filesToUpload",
":=",
"make",
"(",
"[",
"]",
"FileUpload",
",",
"0",
",",
"len",
"(",
"files",
")",
")",
"\n\n",
"for",
"_",
",",
"f",
":=",
"range",
"files",
"{",
"if",
"s",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"f",
")",
";",
"err",
"!=",
"nil",
"||",
"s",
".",
"IsDir",
"(",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"// ignoring error because I can stat the file",
"fd",
",",
"_",
":=",
"os",
".",
"Open",
"(",
"f",
")",
"\n\n",
"filesToUpload",
"=",
"append",
"(",
"filesToUpload",
",",
"FileUpload",
"{",
"FileContents",
":",
"fd",
",",
"FileName",
":",
"filepath",
".",
"Base",
"(",
"fd",
".",
"Name",
"(",
")",
")",
"}",
")",
"\n\n",
"}",
"\n\n",
"return",
"filesToUpload",
",",
"nil",
"\n\n",
"}"
] | // FileUploadFromGlob allows you to create a FileUpload struct slice by just specifying a glob location on the disk
// this function will gloss over all errors in the files and only upload the files that don't return errors from the glob | [
"FileUploadFromGlob",
"allows",
"you",
"to",
"create",
"a",
"FileUpload",
"struct",
"slice",
"by",
"just",
"specifying",
"a",
"glob",
"location",
"on",
"the",
"disk",
"this",
"function",
"will",
"gloss",
"over",
"all",
"errors",
"in",
"the",
"files",
"and",
"only",
"upload",
"the",
"files",
"that",
"don",
"t",
"return",
"errors",
"from",
"the",
"glob"
] | 37c80f76a0dae6ed656cbc830643ba53f45fc79c | https://github.com/levigross/grequests/blob/37c80f76a0dae6ed656cbc830643ba53f45fc79c/file_upload.go#L41-L68 |
151,291 | ahmetb/go-linq | orderby.go | OrderBy | func (q Query) OrderBy(selector func(interface{}) interface{}) OrderedQuery {
return OrderedQuery{
orders: []order{{selector: selector}},
original: q,
Query: Query{
Iterate: func() Iterator {
items := q.sort([]order{{selector: selector}})
len := len(items)
index := 0
return func() (item interface{}, ok bool) {
ok = index < len
if ok {
item = items[index]
index++
}
return
}
},
},
}
} | go | func (q Query) OrderBy(selector func(interface{}) interface{}) OrderedQuery {
return OrderedQuery{
orders: []order{{selector: selector}},
original: q,
Query: Query{
Iterate: func() Iterator {
items := q.sort([]order{{selector: selector}})
len := len(items)
index := 0
return func() (item interface{}, ok bool) {
ok = index < len
if ok {
item = items[index]
index++
}
return
}
},
},
}
} | [
"func",
"(",
"q",
"Query",
")",
"OrderBy",
"(",
"selector",
"func",
"(",
"interface",
"{",
"}",
")",
"interface",
"{",
"}",
")",
"OrderedQuery",
"{",
"return",
"OrderedQuery",
"{",
"orders",
":",
"[",
"]",
"order",
"{",
"{",
"selector",
":",
"selector",
"}",
"}",
",",
"original",
":",
"q",
",",
"Query",
":",
"Query",
"{",
"Iterate",
":",
"func",
"(",
")",
"Iterator",
"{",
"items",
":=",
"q",
".",
"sort",
"(",
"[",
"]",
"order",
"{",
"{",
"selector",
":",
"selector",
"}",
"}",
")",
"\n",
"len",
":=",
"len",
"(",
"items",
")",
"\n",
"index",
":=",
"0",
"\n\n",
"return",
"func",
"(",
")",
"(",
"item",
"interface",
"{",
"}",
",",
"ok",
"bool",
")",
"{",
"ok",
"=",
"index",
"<",
"len",
"\n",
"if",
"ok",
"{",
"item",
"=",
"items",
"[",
"index",
"]",
"\n",
"index",
"++",
"\n",
"}",
"\n\n",
"return",
"\n",
"}",
"\n",
"}",
",",
"}",
",",
"}",
"\n",
"}"
] | // OrderBy sorts the elements of a collection in ascending order. Elements are
// sorted according to a key. | [
"OrderBy",
"sorts",
"the",
"elements",
"of",
"a",
"collection",
"in",
"ascending",
"order",
".",
"Elements",
"are",
"sorted",
"according",
"to",
"a",
"key",
"."
] | 9f6960b5d2e017ec4b7820f045fbd7db66dd53b6 | https://github.com/ahmetb/go-linq/blob/9f6960b5d2e017ec4b7820f045fbd7db66dd53b6/orderby.go#L21-L43 |
151,292 | ahmetb/go-linq | orderby.go | ThenByDescending | func (oq OrderedQuery) ThenByDescending(selector func(interface{}) interface{}) OrderedQuery {
return OrderedQuery{
orders: append(oq.orders, order{selector: selector, desc: true}),
original: oq.original,
Query: Query{
Iterate: func() Iterator {
items := oq.original.sort(append(oq.orders, order{selector: selector, desc: true}))
len := len(items)
index := 0
return func() (item interface{}, ok bool) {
ok = index < len
if ok {
item = items[index]
index++
}
return
}
},
},
}
} | go | func (oq OrderedQuery) ThenByDescending(selector func(interface{}) interface{}) OrderedQuery {
return OrderedQuery{
orders: append(oq.orders, order{selector: selector, desc: true}),
original: oq.original,
Query: Query{
Iterate: func() Iterator {
items := oq.original.sort(append(oq.orders, order{selector: selector, desc: true}))
len := len(items)
index := 0
return func() (item interface{}, ok bool) {
ok = index < len
if ok {
item = items[index]
index++
}
return
}
},
},
}
} | [
"func",
"(",
"oq",
"OrderedQuery",
")",
"ThenByDescending",
"(",
"selector",
"func",
"(",
"interface",
"{",
"}",
")",
"interface",
"{",
"}",
")",
"OrderedQuery",
"{",
"return",
"OrderedQuery",
"{",
"orders",
":",
"append",
"(",
"oq",
".",
"orders",
",",
"order",
"{",
"selector",
":",
"selector",
",",
"desc",
":",
"true",
"}",
")",
",",
"original",
":",
"oq",
".",
"original",
",",
"Query",
":",
"Query",
"{",
"Iterate",
":",
"func",
"(",
")",
"Iterator",
"{",
"items",
":=",
"oq",
".",
"original",
".",
"sort",
"(",
"append",
"(",
"oq",
".",
"orders",
",",
"order",
"{",
"selector",
":",
"selector",
",",
"desc",
":",
"true",
"}",
")",
")",
"\n",
"len",
":=",
"len",
"(",
"items",
")",
"\n",
"index",
":=",
"0",
"\n\n",
"return",
"func",
"(",
")",
"(",
"item",
"interface",
"{",
"}",
",",
"ok",
"bool",
")",
"{",
"ok",
"=",
"index",
"<",
"len",
"\n",
"if",
"ok",
"{",
"item",
"=",
"items",
"[",
"index",
"]",
"\n",
"index",
"++",
"\n",
"}",
"\n\n",
"return",
"\n",
"}",
"\n",
"}",
",",
"}",
",",
"}",
"\n",
"}"
] | // ThenByDescending performs a subsequent ordering of the elements in a
// collection in descending order. This method enables you to specify multiple
// sort criteria by applying any number of ThenBy or ThenByDescending methods. | [
"ThenByDescending",
"performs",
"a",
"subsequent",
"ordering",
"of",
"the",
"elements",
"in",
"a",
"collection",
"in",
"descending",
"order",
".",
"This",
"method",
"enables",
"you",
"to",
"specify",
"multiple",
"sort",
"criteria",
"by",
"applying",
"any",
"number",
"of",
"ThenBy",
"or",
"ThenByDescending",
"methods",
"."
] | 9f6960b5d2e017ec4b7820f045fbd7db66dd53b6 | https://github.com/ahmetb/go-linq/blob/9f6960b5d2e017ec4b7820f045fbd7db66dd53b6/orderby.go#L161-L183 |
151,293 | ahmetb/go-linq | orderby.go | Sort | func (q Query) Sort(less func(i, j interface{}) bool) Query {
return Query{
Iterate: func() Iterator {
items := q.lessSort(less)
len := len(items)
index := 0
return func() (item interface{}, ok bool) {
ok = index < len
if ok {
item = items[index]
index++
}
return
}
},
}
} | go | func (q Query) Sort(less func(i, j interface{}) bool) Query {
return Query{
Iterate: func() Iterator {
items := q.lessSort(less)
len := len(items)
index := 0
return func() (item interface{}, ok bool) {
ok = index < len
if ok {
item = items[index]
index++
}
return
}
},
}
} | [
"func",
"(",
"q",
"Query",
")",
"Sort",
"(",
"less",
"func",
"(",
"i",
",",
"j",
"interface",
"{",
"}",
")",
"bool",
")",
"Query",
"{",
"return",
"Query",
"{",
"Iterate",
":",
"func",
"(",
")",
"Iterator",
"{",
"items",
":=",
"q",
".",
"lessSort",
"(",
"less",
")",
"\n",
"len",
":=",
"len",
"(",
"items",
")",
"\n",
"index",
":=",
"0",
"\n\n",
"return",
"func",
"(",
")",
"(",
"item",
"interface",
"{",
"}",
",",
"ok",
"bool",
")",
"{",
"ok",
"=",
"index",
"<",
"len",
"\n",
"if",
"ok",
"{",
"item",
"=",
"items",
"[",
"index",
"]",
"\n",
"index",
"++",
"\n",
"}",
"\n\n",
"return",
"\n",
"}",
"\n",
"}",
",",
"}",
"\n",
"}"
] | // Sort returns a new query by sorting elements with provided less function in
// ascending order. The comparer function should return true if the parameter i
// is less than j. While this method is uglier than chaining OrderBy,
// OrderByDescending, ThenBy and ThenByDescending methods, it's performance is
// much better. | [
"Sort",
"returns",
"a",
"new",
"query",
"by",
"sorting",
"elements",
"with",
"provided",
"less",
"function",
"in",
"ascending",
"order",
".",
"The",
"comparer",
"function",
"should",
"return",
"true",
"if",
"the",
"parameter",
"i",
"is",
"less",
"than",
"j",
".",
"While",
"this",
"method",
"is",
"uglier",
"than",
"chaining",
"OrderBy",
"OrderByDescending",
"ThenBy",
"and",
"ThenByDescending",
"methods",
"it",
"s",
"performance",
"is",
"much",
"better",
"."
] | 9f6960b5d2e017ec4b7820f045fbd7db66dd53b6 | https://github.com/ahmetb/go-linq/blob/9f6960b5d2e017ec4b7820f045fbd7db66dd53b6/orderby.go#L211-L229 |
151,294 | ahmetb/go-linq | join.go | Join | func (q Query) Join(inner Query,
outerKeySelector func(interface{}) interface{},
innerKeySelector func(interface{}) interface{},
resultSelector func(outer interface{}, inner interface{}) interface{}) Query {
return Query{
Iterate: func() Iterator {
outernext := q.Iterate()
innernext := inner.Iterate()
innerLookup := make(map[interface{}][]interface{})
for innerItem, ok := innernext(); ok; innerItem, ok = innernext() {
innerKey := innerKeySelector(innerItem)
innerLookup[innerKey] = append(innerLookup[innerKey], innerItem)
}
var outerItem interface{}
var innerGroup []interface{}
innerLen, innerIndex := 0, 0
return func() (item interface{}, ok bool) {
if innerIndex >= innerLen {
has := false
for !has {
outerItem, ok = outernext()
if !ok {
return
}
innerGroup, has = innerLookup[outerKeySelector(outerItem)]
innerLen = len(innerGroup)
innerIndex = 0
}
}
item = resultSelector(outerItem, innerGroup[innerIndex])
innerIndex++
return item, true
}
},
}
} | go | func (q Query) Join(inner Query,
outerKeySelector func(interface{}) interface{},
innerKeySelector func(interface{}) interface{},
resultSelector func(outer interface{}, inner interface{}) interface{}) Query {
return Query{
Iterate: func() Iterator {
outernext := q.Iterate()
innernext := inner.Iterate()
innerLookup := make(map[interface{}][]interface{})
for innerItem, ok := innernext(); ok; innerItem, ok = innernext() {
innerKey := innerKeySelector(innerItem)
innerLookup[innerKey] = append(innerLookup[innerKey], innerItem)
}
var outerItem interface{}
var innerGroup []interface{}
innerLen, innerIndex := 0, 0
return func() (item interface{}, ok bool) {
if innerIndex >= innerLen {
has := false
for !has {
outerItem, ok = outernext()
if !ok {
return
}
innerGroup, has = innerLookup[outerKeySelector(outerItem)]
innerLen = len(innerGroup)
innerIndex = 0
}
}
item = resultSelector(outerItem, innerGroup[innerIndex])
innerIndex++
return item, true
}
},
}
} | [
"func",
"(",
"q",
"Query",
")",
"Join",
"(",
"inner",
"Query",
",",
"outerKeySelector",
"func",
"(",
"interface",
"{",
"}",
")",
"interface",
"{",
"}",
",",
"innerKeySelector",
"func",
"(",
"interface",
"{",
"}",
")",
"interface",
"{",
"}",
",",
"resultSelector",
"func",
"(",
"outer",
"interface",
"{",
"}",
",",
"inner",
"interface",
"{",
"}",
")",
"interface",
"{",
"}",
")",
"Query",
"{",
"return",
"Query",
"{",
"Iterate",
":",
"func",
"(",
")",
"Iterator",
"{",
"outernext",
":=",
"q",
".",
"Iterate",
"(",
")",
"\n",
"innernext",
":=",
"inner",
".",
"Iterate",
"(",
")",
"\n\n",
"innerLookup",
":=",
"make",
"(",
"map",
"[",
"interface",
"{",
"}",
"]",
"[",
"]",
"interface",
"{",
"}",
")",
"\n",
"for",
"innerItem",
",",
"ok",
":=",
"innernext",
"(",
")",
";",
"ok",
";",
"innerItem",
",",
"ok",
"=",
"innernext",
"(",
")",
"{",
"innerKey",
":=",
"innerKeySelector",
"(",
"innerItem",
")",
"\n",
"innerLookup",
"[",
"innerKey",
"]",
"=",
"append",
"(",
"innerLookup",
"[",
"innerKey",
"]",
",",
"innerItem",
")",
"\n",
"}",
"\n\n",
"var",
"outerItem",
"interface",
"{",
"}",
"\n",
"var",
"innerGroup",
"[",
"]",
"interface",
"{",
"}",
"\n",
"innerLen",
",",
"innerIndex",
":=",
"0",
",",
"0",
"\n\n",
"return",
"func",
"(",
")",
"(",
"item",
"interface",
"{",
"}",
",",
"ok",
"bool",
")",
"{",
"if",
"innerIndex",
">=",
"innerLen",
"{",
"has",
":=",
"false",
"\n",
"for",
"!",
"has",
"{",
"outerItem",
",",
"ok",
"=",
"outernext",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n\n",
"innerGroup",
",",
"has",
"=",
"innerLookup",
"[",
"outerKeySelector",
"(",
"outerItem",
")",
"]",
"\n",
"innerLen",
"=",
"len",
"(",
"innerGroup",
")",
"\n",
"innerIndex",
"=",
"0",
"\n",
"}",
"\n",
"}",
"\n\n",
"item",
"=",
"resultSelector",
"(",
"outerItem",
",",
"innerGroup",
"[",
"innerIndex",
"]",
")",
"\n",
"innerIndex",
"++",
"\n",
"return",
"item",
",",
"true",
"\n",
"}",
"\n",
"}",
",",
"}",
"\n",
"}"
] | // Join correlates the elements of two collection based on matching keys.
//
// A join refers to the operation of correlating the elements of two sources of
// information based on a common key. Join brings the two information sources
// and the keys by which they are matched together in one method call. This
// differs from the use of SelectMany, which requires more than one method call
// to perform the same operation.
//
// Join preserves the order of the elements of outer collection, and for each of
// these elements, the order of the matching elements of inner. | [
"Join",
"correlates",
"the",
"elements",
"of",
"two",
"collection",
"based",
"on",
"matching",
"keys",
".",
"A",
"join",
"refers",
"to",
"the",
"operation",
"of",
"correlating",
"the",
"elements",
"of",
"two",
"sources",
"of",
"information",
"based",
"on",
"a",
"common",
"key",
".",
"Join",
"brings",
"the",
"two",
"information",
"sources",
"and",
"the",
"keys",
"by",
"which",
"they",
"are",
"matched",
"together",
"in",
"one",
"method",
"call",
".",
"This",
"differs",
"from",
"the",
"use",
"of",
"SelectMany",
"which",
"requires",
"more",
"than",
"one",
"method",
"call",
"to",
"perform",
"the",
"same",
"operation",
".",
"Join",
"preserves",
"the",
"order",
"of",
"the",
"elements",
"of",
"outer",
"collection",
"and",
"for",
"each",
"of",
"these",
"elements",
"the",
"order",
"of",
"the",
"matching",
"elements",
"of",
"inner",
"."
] | 9f6960b5d2e017ec4b7820f045fbd7db66dd53b6 | https://github.com/ahmetb/go-linq/blob/9f6960b5d2e017ec4b7820f045fbd7db66dd53b6/join.go#L13-L54 |
151,295 | ahmetb/go-linq | skip.go | Skip | func (q Query) Skip(count int) Query {
return Query{
Iterate: func() Iterator {
next := q.Iterate()
n := count
return func() (item interface{}, ok bool) {
for ; n > 0; n-- {
item, ok = next()
if !ok {
return
}
}
return next()
}
},
}
} | go | func (q Query) Skip(count int) Query {
return Query{
Iterate: func() Iterator {
next := q.Iterate()
n := count
return func() (item interface{}, ok bool) {
for ; n > 0; n-- {
item, ok = next()
if !ok {
return
}
}
return next()
}
},
}
} | [
"func",
"(",
"q",
"Query",
")",
"Skip",
"(",
"count",
"int",
")",
"Query",
"{",
"return",
"Query",
"{",
"Iterate",
":",
"func",
"(",
")",
"Iterator",
"{",
"next",
":=",
"q",
".",
"Iterate",
"(",
")",
"\n",
"n",
":=",
"count",
"\n\n",
"return",
"func",
"(",
")",
"(",
"item",
"interface",
"{",
"}",
",",
"ok",
"bool",
")",
"{",
"for",
";",
"n",
">",
"0",
";",
"n",
"--",
"{",
"item",
",",
"ok",
"=",
"next",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"next",
"(",
")",
"\n",
"}",
"\n",
"}",
",",
"}",
"\n",
"}"
] | // Skip bypasses a specified number of elements in a collection and then returns
// the remaining elements. | [
"Skip",
"bypasses",
"a",
"specified",
"number",
"of",
"elements",
"in",
"a",
"collection",
"and",
"then",
"returns",
"the",
"remaining",
"elements",
"."
] | 9f6960b5d2e017ec4b7820f045fbd7db66dd53b6 | https://github.com/ahmetb/go-linq/blob/9f6960b5d2e017ec4b7820f045fbd7db66dd53b6/skip.go#L5-L23 |
151,296 | ahmetb/go-linq | skip.go | SkipWhile | func (q Query) SkipWhile(predicate func(interface{}) bool) Query {
return Query{
Iterate: func() Iterator {
next := q.Iterate()
ready := false
return func() (item interface{}, ok bool) {
for !ready {
item, ok = next()
if !ok {
return
}
ready = !predicate(item)
if ready {
return
}
}
return next()
}
},
}
} | go | func (q Query) SkipWhile(predicate func(interface{}) bool) Query {
return Query{
Iterate: func() Iterator {
next := q.Iterate()
ready := false
return func() (item interface{}, ok bool) {
for !ready {
item, ok = next()
if !ok {
return
}
ready = !predicate(item)
if ready {
return
}
}
return next()
}
},
}
} | [
"func",
"(",
"q",
"Query",
")",
"SkipWhile",
"(",
"predicate",
"func",
"(",
"interface",
"{",
"}",
")",
"bool",
")",
"Query",
"{",
"return",
"Query",
"{",
"Iterate",
":",
"func",
"(",
")",
"Iterator",
"{",
"next",
":=",
"q",
".",
"Iterate",
"(",
")",
"\n",
"ready",
":=",
"false",
"\n\n",
"return",
"func",
"(",
")",
"(",
"item",
"interface",
"{",
"}",
",",
"ok",
"bool",
")",
"{",
"for",
"!",
"ready",
"{",
"item",
",",
"ok",
"=",
"next",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n\n",
"ready",
"=",
"!",
"predicate",
"(",
"item",
")",
"\n",
"if",
"ready",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"next",
"(",
")",
"\n",
"}",
"\n",
"}",
",",
"}",
"\n",
"}"
] | // SkipWhile bypasses elements in a collection as long as a specified condition
// is true and then returns the remaining elements.
//
// This method tests each element by using predicate and skips the element if
// the result is true. After the predicate function returns false for an
// element, that element and the remaining elements in source are returned and
// there are no more invocations of predicate. | [
"SkipWhile",
"bypasses",
"elements",
"in",
"a",
"collection",
"as",
"long",
"as",
"a",
"specified",
"condition",
"is",
"true",
"and",
"then",
"returns",
"the",
"remaining",
"elements",
".",
"This",
"method",
"tests",
"each",
"element",
"by",
"using",
"predicate",
"and",
"skips",
"the",
"element",
"if",
"the",
"result",
"is",
"true",
".",
"After",
"the",
"predicate",
"function",
"returns",
"false",
"for",
"an",
"element",
"that",
"element",
"and",
"the",
"remaining",
"elements",
"in",
"source",
"are",
"returned",
"and",
"there",
"are",
"no",
"more",
"invocations",
"of",
"predicate",
"."
] | 9f6960b5d2e017ec4b7820f045fbd7db66dd53b6 | https://github.com/ahmetb/go-linq/blob/9f6960b5d2e017ec4b7820f045fbd7db66dd53b6/skip.go#L32-L55 |
151,297 | ahmetb/go-linq | skip.go | SkipWhileIndexed | func (q Query) SkipWhileIndexed(predicate func(int, interface{}) bool) Query {
return Query{
Iterate: func() Iterator {
next := q.Iterate()
ready := false
index := 0
return func() (item interface{}, ok bool) {
for !ready {
item, ok = next()
if !ok {
return
}
ready = !predicate(index, item)
if ready {
return
}
index++
}
return next()
}
},
}
} | go | func (q Query) SkipWhileIndexed(predicate func(int, interface{}) bool) Query {
return Query{
Iterate: func() Iterator {
next := q.Iterate()
ready := false
index := 0
return func() (item interface{}, ok bool) {
for !ready {
item, ok = next()
if !ok {
return
}
ready = !predicate(index, item)
if ready {
return
}
index++
}
return next()
}
},
}
} | [
"func",
"(",
"q",
"Query",
")",
"SkipWhileIndexed",
"(",
"predicate",
"func",
"(",
"int",
",",
"interface",
"{",
"}",
")",
"bool",
")",
"Query",
"{",
"return",
"Query",
"{",
"Iterate",
":",
"func",
"(",
")",
"Iterator",
"{",
"next",
":=",
"q",
".",
"Iterate",
"(",
")",
"\n",
"ready",
":=",
"false",
"\n",
"index",
":=",
"0",
"\n\n",
"return",
"func",
"(",
")",
"(",
"item",
"interface",
"{",
"}",
",",
"ok",
"bool",
")",
"{",
"for",
"!",
"ready",
"{",
"item",
",",
"ok",
"=",
"next",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n\n",
"ready",
"=",
"!",
"predicate",
"(",
"index",
",",
"item",
")",
"\n",
"if",
"ready",
"{",
"return",
"\n",
"}",
"\n\n",
"index",
"++",
"\n",
"}",
"\n\n",
"return",
"next",
"(",
")",
"\n",
"}",
"\n",
"}",
",",
"}",
"\n",
"}"
] | // SkipWhileIndexed bypasses elements in a collection as long as a specified
// condition is true and then returns the remaining elements. The element's
// index is used in the logic of the predicate function.
//
// This method tests each element by using predicate and skips the element if
// the result is true. After the predicate function returns false for an
// element, that element and the remaining elements in source are returned and
// there are no more invocations of predicate. | [
"SkipWhileIndexed",
"bypasses",
"elements",
"in",
"a",
"collection",
"as",
"long",
"as",
"a",
"specified",
"condition",
"is",
"true",
"and",
"then",
"returns",
"the",
"remaining",
"elements",
".",
"The",
"element",
"s",
"index",
"is",
"used",
"in",
"the",
"logic",
"of",
"the",
"predicate",
"function",
".",
"This",
"method",
"tests",
"each",
"element",
"by",
"using",
"predicate",
"and",
"skips",
"the",
"element",
"if",
"the",
"result",
"is",
"true",
".",
"After",
"the",
"predicate",
"function",
"returns",
"false",
"for",
"an",
"element",
"that",
"element",
"and",
"the",
"remaining",
"elements",
"in",
"source",
"are",
"returned",
"and",
"there",
"are",
"no",
"more",
"invocations",
"of",
"predicate",
"."
] | 9f6960b5d2e017ec4b7820f045fbd7db66dd53b6 | https://github.com/ahmetb/go-linq/blob/9f6960b5d2e017ec4b7820f045fbd7db66dd53b6/skip.go#L87-L113 |
151,298 | ahmetb/go-linq | take.go | TakeWhile | func (q Query) TakeWhile(predicate func(interface{}) bool) Query {
return Query{
Iterate: func() Iterator {
next := q.Iterate()
done := false
return func() (item interface{}, ok bool) {
if done {
return
}
item, ok = next()
if !ok {
done = true
return
}
if predicate(item) {
return
}
done = true
return nil, false
}
},
}
} | go | func (q Query) TakeWhile(predicate func(interface{}) bool) Query {
return Query{
Iterate: func() Iterator {
next := q.Iterate()
done := false
return func() (item interface{}, ok bool) {
if done {
return
}
item, ok = next()
if !ok {
done = true
return
}
if predicate(item) {
return
}
done = true
return nil, false
}
},
}
} | [
"func",
"(",
"q",
"Query",
")",
"TakeWhile",
"(",
"predicate",
"func",
"(",
"interface",
"{",
"}",
")",
"bool",
")",
"Query",
"{",
"return",
"Query",
"{",
"Iterate",
":",
"func",
"(",
")",
"Iterator",
"{",
"next",
":=",
"q",
".",
"Iterate",
"(",
")",
"\n",
"done",
":=",
"false",
"\n\n",
"return",
"func",
"(",
")",
"(",
"item",
"interface",
"{",
"}",
",",
"ok",
"bool",
")",
"{",
"if",
"done",
"{",
"return",
"\n",
"}",
"\n\n",
"item",
",",
"ok",
"=",
"next",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"done",
"=",
"true",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"predicate",
"(",
"item",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"done",
"=",
"true",
"\n",
"return",
"nil",
",",
"false",
"\n",
"}",
"\n",
"}",
",",
"}",
"\n",
"}"
] | // TakeWhile returns elements from a collection as long as a specified condition
// is true, and then skips the remaining elements. | [
"TakeWhile",
"returns",
"elements",
"from",
"a",
"collection",
"as",
"long",
"as",
"a",
"specified",
"condition",
"is",
"true",
"and",
"then",
"skips",
"the",
"remaining",
"elements",
"."
] | 9f6960b5d2e017ec4b7820f045fbd7db66dd53b6 | https://github.com/ahmetb/go-linq/blob/9f6960b5d2e017ec4b7820f045fbd7db66dd53b6/take.go#L25-L51 |
151,299 | ahmetb/go-linq | take.go | TakeWhileIndexed | func (q Query) TakeWhileIndexed(predicate func(int, interface{}) bool) Query {
return Query{
Iterate: func() Iterator {
next := q.Iterate()
done := false
index := 0
return func() (item interface{}, ok bool) {
if done {
return
}
item, ok = next()
if !ok {
done = true
return
}
if predicate(index, item) {
index++
return
}
done = true
return nil, false
}
},
}
} | go | func (q Query) TakeWhileIndexed(predicate func(int, interface{}) bool) Query {
return Query{
Iterate: func() Iterator {
next := q.Iterate()
done := false
index := 0
return func() (item interface{}, ok bool) {
if done {
return
}
item, ok = next()
if !ok {
done = true
return
}
if predicate(index, item) {
index++
return
}
done = true
return nil, false
}
},
}
} | [
"func",
"(",
"q",
"Query",
")",
"TakeWhileIndexed",
"(",
"predicate",
"func",
"(",
"int",
",",
"interface",
"{",
"}",
")",
"bool",
")",
"Query",
"{",
"return",
"Query",
"{",
"Iterate",
":",
"func",
"(",
")",
"Iterator",
"{",
"next",
":=",
"q",
".",
"Iterate",
"(",
")",
"\n",
"done",
":=",
"false",
"\n",
"index",
":=",
"0",
"\n\n",
"return",
"func",
"(",
")",
"(",
"item",
"interface",
"{",
"}",
",",
"ok",
"bool",
")",
"{",
"if",
"done",
"{",
"return",
"\n",
"}",
"\n\n",
"item",
",",
"ok",
"=",
"next",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"done",
"=",
"true",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"predicate",
"(",
"index",
",",
"item",
")",
"{",
"index",
"++",
"\n",
"return",
"\n",
"}",
"\n\n",
"done",
"=",
"true",
"\n",
"return",
"nil",
",",
"false",
"\n",
"}",
"\n",
"}",
",",
"}",
"\n",
"}"
] | // TakeWhileIndexed returns elements from a collection as long as a specified
// condition is true. The element's index is used in the logic of the predicate
// function. The first argument of predicate represents the zero-based index of
// the element within collection. The second argument represents the element to
// test. | [
"TakeWhileIndexed",
"returns",
"elements",
"from",
"a",
"collection",
"as",
"long",
"as",
"a",
"specified",
"condition",
"is",
"true",
".",
"The",
"element",
"s",
"index",
"is",
"used",
"in",
"the",
"logic",
"of",
"the",
"predicate",
"function",
".",
"The",
"first",
"argument",
"of",
"predicate",
"represents",
"the",
"zero",
"-",
"based",
"index",
"of",
"the",
"element",
"within",
"collection",
".",
"The",
"second",
"argument",
"represents",
"the",
"element",
"to",
"test",
"."
] | 9f6960b5d2e017ec4b7820f045fbd7db66dd53b6 | https://github.com/ahmetb/go-linq/blob/9f6960b5d2e017ec4b7820f045fbd7db66dd53b6/take.go#L80-L108 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.