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
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
2,900
m3db/m3x
checked/ref.go
DecWrites
func (c *RefCount) DecWrites() { tracebackEvent(c, c.NumRef(), decWritesEvent) n := atomic.AddInt32(&c.writes, -1) if ref := c.NumRef(); ref < 1 { err := fmt.Errorf("write finish after free: writes=%d, ref=%d", n, ref) panicRef(c, err) } }
go
func (c *RefCount) DecWrites() { tracebackEvent(c, c.NumRef(), decWritesEvent) n := atomic.AddInt32(&c.writes, -1) if ref := c.NumRef(); ref < 1 { err := fmt.Errorf("write finish after free: writes=%d, ref=%d", n, ref) panicRef(c, err) } }
[ "func", "(", "c", "*", "RefCount", ")", "DecWrites", "(", ")", "{", "tracebackEvent", "(", "c", ",", "c", ".", "NumRef", "(", ")", ",", "decWritesEvent", ")", "\n", "n", ":=", "atomic", ".", "AddInt32", "(", "&", "c", ".", "writes", ",", "-", "1"...
// DecWrites decrements the writes count to this entity.
[ "DecWrites", "decrements", "the", "writes", "count", "to", "this", "entity", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/checked/ref.go#L142-L150
2,901
m3db/m3x
checked/ref.go
TrackObject
func (c *RefCount) TrackObject(v interface{}) { if !leakDetectionFlag { return } var size int switch v := reflect.ValueOf(v); v.Kind() { case reflect.Ptr: size = int(v.Type().Elem().Size()) case reflect.Array, reflect.Slice, reflect.Chan: size = int(v.Type().Elem().Size()) * v.Cap() case reflect.String: size = v.Len() default: size = int(v.Type().Size()) } runtime.SetFinalizer(c, func(c *RefCount) { if c.NumRef() == 0 { return } origin := getDebuggerRef(c).String() leaks.Lock() // Keep track of bytes leaked, not objects. leaks.m[origin] += uint64(size) leaks.Unlock() }) }
go
func (c *RefCount) TrackObject(v interface{}) { if !leakDetectionFlag { return } var size int switch v := reflect.ValueOf(v); v.Kind() { case reflect.Ptr: size = int(v.Type().Elem().Size()) case reflect.Array, reflect.Slice, reflect.Chan: size = int(v.Type().Elem().Size()) * v.Cap() case reflect.String: size = v.Len() default: size = int(v.Type().Size()) } runtime.SetFinalizer(c, func(c *RefCount) { if c.NumRef() == 0 { return } origin := getDebuggerRef(c).String() leaks.Lock() // Keep track of bytes leaked, not objects. leaks.m[origin] += uint64(size) leaks.Unlock() }) }
[ "func", "(", "c", "*", "RefCount", ")", "TrackObject", "(", "v", "interface", "{", "}", ")", "{", "if", "!", "leakDetectionFlag", "{", "return", "\n", "}", "\n\n", "var", "size", "int", "\n\n", "switch", "v", ":=", "reflect", ".", "ValueOf", "(", "v"...
// TrackObject sets up the initial internal state of the Ref for // leak detection.
[ "TrackObject", "sets", "up", "the", "initial", "internal", "state", "of", "the", "Ref", "for", "leak", "detection", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/checked/ref.go#L159-L189
2,902
m3db/m3x
config/listenaddress/listenaddress.go
Resolve
func (c Configuration) Resolve() (string, error) { listenAddrType := c.ListenAddressType var listenAddress string switch listenAddrType { case ConfigResolver: if c.Value == nil { err := fmt.Errorf("missing listen address value using: resolver=%s", string(listenAddrType)) return "", err } listenAddress = *c.Value case EnvironmentResolver: // environment variable for port is required if c.EnvVarListenPort == nil { err := fmt.Errorf("missing port env var name using: resolver=%s", string(listenAddrType)) return "", err } portStr := os.Getenv(*c.EnvVarListenPort) port, err := strconv.Atoi(portStr) if err != nil { err := fmt.Errorf("invalid port env var value using: resolver=%s, name=%s", string(listenAddrType), *c.EnvVarListenPort) return "", err } // if environment variable for hostname is not set, use the default if c.EnvVarListenHost == nil { listenAddress = fmt.Sprintf("%s:%d", defaultHostname, port) } else { envHost := os.Getenv(*c.EnvVarListenHost) listenAddress = fmt.Sprintf("%s:%d", envHost, port) } default: return "", fmt.Errorf("unknown listen address type: resolver=%s", string(listenAddrType)) } return listenAddress, nil }
go
func (c Configuration) Resolve() (string, error) { listenAddrType := c.ListenAddressType var listenAddress string switch listenAddrType { case ConfigResolver: if c.Value == nil { err := fmt.Errorf("missing listen address value using: resolver=%s", string(listenAddrType)) return "", err } listenAddress = *c.Value case EnvironmentResolver: // environment variable for port is required if c.EnvVarListenPort == nil { err := fmt.Errorf("missing port env var name using: resolver=%s", string(listenAddrType)) return "", err } portStr := os.Getenv(*c.EnvVarListenPort) port, err := strconv.Atoi(portStr) if err != nil { err := fmt.Errorf("invalid port env var value using: resolver=%s, name=%s", string(listenAddrType), *c.EnvVarListenPort) return "", err } // if environment variable for hostname is not set, use the default if c.EnvVarListenHost == nil { listenAddress = fmt.Sprintf("%s:%d", defaultHostname, port) } else { envHost := os.Getenv(*c.EnvVarListenHost) listenAddress = fmt.Sprintf("%s:%d", envHost, port) } default: return "", fmt.Errorf("unknown listen address type: resolver=%s", string(listenAddrType)) } return listenAddress, nil }
[ "func", "(", "c", "Configuration", ")", "Resolve", "(", ")", "(", "string", ",", "error", ")", "{", "listenAddrType", ":=", "c", ".", "ListenAddressType", "\n\n", "var", "listenAddress", "string", "\n", "switch", "listenAddrType", "{", "case", "ConfigResolver"...
// Resolve returns the resolved listen address given the configuration.
[ "Resolve", "returns", "the", "resolved", "listen", "address", "given", "the", "configuration", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/config/listenaddress/listenaddress.go#L62-L103
2,903
m3db/m3x
log/config.go
BuildLogger
func (cfg Configuration) BuildLogger() (Logger, error) { writer := io.Writer(os.Stdout) if cfg.File != "" { fd, err := os.OpenFile(cfg.File, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) if err != nil { return nil, err } writer = io.MultiWriter(writer, fd) } logger := NewLogger(writer) if len(cfg.Level) != 0 { level, err := ParseLevel(cfg.Level) if err != nil { return nil, err } logger = NewLevelLogger(logger, level) } if len(cfg.Fields) != 0 { var fields []Field for k, v := range cfg.Fields { fields = append(fields, NewField(k, v)) } logger = logger.WithFields(fields...) } return logger, nil }
go
func (cfg Configuration) BuildLogger() (Logger, error) { writer := io.Writer(os.Stdout) if cfg.File != "" { fd, err := os.OpenFile(cfg.File, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) if err != nil { return nil, err } writer = io.MultiWriter(writer, fd) } logger := NewLogger(writer) if len(cfg.Level) != 0 { level, err := ParseLevel(cfg.Level) if err != nil { return nil, err } logger = NewLevelLogger(logger, level) } if len(cfg.Fields) != 0 { var fields []Field for k, v := range cfg.Fields { fields = append(fields, NewField(k, v)) } logger = logger.WithFields(fields...) } return logger, nil }
[ "func", "(", "cfg", "Configuration", ")", "BuildLogger", "(", ")", "(", "Logger", ",", "error", ")", "{", "writer", ":=", "io", ".", "Writer", "(", "os", ".", "Stdout", ")", "\n\n", "if", "cfg", ".", "File", "!=", "\"", "\"", "{", "fd", ",", "err...
// BuildLogger builds a new Logger based on the configuration.
[ "BuildLogger", "builds", "a", "new", "Logger", "based", "on", "the", "configuration", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/log/config.go#L36-L68
2,904
m3db/m3x
watch/value.go
NewValue
func NewValue( opts Options, ) Value { v := &value{ opts: opts, log: opts.InstrumentOptions().Logger(), newUpdatableFn: opts.NewUpdatableFn(), getUpdateFn: opts.GetUpdateFn(), processFn: opts.ProcessFn(), } v.processWithLockFn = v.processWithLock return v }
go
func NewValue( opts Options, ) Value { v := &value{ opts: opts, log: opts.InstrumentOptions().Logger(), newUpdatableFn: opts.NewUpdatableFn(), getUpdateFn: opts.GetUpdateFn(), processFn: opts.ProcessFn(), } v.processWithLockFn = v.processWithLock return v }
[ "func", "NewValue", "(", "opts", "Options", ",", ")", "Value", "{", "v", ":=", "&", "value", "{", "opts", ":", "opts", ",", "log", ":", "opts", ".", "InstrumentOptions", "(", ")", ".", "Logger", "(", ")", ",", "newUpdatableFn", ":", "opts", ".", "N...
// NewValue creates a new value.
[ "NewValue", "creates", "a", "new", "value", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/watch/value.go#L80-L92
2,905
m3db/m3x
ident/tag_matcher.go
NewTagMatcher
func NewTagMatcher(name string, value string) TagMatcher { return &tagMatcher{tag: StringTag(name, value)} }
go
func NewTagMatcher(name string, value string) TagMatcher { return &tagMatcher{tag: StringTag(name, value)} }
[ "func", "NewTagMatcher", "(", "name", "string", ",", "value", "string", ")", "TagMatcher", "{", "return", "&", "tagMatcher", "{", "tag", ":", "StringTag", "(", "name", ",", "value", ")", "}", "\n", "}" ]
// NewTagMatcher returns a new TagMatcher
[ "NewTagMatcher", "returns", "a", "new", "TagMatcher" ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/ident/tag_matcher.go#L35-L37
2,906
m3db/m3x
sampler/sampler.go
NewSampler
func NewSampler(sampleRate float64) (*Sampler, error) { if sampleRate <= 0.0 || sampleRate >= 1.0 { return nil, fmt.Errorf("invalid sample rate %f", sampleRate) } return &Sampler{numTried: atomic.NewInt32(0), sampleEvery: int32(1.0 / sampleRate)}, nil }
go
func NewSampler(sampleRate float64) (*Sampler, error) { if sampleRate <= 0.0 || sampleRate >= 1.0 { return nil, fmt.Errorf("invalid sample rate %f", sampleRate) } return &Sampler{numTried: atomic.NewInt32(0), sampleEvery: int32(1.0 / sampleRate)}, nil }
[ "func", "NewSampler", "(", "sampleRate", "float64", ")", "(", "*", "Sampler", ",", "error", ")", "{", "if", "sampleRate", "<=", "0.0", "||", "sampleRate", ">=", "1.0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "sampleRate",...
// NewSampler creates a new sampler with a sample rate.
[ "NewSampler", "creates", "a", "new", "sampler", "with", "a", "sample", "rate", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/sampler/sampler.go#L37-L42
2,907
m3db/m3x
pool/object.go
NewObjectPool
func NewObjectPool(opts ObjectPoolOptions) ObjectPool { if opts == nil { opts = NewObjectPoolOptions() } m := opts.InstrumentOptions().MetricsScope() p := &objectPool{ opts: opts, values: make(chan interface{}, opts.Size()), size: opts.Size(), refillLowWatermark: int(math.Ceil( opts.RefillLowWatermark() * float64(opts.Size()))), refillHighWatermark: int(math.Ceil( opts.RefillHighWatermark() * float64(opts.Size()))), metrics: objectPoolMetrics{ free: m.Gauge("free"), total: m.Gauge("total"), getOnEmpty: m.Counter("get-on-empty"), putOnFull: m.Counter("put-on-full"), }, } p.setGauges() return p }
go
func NewObjectPool(opts ObjectPoolOptions) ObjectPool { if opts == nil { opts = NewObjectPoolOptions() } m := opts.InstrumentOptions().MetricsScope() p := &objectPool{ opts: opts, values: make(chan interface{}, opts.Size()), size: opts.Size(), refillLowWatermark: int(math.Ceil( opts.RefillLowWatermark() * float64(opts.Size()))), refillHighWatermark: int(math.Ceil( opts.RefillHighWatermark() * float64(opts.Size()))), metrics: objectPoolMetrics{ free: m.Gauge("free"), total: m.Gauge("total"), getOnEmpty: m.Counter("get-on-empty"), putOnFull: m.Counter("put-on-full"), }, } p.setGauges() return p }
[ "func", "NewObjectPool", "(", "opts", "ObjectPoolOptions", ")", "ObjectPool", "{", "if", "opts", "==", "nil", "{", "opts", "=", "NewObjectPoolOptions", "(", ")", "\n", "}", "\n\n", "m", ":=", "opts", ".", "InstrumentOptions", "(", ")", ".", "MetricsScope", ...
// NewObjectPool creates a new pool
[ "NewObjectPool", "creates", "a", "new", "pool" ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/pool/object.go#L63-L89
2,908
m3db/m3x
time/range.go
Equal
func (r Range) Equal(other Range) bool { return r.Start.Equal(other.Start) && r.End.Equal(other.End) }
go
func (r Range) Equal(other Range) bool { return r.Start.Equal(other.Start) && r.End.Equal(other.End) }
[ "func", "(", "r", "Range", ")", "Equal", "(", "other", "Range", ")", "bool", "{", "return", "r", ".", "Start", ".", "Equal", "(", "other", ".", "Start", ")", "&&", "r", ".", "End", ".", "Equal", "(", "other", ".", "End", ")", "\n", "}" ]
// Equal returns whether two time ranges are equal.
[ "Equal", "returns", "whether", "two", "time", "ranges", "are", "equal", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/time/range.go#L40-L42
2,909
m3db/m3x
time/range.go
Before
func (r Range) Before(other Range) bool { return !r.End.After(other.Start) }
go
func (r Range) Before(other Range) bool { return !r.End.After(other.Start) }
[ "func", "(", "r", "Range", ")", "Before", "(", "other", "Range", ")", "bool", "{", "return", "!", "r", ".", "End", ".", "After", "(", "other", ".", "Start", ")", "\n", "}" ]
// Before determines whether r is before other.
[ "Before", "determines", "whether", "r", "is", "before", "other", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/time/range.go#L45-L47
2,910
m3db/m3x
time/range.go
Contains
func (r Range) Contains(other Range) bool { return !r.Start.After(other.Start) && !r.End.Before(other.End) }
go
func (r Range) Contains(other Range) bool { return !r.Start.After(other.Start) && !r.End.Before(other.End) }
[ "func", "(", "r", "Range", ")", "Contains", "(", "other", "Range", ")", "bool", "{", "return", "!", "r", ".", "Start", ".", "After", "(", "other", ".", "Start", ")", "&&", "!", "r", ".", "End", ".", "Before", "(", "other", ".", "End", ")", "\n"...
// Contains determines whether r contains other.
[ "Contains", "determines", "whether", "r", "contains", "other", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/time/range.go#L55-L57
2,911
m3db/m3x
time/range.go
Duration
func (r Range) Duration() time.Duration { return r.End.Sub(r.Start) }
go
func (r Range) Duration() time.Duration { return r.End.Sub(r.Start) }
[ "func", "(", "r", "Range", ")", "Duration", "(", ")", "time", ".", "Duration", "{", "return", "r", ".", "End", ".", "Sub", "(", "r", ".", "Start", ")", "\n", "}" ]
// Duration returns the duration of the range.
[ "Duration", "returns", "the", "duration", "of", "the", "range", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/time/range.go#L65-L67
2,912
m3db/m3x
time/range.go
Intersect
func (r Range) Intersect(other Range) (Range, bool) { if !r.Overlaps(other) { return Range{}, false } newRange := r if newRange.Start.Before(other.Start) { newRange.Start = other.Start } if newRange.End.After(other.End) { newRange.End = other.End } return newRange, true }
go
func (r Range) Intersect(other Range) (Range, bool) { if !r.Overlaps(other) { return Range{}, false } newRange := r if newRange.Start.Before(other.Start) { newRange.Start = other.Start } if newRange.End.After(other.End) { newRange.End = other.End } return newRange, true }
[ "func", "(", "r", "Range", ")", "Intersect", "(", "other", "Range", ")", "(", "Range", ",", "bool", ")", "{", "if", "!", "r", ".", "Overlaps", "(", "other", ")", "{", "return", "Range", "{", "}", ",", "false", "\n", "}", "\n", "newRange", ":=", ...
// Intersect calculates the intersection of the receiver range against the // provided argument range iff there is an overlap between the two. It also // returns a bool indicating if there was a valid intersection.
[ "Intersect", "calculates", "the", "intersection", "of", "the", "receiver", "range", "against", "the", "provided", "argument", "range", "iff", "there", "is", "an", "overlap", "between", "the", "two", ".", "It", "also", "returns", "a", "bool", "indicating", "if"...
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/time/range.go#L72-L84
2,913
m3db/m3x
time/range.go
Since
func (r Range) Since(t time.Time) Range { if t.Before(r.Start) { return r } if t.After(r.End) { return Range{} } return Range{Start: t, End: r.End} }
go
func (r Range) Since(t time.Time) Range { if t.Before(r.Start) { return r } if t.After(r.End) { return Range{} } return Range{Start: t, End: r.End} }
[ "func", "(", "r", "Range", ")", "Since", "(", "t", "time", ".", "Time", ")", "Range", "{", "if", "t", ".", "Before", "(", "r", ".", "Start", ")", "{", "return", "r", "\n", "}", "\n", "if", "t", ".", "After", "(", "r", ".", "End", ")", "{", ...
// Since returns the time range since a given point in time.
[ "Since", "returns", "the", "time", "range", "since", "a", "given", "point", "in", "time", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/time/range.go#L87-L95
2,914
m3db/m3x
time/range.go
Merge
func (r Range) Merge(other Range) Range { start := MinTime(r.Start, other.Start) end := MaxTime(r.End, other.End) return Range{Start: start, End: end} }
go
func (r Range) Merge(other Range) Range { start := MinTime(r.Start, other.Start) end := MaxTime(r.End, other.End) return Range{Start: start, End: end} }
[ "func", "(", "r", "Range", ")", "Merge", "(", "other", "Range", ")", "Range", "{", "start", ":=", "MinTime", "(", "r", ".", "Start", ",", "other", ".", "Start", ")", "\n", "end", ":=", "MaxTime", "(", "r", ".", "End", ",", "other", ".", "End", ...
// Merge merges the two ranges if they overlap. Otherwise, // the gap between them is included.
[ "Merge", "merges", "the", "two", "ranges", "if", "they", "overlap", ".", "Otherwise", "the", "gap", "between", "them", "is", "included", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/time/range.go#L99-L103
2,915
m3db/m3x
time/range.go
Subtract
func (r Range) Subtract(other Range) []Range { if !r.Overlaps(other) { return []Range{r} } if other.Contains(r) { return nil } var res []Range left := Range{r.Start, other.Start} right := Range{other.End, r.End} if r.Contains(other) { if !left.IsEmpty() { res = append(res, left) } if !right.IsEmpty() { res = append(res, right) } return res } if !r.Start.After(other.Start) { if !left.IsEmpty() { res = append(res, left) } return res } if !right.IsEmpty() { res = append(res, right) } return res }
go
func (r Range) Subtract(other Range) []Range { if !r.Overlaps(other) { return []Range{r} } if other.Contains(r) { return nil } var res []Range left := Range{r.Start, other.Start} right := Range{other.End, r.End} if r.Contains(other) { if !left.IsEmpty() { res = append(res, left) } if !right.IsEmpty() { res = append(res, right) } return res } if !r.Start.After(other.Start) { if !left.IsEmpty() { res = append(res, left) } return res } if !right.IsEmpty() { res = append(res, right) } return res }
[ "func", "(", "r", "Range", ")", "Subtract", "(", "other", "Range", ")", "[", "]", "Range", "{", "if", "!", "r", ".", "Overlaps", "(", "other", ")", "{", "return", "[", "]", "Range", "{", "r", "}", "\n", "}", "\n", "if", "other", ".", "Contains"...
// Subtract removes the intersection between r and other // from r, possibly splitting r into two smaller ranges.
[ "Subtract", "removes", "the", "intersection", "between", "r", "and", "other", "from", "r", "possibly", "splitting", "r", "into", "two", "smaller", "ranges", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/time/range.go#L107-L136
2,916
m3db/m3x
instrument/invariant.go
EmitAndLogInvariantViolation
func EmitAndLogInvariantViolation(opts Options, f func(l log.Logger)) { EmitInvariantViolation(opts) logger := opts.Logger().WithFields( log.NewField(InvariantViolatedLogFieldName, InvariantViolatedLogFieldValue)) f(logger) panicIfEnvSet() }
go
func EmitAndLogInvariantViolation(opts Options, f func(l log.Logger)) { EmitInvariantViolation(opts) logger := opts.Logger().WithFields( log.NewField(InvariantViolatedLogFieldName, InvariantViolatedLogFieldValue)) f(logger) panicIfEnvSet() }
[ "func", "EmitAndLogInvariantViolation", "(", "opts", "Options", ",", "f", "func", "(", "l", "log", ".", "Logger", ")", ")", "{", "EmitInvariantViolation", "(", "opts", ")", "\n\n", "logger", ":=", "opts", ".", "Logger", "(", ")", ".", "WithFields", "(", ...
// EmitAndLogInvariantViolation calls EmitInvariantViolation and then calls the provided function // with a supplied logger that is pre-configured with an invariant violated field. Optionally panics // if the ShouldPanicEnvironmentVariableName is set to "true".
[ "EmitAndLogInvariantViolation", "calls", "EmitInvariantViolation", "and", "then", "calls", "the", "provided", "function", "with", "a", "supplied", "logger", "that", "is", "pre", "-", "configured", "with", "an", "invariant", "violated", "field", ".", "Optionally", "p...
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/instrument/invariant.go#L71-L79
2,917
m3db/m3x
instrument/invariant.go
InvariantErrorf
func InvariantErrorf(format string, a ...interface{}) error { var ( invariantFormat = InvariantViolatedMetricName + ": " + format err = fmt.Errorf(invariantFormat, a...) ) panicIfEnvSetWithMessage(err.Error()) return err }
go
func InvariantErrorf(format string, a ...interface{}) error { var ( invariantFormat = InvariantViolatedMetricName + ": " + format err = fmt.Errorf(invariantFormat, a...) ) panicIfEnvSetWithMessage(err.Error()) return err }
[ "func", "InvariantErrorf", "(", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "error", "{", "var", "(", "invariantFormat", "=", "InvariantViolatedMetricName", "+", "\"", "\"", "+", "format", "\n", "err", "=", "fmt", ".", "Errorf", "(", ...
// InvariantErrorf constructs a new error, prefixed with a string indicating that an invariant // violation occurred. Optionally panics if the ShouldPanicEnvironmentVariableName is set to "true".
[ "InvariantErrorf", "constructs", "a", "new", "error", "prefixed", "with", "a", "string", "indicating", "that", "an", "invariant", "violation", "occurred", ".", "Optionally", "panics", "if", "the", "ShouldPanicEnvironmentVariableName", "is", "set", "to", "true", "." ...
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/instrument/invariant.go#L83-L91
2,918
m3db/m3x
time/time.go
ToNormalizedTime
func ToNormalizedTime(t time.Time, u time.Duration) int64 { return t.UnixNano() / u.Nanoseconds() }
go
func ToNormalizedTime(t time.Time, u time.Duration) int64 { return t.UnixNano() / u.Nanoseconds() }
[ "func", "ToNormalizedTime", "(", "t", "time", ".", "Time", ",", "u", "time", ".", "Duration", ")", "int64", "{", "return", "t", ".", "UnixNano", "(", ")", "/", "u", ".", "Nanoseconds", "(", ")", "\n", "}" ]
// ToNormalizedTime returns the normalized units of time given a time unit.
[ "ToNormalizedTime", "returns", "the", "normalized", "units", "of", "time", "given", "a", "time", "unit", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/time/time.go#L31-L33
2,919
m3db/m3x
time/time.go
FromNormalizedTime
func FromNormalizedTime(nt int64, u time.Duration) time.Time { return time.Unix(0, int64(u/time.Nanosecond)*nt) }
go
func FromNormalizedTime(nt int64, u time.Duration) time.Time { return time.Unix(0, int64(u/time.Nanosecond)*nt) }
[ "func", "FromNormalizedTime", "(", "nt", "int64", ",", "u", "time", ".", "Duration", ")", "time", ".", "Time", "{", "return", "time", ".", "Unix", "(", "0", ",", "int64", "(", "u", "/", "time", ".", "Nanosecond", ")", "*", "nt", ")", "\n", "}" ]
// FromNormalizedTime returns the time given the normalized time units and the time unit.
[ "FromNormalizedTime", "returns", "the", "time", "given", "the", "normalized", "time", "units", "and", "the", "time", "unit", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/time/time.go#L36-L38
2,920
m3db/m3x
time/time.go
ToNormalizedDuration
func ToNormalizedDuration(d time.Duration, u time.Duration) int64 { return int64(d / u) }
go
func ToNormalizedDuration(d time.Duration, u time.Duration) int64 { return int64(d / u) }
[ "func", "ToNormalizedDuration", "(", "d", "time", ".", "Duration", ",", "u", "time", ".", "Duration", ")", "int64", "{", "return", "int64", "(", "d", "/", "u", ")", "\n", "}" ]
// ToNormalizedDuration returns the normalized units of duration given a time unit.
[ "ToNormalizedDuration", "returns", "the", "normalized", "units", "of", "duration", "given", "a", "time", "unit", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/time/time.go#L41-L43
2,921
m3db/m3x
time/time.go
FromNormalizedDuration
func FromNormalizedDuration(nd int64, u time.Duration) time.Duration { return time.Duration(nd) * u }
go
func FromNormalizedDuration(nd int64, u time.Duration) time.Duration { return time.Duration(nd) * u }
[ "func", "FromNormalizedDuration", "(", "nd", "int64", ",", "u", "time", ".", "Duration", ")", "time", ".", "Duration", "{", "return", "time", ".", "Duration", "(", "nd", ")", "*", "u", "\n", "}" ]
// FromNormalizedDuration returns the duration given the normalized time duration and a time unit.
[ "FromNormalizedDuration", "returns", "the", "duration", "given", "the", "normalized", "time", "duration", "and", "a", "time", "unit", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/time/time.go#L46-L48
2,922
m3db/m3x
time/time.go
Ceil
func Ceil(t time.Time, d time.Duration) time.Time { res := t.Truncate(d) if res.Before(t) { res = res.Add(d) } return res }
go
func Ceil(t time.Time, d time.Duration) time.Time { res := t.Truncate(d) if res.Before(t) { res = res.Add(d) } return res }
[ "func", "Ceil", "(", "t", "time", ".", "Time", ",", "d", "time", ".", "Duration", ")", "time", ".", "Time", "{", "res", ":=", "t", ".", "Truncate", "(", "d", ")", "\n", "if", "res", ".", "Before", "(", "t", ")", "{", "res", "=", "res", ".", ...
// Ceil returns the result of rounding t up to a multiple of d since // the zero time.
[ "Ceil", "returns", "the", "result", "of", "rounding", "t", "up", "to", "a", "multiple", "of", "d", "since", "the", "zero", "time", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/time/time.go#L72-L78
2,923
m3db/m3x
time/time.go
MinTime
func MinTime(t1, t2 time.Time) time.Time { if t1.Before(t2) { return t1 } return t2 }
go
func MinTime(t1, t2 time.Time) time.Time { if t1.Before(t2) { return t1 } return t2 }
[ "func", "MinTime", "(", "t1", ",", "t2", "time", ".", "Time", ")", "time", ".", "Time", "{", "if", "t1", ".", "Before", "(", "t2", ")", "{", "return", "t1", "\n", "}", "\n", "return", "t2", "\n", "}" ]
// MinTime returns the earlier one of t1 and t2.
[ "MinTime", "returns", "the", "earlier", "one", "of", "t1", "and", "t2", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/time/time.go#L81-L86
2,924
m3db/m3x
time/time.go
MaxTime
func MaxTime(t1, t2 time.Time) time.Time { if t1.After(t2) { return t1 } return t2 }
go
func MaxTime(t1, t2 time.Time) time.Time { if t1.After(t2) { return t1 } return t2 }
[ "func", "MaxTime", "(", "t1", ",", "t2", "time", ".", "Time", ")", "time", ".", "Time", "{", "if", "t1", ".", "After", "(", "t2", ")", "{", "return", "t1", "\n", "}", "\n", "return", "t2", "\n", "}" ]
// MaxTime returns the later one of t1 and t2.
[ "MaxTime", "returns", "the", "later", "one", "of", "t1", "and", "t2", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/time/time.go#L89-L94
2,925
m3db/m3x
pool/bucketized.go
NewBucketizedObjectPool
func NewBucketizedObjectPool(sizes []Bucket, opts ObjectPoolOptions) BucketizedObjectPool { if opts == nil { opts = NewObjectPoolOptions() } sizesAsc := make([]Bucket, len(sizes)) copy(sizesAsc, sizes) sort.Sort(BucketByCapacity(sizesAsc)) var maxBucketCapacity int if len(sizesAsc) != 0 { maxBucketCapacity = sizesAsc[len(sizesAsc)-1].Capacity } iopts := opts.InstrumentOptions() return &bucketizedObjectPool{ opts: opts, sizesAsc: sizesAsc, maxBucketCapacity: maxBucketCapacity, maxAlloc: iopts.MetricsScope().Counter("alloc-max"), } }
go
func NewBucketizedObjectPool(sizes []Bucket, opts ObjectPoolOptions) BucketizedObjectPool { if opts == nil { opts = NewObjectPoolOptions() } sizesAsc := make([]Bucket, len(sizes)) copy(sizesAsc, sizes) sort.Sort(BucketByCapacity(sizesAsc)) var maxBucketCapacity int if len(sizesAsc) != 0 { maxBucketCapacity = sizesAsc[len(sizesAsc)-1].Capacity } iopts := opts.InstrumentOptions() return &bucketizedObjectPool{ opts: opts, sizesAsc: sizesAsc, maxBucketCapacity: maxBucketCapacity, maxAlloc: iopts.MetricsScope().Counter("alloc-max"), } }
[ "func", "NewBucketizedObjectPool", "(", "sizes", "[", "]", "Bucket", ",", "opts", "ObjectPoolOptions", ")", "BucketizedObjectPool", "{", "if", "opts", "==", "nil", "{", "opts", "=", "NewObjectPoolOptions", "(", ")", "\n", "}", "\n\n", "sizesAsc", ":=", "make",...
// NewBucketizedObjectPool creates a bucketized object pool
[ "NewBucketizedObjectPool", "creates", "a", "bucketized", "object", "pool" ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/pool/bucketized.go#L45-L67
2,926
m3db/m3x
config/config.go
LoadFile
func LoadFile(config interface{}, file string, opts Options) error { return LoadFiles(config, []string{file}, opts) }
go
func LoadFile(config interface{}, file string, opts Options) error { return LoadFiles(config, []string{file}, opts) }
[ "func", "LoadFile", "(", "config", "interface", "{", "}", ",", "file", "string", ",", "opts", "Options", ")", "error", "{", "return", "LoadFiles", "(", "config", ",", "[", "]", "string", "{", "file", "}", ",", "opts", ")", "\n", "}" ]
// LoadFile loads a config from a file.
[ "LoadFile", "loads", "a", "config", "from", "a", "file", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/config/config.go#L41-L43
2,927
m3db/m3x
config/config.go
LoadFiles
func LoadFiles(config interface{}, files []string, opts Options) error { if len(files) == 0 { return errNoFilesToLoad } for _, name := range files { data, err := ioutil.ReadFile(name) if err != nil { return err } unmarshal := yaml.UnmarshalStrict if opts.DisableUnmarshalStrict { unmarshal = yaml.Unmarshal } if err := unmarshal(data, config); err != nil { return err } } if opts.DisableValidate { return nil } return validator.Validate(config) }
go
func LoadFiles(config interface{}, files []string, opts Options) error { if len(files) == 0 { return errNoFilesToLoad } for _, name := range files { data, err := ioutil.ReadFile(name) if err != nil { return err } unmarshal := yaml.UnmarshalStrict if opts.DisableUnmarshalStrict { unmarshal = yaml.Unmarshal } if err := unmarshal(data, config); err != nil { return err } } if opts.DisableValidate { return nil } return validator.Validate(config) }
[ "func", "LoadFiles", "(", "config", "interface", "{", "}", ",", "files", "[", "]", "string", ",", "opts", "Options", ")", "error", "{", "if", "len", "(", "files", ")", "==", "0", "{", "return", "errNoFilesToLoad", "\n", "}", "\n", "for", "_", ",", ...
// LoadFiles loads a config from list of files. If value for a property is // present in multiple files, the value from the last file will be applied. // Validation is done after merging all values.
[ "LoadFiles", "loads", "a", "config", "from", "list", "of", "files", ".", "If", "value", "for", "a", "property", "is", "present", "in", "multiple", "files", "the", "value", "from", "the", "last", "file", "will", "be", "applied", ".", "Validation", "is", "...
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/config/config.go#L48-L69
2,928
m3db/m3x
retry/retry.go
NewRetrier
func NewRetrier(opts Options) Retrier { scope := opts.MetricsScope() errorTags := struct { retryable map[string]string notRetryable map[string]string }{ map[string]string{ "type": "retryable", }, map[string]string{ "type": "not-retryable", }, } return &retrier{ initialBackoff: opts.InitialBackoff(), backoffFactor: opts.BackoffFactor(), maxBackoff: opts.MaxBackoff(), maxRetries: opts.MaxRetries(), forever: opts.Forever(), jitter: opts.Jitter(), rngFn: opts.RngFn(), sleepFn: time.Sleep, metrics: retrierMetrics{ success: scope.Counter("success"), successLatency: scope.Timer("success-latency"), errors: scope.Tagged(errorTags.retryable).Counter("errors"), errorsNotRetryable: scope.Tagged(errorTags.notRetryable).Counter("errors"), errorsFinal: scope.Counter("errors-final"), errorsLatency: scope.Timer("errors-latency"), retries: scope.Counter("retries"), }, } }
go
func NewRetrier(opts Options) Retrier { scope := opts.MetricsScope() errorTags := struct { retryable map[string]string notRetryable map[string]string }{ map[string]string{ "type": "retryable", }, map[string]string{ "type": "not-retryable", }, } return &retrier{ initialBackoff: opts.InitialBackoff(), backoffFactor: opts.BackoffFactor(), maxBackoff: opts.MaxBackoff(), maxRetries: opts.MaxRetries(), forever: opts.Forever(), jitter: opts.Jitter(), rngFn: opts.RngFn(), sleepFn: time.Sleep, metrics: retrierMetrics{ success: scope.Counter("success"), successLatency: scope.Timer("success-latency"), errors: scope.Tagged(errorTags.retryable).Counter("errors"), errorsNotRetryable: scope.Tagged(errorTags.notRetryable).Counter("errors"), errorsFinal: scope.Counter("errors-final"), errorsLatency: scope.Timer("errors-latency"), retries: scope.Counter("retries"), }, } }
[ "func", "NewRetrier", "(", "opts", "Options", ")", "Retrier", "{", "scope", ":=", "opts", ".", "MetricsScope", "(", ")", "\n", "errorTags", ":=", "struct", "{", "retryable", "map", "[", "string", "]", "string", "\n", "notRetryable", "map", "[", "string", ...
// NewRetrier creates a new retrier.
[ "NewRetrier", "creates", "a", "new", "retrier", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/retry/retry.go#L62-L94
2,929
m3db/m3x
retry/retry.go
BackoffNanos
func BackoffNanos( retry int, jitter bool, backoffFactor float64, initialBackoff time.Duration, maxBackoff time.Duration, rngFn RngFn, ) int64 { backoff := initialBackoff.Nanoseconds() if retry >= 1 { backoffFloat64 := float64(backoff) * math.Pow(backoffFactor, float64(retry-1)) // math.Inf is also larger than math.MaxInt64. if backoffFloat64 > math.MaxInt64 { return maxBackoff.Nanoseconds() } backoff = int64(backoffFloat64) } // Validate the value of backoff to make sure Int63n() does not panic. if jitter && backoff >= 2 { half := backoff / 2 backoff = half + rngFn(half) } if maxBackoff := maxBackoff.Nanoseconds(); backoff > maxBackoff { backoff = maxBackoff } return backoff }
go
func BackoffNanos( retry int, jitter bool, backoffFactor float64, initialBackoff time.Duration, maxBackoff time.Duration, rngFn RngFn, ) int64 { backoff := initialBackoff.Nanoseconds() if retry >= 1 { backoffFloat64 := float64(backoff) * math.Pow(backoffFactor, float64(retry-1)) // math.Inf is also larger than math.MaxInt64. if backoffFloat64 > math.MaxInt64 { return maxBackoff.Nanoseconds() } backoff = int64(backoffFloat64) } // Validate the value of backoff to make sure Int63n() does not panic. if jitter && backoff >= 2 { half := backoff / 2 backoff = half + rngFn(half) } if maxBackoff := maxBackoff.Nanoseconds(); backoff > maxBackoff { backoff = maxBackoff } return backoff }
[ "func", "BackoffNanos", "(", "retry", "int", ",", "jitter", "bool", ",", "backoffFactor", "float64", ",", "initialBackoff", "time", ".", "Duration", ",", "maxBackoff", "time", ".", "Duration", ",", "rngFn", "RngFn", ",", ")", "int64", "{", "backoff", ":=", ...
// BackoffNanos calculates the backoff for a retry in nanoseconds.
[ "BackoffNanos", "calculates", "the", "backoff", "for", "a", "retry", "in", "nanoseconds", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/retry/retry.go#L164-L190
2,930
m3db/m3x
time/range_iter.go
Next
func (it *RangeIter) Next() bool { if it.ranges == nil { return false } if it.cur == nil { it.cur = it.ranges.Front() } else { it.cur = it.cur.Next() } return it.cur != nil }
go
func (it *RangeIter) Next() bool { if it.ranges == nil { return false } if it.cur == nil { it.cur = it.ranges.Front() } else { it.cur = it.cur.Next() } return it.cur != nil }
[ "func", "(", "it", "*", "RangeIter", ")", "Next", "(", ")", "bool", "{", "if", "it", ".", "ranges", "==", "nil", "{", "return", "false", "\n", "}", "\n", "if", "it", ".", "cur", "==", "nil", "{", "it", ".", "cur", "=", "it", ".", "ranges", "....
// Next moves to the next item.
[ "Next", "moves", "to", "the", "next", "item", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/time/range_iter.go#L36-L46
2,931
m3db/m3x
time/range_iter.go
Value
func (it *RangeIter) Value() Range { if it.cur == nil { return Range{} } return it.cur.Value.(Range) }
go
func (it *RangeIter) Value() Range { if it.cur == nil { return Range{} } return it.cur.Value.(Range) }
[ "func", "(", "it", "*", "RangeIter", ")", "Value", "(", ")", "Range", "{", "if", "it", ".", "cur", "==", "nil", "{", "return", "Range", "{", "}", "\n", "}", "\n", "return", "it", ".", "cur", ".", "Value", ".", "(", "Range", ")", "\n", "}" ]
// Value returns the current time range.
[ "Value", "returns", "the", "current", "time", "range", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/time/range_iter.go#L49-L54
2,932
m3db/m3x
instrument/methods.go
NewSampledTimer
func NewSampledTimer(base tally.Timer, rate float64) (tally.Timer, error) { if rate <= 0.0 || rate > 1.0 { return nil, fmt.Errorf("sampling rate %f must be between 0.0 and 1.0", rate) } return &sampledTimer{ Timer: base, rate: uint64(1.0 / rate), }, nil }
go
func NewSampledTimer(base tally.Timer, rate float64) (tally.Timer, error) { if rate <= 0.0 || rate > 1.0 { return nil, fmt.Errorf("sampling rate %f must be between 0.0 and 1.0", rate) } return &sampledTimer{ Timer: base, rate: uint64(1.0 / rate), }, nil }
[ "func", "NewSampledTimer", "(", "base", "tally", ".", "Timer", ",", "rate", "float64", ")", "(", "tally", ".", "Timer", ",", "error", ")", "{", "if", "rate", "<=", "0.0", "||", "rate", ">", "1.0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(...
// NewSampledTimer creates a new sampled timer.
[ "NewSampledTimer", "creates", "a", "new", "sampled", "timer", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/instrument/methods.go#L45-L53
2,933
m3db/m3x
instrument/methods.go
MustCreateSampledTimer
func MustCreateSampledTimer(base tally.Timer, rate float64) tally.Timer { t, err := NewSampledTimer(base, rate) if err != nil { panic(err) } return t }
go
func MustCreateSampledTimer(base tally.Timer, rate float64) tally.Timer { t, err := NewSampledTimer(base, rate) if err != nil { panic(err) } return t }
[ "func", "MustCreateSampledTimer", "(", "base", "tally", ".", "Timer", ",", "rate", "float64", ")", "tally", ".", "Timer", "{", "t", ",", "err", ":=", "NewSampledTimer", "(", "base", ",", "rate", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", ...
// MustCreateSampledTimer creates a new sampled timer, and panics if an error // is encountered.
[ "MustCreateSampledTimer", "creates", "a", "new", "sampled", "timer", "and", "panics", "if", "an", "error", "is", "encountered", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/instrument/methods.go#L57-L63
2,934
m3db/m3x
instrument/methods.go
ReportSuccess
func (m *MethodMetrics) ReportSuccess(d time.Duration) { m.Success.Inc(1) m.SuccessLatency.Record(d) }
go
func (m *MethodMetrics) ReportSuccess(d time.Duration) { m.Success.Inc(1) m.SuccessLatency.Record(d) }
[ "func", "(", "m", "*", "MethodMetrics", ")", "ReportSuccess", "(", "d", "time", ".", "Duration", ")", "{", "m", ".", "Success", ".", "Inc", "(", "1", ")", "\n", "m", ".", "SuccessLatency", ".", "Record", "(", "d", ")", "\n", "}" ]
// ReportSuccess reports a success.
[ "ReportSuccess", "reports", "a", "success", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/instrument/methods.go#L100-L103
2,935
m3db/m3x
instrument/methods.go
ReportError
func (m *MethodMetrics) ReportError(d time.Duration) { m.Errors.Inc(1) m.ErrorsLatency.Record(d) }
go
func (m *MethodMetrics) ReportError(d time.Duration) { m.Errors.Inc(1) m.ErrorsLatency.Record(d) }
[ "func", "(", "m", "*", "MethodMetrics", ")", "ReportError", "(", "d", "time", ".", "Duration", ")", "{", "m", ".", "Errors", ".", "Inc", "(", "1", ")", "\n", "m", ".", "ErrorsLatency", ".", "Record", "(", "d", ")", "\n", "}" ]
// ReportError reports an error.
[ "ReportError", "reports", "an", "error", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/instrument/methods.go#L106-L109
2,936
m3db/m3x
instrument/methods.go
NewMethodMetrics
func NewMethodMetrics(scope tally.Scope, methodName string, samplingRate float64) MethodMetrics { return MethodMetrics{ Errors: scope.Counter(methodName + ".errors"), Success: scope.Counter(methodName + ".success"), ErrorsLatency: MustCreateSampledTimer(scope.Timer(methodName+".errors-latency"), samplingRate), SuccessLatency: MustCreateSampledTimer(scope.Timer(methodName+".success-latency"), samplingRate), } }
go
func NewMethodMetrics(scope tally.Scope, methodName string, samplingRate float64) MethodMetrics { return MethodMetrics{ Errors: scope.Counter(methodName + ".errors"), Success: scope.Counter(methodName + ".success"), ErrorsLatency: MustCreateSampledTimer(scope.Timer(methodName+".errors-latency"), samplingRate), SuccessLatency: MustCreateSampledTimer(scope.Timer(methodName+".success-latency"), samplingRate), } }
[ "func", "NewMethodMetrics", "(", "scope", "tally", ".", "Scope", ",", "methodName", "string", ",", "samplingRate", "float64", ")", "MethodMetrics", "{", "return", "MethodMetrics", "{", "Errors", ":", "scope", ".", "Counter", "(", "methodName", "+", "\"", "\"",...
// NewMethodMetrics returns a new Method metrics for the given method name.
[ "NewMethodMetrics", "returns", "a", "new", "Method", "metrics", "for", "the", "given", "method", "name", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/instrument/methods.go#L121-L128
2,937
m3db/m3x
instrument/methods.go
NewBatchMethodMetrics
func NewBatchMethodMetrics( scope tally.Scope, methodName string, samplingRate float64, ) BatchMethodMetrics { return BatchMethodMetrics{ RetryableErrors: scope.Counter(methodName + ".retryable-errors"), NonRetryableErrors: scope.Counter(methodName + ".non-retryable-errors"), Errors: scope.Counter(methodName + ".errors"), Success: scope.Counter(methodName + ".success"), Latency: MustCreateSampledTimer(scope.Timer(methodName+".latency"), samplingRate), } }
go
func NewBatchMethodMetrics( scope tally.Scope, methodName string, samplingRate float64, ) BatchMethodMetrics { return BatchMethodMetrics{ RetryableErrors: scope.Counter(methodName + ".retryable-errors"), NonRetryableErrors: scope.Counter(methodName + ".non-retryable-errors"), Errors: scope.Counter(methodName + ".errors"), Success: scope.Counter(methodName + ".success"), Latency: MustCreateSampledTimer(scope.Timer(methodName+".latency"), samplingRate), } }
[ "func", "NewBatchMethodMetrics", "(", "scope", "tally", ".", "Scope", ",", "methodName", "string", ",", "samplingRate", "float64", ",", ")", "BatchMethodMetrics", "{", "return", "BatchMethodMetrics", "{", "RetryableErrors", ":", "scope", ".", "Counter", "(", "meth...
// NewBatchMethodMetrics creates new batch method metrics.
[ "NewBatchMethodMetrics", "creates", "new", "batch", "method", "metrics", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/instrument/methods.go#L140-L152
2,938
m3db/m3x
instrument/methods.go
ReportSuccess
func (m *BatchMethodMetrics) ReportSuccess(n int) { m.Success.Inc(int64(n)) }
go
func (m *BatchMethodMetrics) ReportSuccess(n int) { m.Success.Inc(int64(n)) }
[ "func", "(", "m", "*", "BatchMethodMetrics", ")", "ReportSuccess", "(", "n", "int", ")", "{", "m", ".", "Success", ".", "Inc", "(", "int64", "(", "n", ")", ")", "\n", "}" ]
// ReportSuccess reports successess.
[ "ReportSuccess", "reports", "successess", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/instrument/methods.go#L155-L157
2,939
m3db/m3x
instrument/methods.go
ReportRetryableErrors
func (m *BatchMethodMetrics) ReportRetryableErrors(n int) { m.RetryableErrors.Inc(int64(n)) m.Errors.Inc(int64(n)) }
go
func (m *BatchMethodMetrics) ReportRetryableErrors(n int) { m.RetryableErrors.Inc(int64(n)) m.Errors.Inc(int64(n)) }
[ "func", "(", "m", "*", "BatchMethodMetrics", ")", "ReportRetryableErrors", "(", "n", "int", ")", "{", "m", ".", "RetryableErrors", ".", "Inc", "(", "int64", "(", "n", ")", ")", "\n", "m", ".", "Errors", ".", "Inc", "(", "int64", "(", "n", ")", ")",...
// ReportRetryableErrors reports retryable errors.
[ "ReportRetryableErrors", "reports", "retryable", "errors", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/instrument/methods.go#L160-L163
2,940
m3db/m3x
instrument/methods.go
ReportNonRetryableErrors
func (m *BatchMethodMetrics) ReportNonRetryableErrors(n int) { m.NonRetryableErrors.Inc(int64(n)) m.Errors.Inc(int64(n)) }
go
func (m *BatchMethodMetrics) ReportNonRetryableErrors(n int) { m.NonRetryableErrors.Inc(int64(n)) m.Errors.Inc(int64(n)) }
[ "func", "(", "m", "*", "BatchMethodMetrics", ")", "ReportNonRetryableErrors", "(", "n", "int", ")", "{", "m", ".", "NonRetryableErrors", ".", "Inc", "(", "int64", "(", "n", ")", ")", "\n", "m", ".", "Errors", ".", "Inc", "(", "int64", "(", "n", ")", ...
// ReportNonRetryableErrors reports non-retryable errors.
[ "ReportNonRetryableErrors", "reports", "non", "-", "retryable", "errors", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/instrument/methods.go#L166-L169
2,941
m3db/m3x
instrument/methods.go
ReportLatency
func (m *BatchMethodMetrics) ReportLatency(d time.Duration) { m.Latency.Record(d) }
go
func (m *BatchMethodMetrics) ReportLatency(d time.Duration) { m.Latency.Record(d) }
[ "func", "(", "m", "*", "BatchMethodMetrics", ")", "ReportLatency", "(", "d", "time", ".", "Duration", ")", "{", "m", ".", "Latency", ".", "Record", "(", "d", ")", "\n", "}" ]
// ReportLatency reports latency.
[ "ReportLatency", "reports", "latency", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/instrument/methods.go#L172-L174
2,942
m3db/m3x
watch/source.go
NewSource
func NewSource(input SourceInput, logger log.Logger) Source { s := &source{ input: input, w: NewWatchable(), logger: logger, } go s.run() return s }
go
func NewSource(input SourceInput, logger log.Logger) Source { s := &source{ input: input, w: NewWatchable(), logger: logger, } go s.run() return s }
[ "func", "NewSource", "(", "input", "SourceInput", ",", "logger", "log", ".", "Logger", ")", "Source", "{", "s", ":=", "&", "source", "{", "input", ":", "input", ",", "w", ":", "NewWatchable", "(", ")", ",", "logger", ":", "logger", ",", "}", "\n\n", ...
// NewSource returns a new Source.
[ "NewSource", "returns", "a", "new", "Source", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/watch/source.go#L53-L62
2,943
m3db/m3x
log/logger.go
NewLogger
func NewLogger(writer io.Writer, fields ...Field) Logger { return &writerLogger{writer, Fields(fields)} }
go
func NewLogger(writer io.Writer, fields ...Field) Logger { return &writerLogger{writer, Fields(fields)} }
[ "func", "NewLogger", "(", "writer", "io", ".", "Writer", ",", "fields", "...", "Field", ")", "Logger", "{", "return", "&", "writerLogger", "{", "writer", ",", "Fields", "(", "fields", ")", "}", "\n", "}" ]
// NewLogger returns a Logger that writes to the given writer.
[ "NewLogger", "returns", "a", "Logger", "that", "writes", "to", "the", "given", "writer", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/log/logger.go#L155-L157
2,944
m3db/m3x
log/logger.go
ParseLevel
func ParseLevel(level string) (Level, error) { level = strings.ToLower(level) for _, l := range levels { if strings.ToLower(l.String()) == level { return l, nil } } return Level(0), fmt.Errorf("unrecognized log level: %s", level) }
go
func ParseLevel(level string) (Level, error) { level = strings.ToLower(level) for _, l := range levels { if strings.ToLower(l.String()) == level { return l, nil } } return Level(0), fmt.Errorf("unrecognized log level: %s", level) }
[ "func", "ParseLevel", "(", "level", "string", ")", "(", "Level", ",", "error", ")", "{", "level", "=", "strings", ".", "ToLower", "(", "level", ")", "\n", "for", "_", ",", "l", ":=", "range", "levels", "{", "if", "strings", ".", "ToLower", "(", "l"...
// ParseLevel parses a log level string to log level.
[ "ParseLevel", "parses", "a", "log", "level", "string", "to", "log", "level", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/log/logger.go#L243-L251
2,945
m3db/m3x
clock/types.go
WaitUntil
func WaitUntil(fn ConditionFn, timeout time.Duration) bool { deadline := time.Now().Add(timeout) for time.Now().Before(deadline) { if fn() { return true } time.Sleep(100 * time.Millisecond) } return false }
go
func WaitUntil(fn ConditionFn, timeout time.Duration) bool { deadline := time.Now().Add(timeout) for time.Now().Before(deadline) { if fn() { return true } time.Sleep(100 * time.Millisecond) } return false }
[ "func", "WaitUntil", "(", "fn", "ConditionFn", ",", "timeout", "time", ".", "Duration", ")", "bool", "{", "deadline", ":=", "time", ".", "Now", "(", ")", ".", "Add", "(", "timeout", ")", "\n", "for", "time", ".", "Now", "(", ")", ".", "Before", "("...
// WaitUntil returns true if the condition specified evaluated to // true before the timeout, false otherwise.
[ "WaitUntil", "returns", "true", "if", "the", "condition", "specified", "evaluated", "to", "true", "before", "the", "timeout", "false", "otherwise", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/clock/types.go#L61-L70
2,946
m3db/m3x
net/server.go
StartAcceptLoop
func StartAcceptLoop(l net.Listener, rOpts retry.Options) (<-chan net.Conn, <-chan error) { var ( connCh = make(chan net.Conn) errCh = make(chan error) retrier = retry.NewRetrier(rOpts) ) go func() { defer l.Close() for { var conn net.Conn if err := retrier.Attempt(func() error { var connErr error conn, connErr = l.Accept() if connErr == nil { return nil } // If the error is a temporary network error, we consider it retryable. if ne, ok := connErr.(net.Error); ok && ne.Temporary() { return ne } // Otherwise it's a non-retryable error. return errors.NewNonRetryableError(connErr) }); err != nil { close(connCh) errCh <- err close(errCh) return } connCh <- conn } }() return connCh, errCh }
go
func StartAcceptLoop(l net.Listener, rOpts retry.Options) (<-chan net.Conn, <-chan error) { var ( connCh = make(chan net.Conn) errCh = make(chan error) retrier = retry.NewRetrier(rOpts) ) go func() { defer l.Close() for { var conn net.Conn if err := retrier.Attempt(func() error { var connErr error conn, connErr = l.Accept() if connErr == nil { return nil } // If the error is a temporary network error, we consider it retryable. if ne, ok := connErr.(net.Error); ok && ne.Temporary() { return ne } // Otherwise it's a non-retryable error. return errors.NewNonRetryableError(connErr) }); err != nil { close(connCh) errCh <- err close(errCh) return } connCh <- conn } }() return connCh, errCh }
[ "func", "StartAcceptLoop", "(", "l", "net", ".", "Listener", ",", "rOpts", "retry", ".", "Options", ")", "(", "<-", "chan", "net", ".", "Conn", ",", "<-", "chan", "error", ")", "{", "var", "(", "connCh", "=", "make", "(", "chan", "net", ".", "Conn"...
// StartAcceptLoop starts an accept loop for the given listener, // returning accepted connections via a channel while handling // temporary network errors. Fatal errors are returned via the // error channel with the listener closed on return.
[ "StartAcceptLoop", "starts", "an", "accept", "loop", "for", "the", "given", "listener", "returning", "accepted", "connections", "via", "a", "channel", "while", "handling", "temporary", "network", "errors", ".", "Fatal", "errors", "are", "returned", "via", "the", ...
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/net/server.go#L35-L70
2,947
m3db/m3x
net/server.go
StartForeverAcceptLoop
func StartForeverAcceptLoop(l net.Listener, rOpts retry.Options) (<-chan net.Conn, <-chan error) { return StartAcceptLoop(l, rOpts.SetForever(true)) }
go
func StartForeverAcceptLoop(l net.Listener, rOpts retry.Options) (<-chan net.Conn, <-chan error) { return StartAcceptLoop(l, rOpts.SetForever(true)) }
[ "func", "StartForeverAcceptLoop", "(", "l", "net", ".", "Listener", ",", "rOpts", "retry", ".", "Options", ")", "(", "<-", "chan", "net", ".", "Conn", ",", "<-", "chan", "error", ")", "{", "return", "StartAcceptLoop", "(", "l", ",", "rOpts", ".", "SetF...
// StartForeverAcceptLoop starts an accept loop for the // given listener that retries forever, returning // accepted connections via a channel while handling // temporary network errors. Fatal errors are returned via the // error channel with the listener closed on return.
[ "StartForeverAcceptLoop", "starts", "an", "accept", "loop", "for", "the", "given", "listener", "that", "retries", "forever", "returning", "accepted", "connections", "via", "a", "channel", "while", "handling", "temporary", "network", "errors", ".", "Fatal", "errors",...
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/net/server.go#L77-L79
2,948
m3db/m3x
pool/options.go
NewObjectPoolOptions
func NewObjectPoolOptions() ObjectPoolOptions { return &objectPoolOptions{ size: defaultSize, refillLowWatermark: defaultRefillLowWatermark, refillHighWatermark: defaultRefillHighWatermark, instrumentOpts: instrument.NewOptions(), onPoolAccessErrorFn: func(err error) { panic(err) }, } }
go
func NewObjectPoolOptions() ObjectPoolOptions { return &objectPoolOptions{ size: defaultSize, refillLowWatermark: defaultRefillLowWatermark, refillHighWatermark: defaultRefillHighWatermark, instrumentOpts: instrument.NewOptions(), onPoolAccessErrorFn: func(err error) { panic(err) }, } }
[ "func", "NewObjectPoolOptions", "(", ")", "ObjectPoolOptions", "{", "return", "&", "objectPoolOptions", "{", "size", ":", "defaultSize", ",", "refillLowWatermark", ":", "defaultRefillLowWatermark", ",", "refillHighWatermark", ":", "defaultRefillHighWatermark", ",", "instr...
// NewObjectPoolOptions creates a new set of object pool options
[ "NewObjectPoolOptions", "creates", "a", "new", "set", "of", "object", "pool", "options" ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/pool/options.go#L40-L48
2,949
m3db/m3x
ident/ident_mock.go
NewMockID
func NewMockID(ctrl *gomock.Controller) *MockID { mock := &MockID{ctrl: ctrl} mock.recorder = &MockIDMockRecorder{mock} return mock }
go
func NewMockID(ctrl *gomock.Controller) *MockID { mock := &MockID{ctrl: ctrl} mock.recorder = &MockIDMockRecorder{mock} return mock }
[ "func", "NewMockID", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockID", "{", "mock", ":=", "&", "MockID", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockIDMockRecorder", "{", "mock", "}", "\n", "return", ...
// NewMockID creates a new mock instance
[ "NewMockID", "creates", "a", "new", "mock", "instance" ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/ident/ident_mock.go#L45-L49
2,950
m3db/m3x
ident/ident_mock.go
Bytes
func (mr *MockIDMockRecorder) Bytes() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bytes", reflect.TypeOf((*MockID)(nil).Bytes)) }
go
func (mr *MockIDMockRecorder) Bytes() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bytes", reflect.TypeOf((*MockID)(nil).Bytes)) }
[ "func", "(", "mr", "*", "MockIDMockRecorder", ")", "Bytes", "(", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", "\"", ",", "reflect", ".", "TypeOf", ...
// Bytes indicates an expected call of Bytes
[ "Bytes", "indicates", "an", "expected", "call", "of", "Bytes" ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/ident/ident_mock.go#L64-L66
2,951
m3db/m3x
ident/ident_mock.go
Equal
func (m *MockID) Equal(arg0 ID) bool { ret := m.ctrl.Call(m, "Equal", arg0) ret0, _ := ret[0].(bool) return ret0 }
go
func (m *MockID) Equal(arg0 ID) bool { ret := m.ctrl.Call(m, "Equal", arg0) ret0, _ := ret[0].(bool) return ret0 }
[ "func", "(", "m", "*", "MockID", ")", "Equal", "(", "arg0", "ID", ")", "bool", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "arg0", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "bo...
// Equal mocks base method
[ "Equal", "mocks", "base", "method" ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/ident/ident_mock.go#L69-L73
2,952
m3db/m3x
ident/ident_mock.go
Equal
func (mr *MockIDMockRecorder) Equal(arg0 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Equal", reflect.TypeOf((*MockID)(nil).Equal), arg0) }
go
func (mr *MockIDMockRecorder) Equal(arg0 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Equal", reflect.TypeOf((*MockID)(nil).Equal), arg0) }
[ "func", "(", "mr", "*", "MockIDMockRecorder", ")", "Equal", "(", "arg0", "interface", "{", "}", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", "\"", ...
// Equal indicates an expected call of Equal
[ "Equal", "indicates", "an", "expected", "call", "of", "Equal" ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/ident/ident_mock.go#L76-L78
2,953
m3db/m3x
ident/ident_mock.go
IsNoFinalize
func (m *MockID) IsNoFinalize() bool { ret := m.ctrl.Call(m, "IsNoFinalize") ret0, _ := ret[0].(bool) return ret0 }
go
func (m *MockID) IsNoFinalize() bool { ret := m.ctrl.Call(m, "IsNoFinalize") ret0, _ := ret[0].(bool) return ret0 }
[ "func", "(", "m", "*", "MockID", ")", "IsNoFinalize", "(", ")", "bool", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "bool", ")", "\n", "retur...
// IsNoFinalize mocks base method
[ "IsNoFinalize", "mocks", "base", "method" ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/ident/ident_mock.go#L91-L95
2,954
m3db/m3x
ident/ident_mock.go
NewMockTagIterator
func NewMockTagIterator(ctrl *gomock.Controller) *MockTagIterator { mock := &MockTagIterator{ctrl: ctrl} mock.recorder = &MockTagIteratorMockRecorder{mock} return mock }
go
func NewMockTagIterator(ctrl *gomock.Controller) *MockTagIterator { mock := &MockTagIterator{ctrl: ctrl} mock.recorder = &MockTagIteratorMockRecorder{mock} return mock }
[ "func", "NewMockTagIterator", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockTagIterator", "{", "mock", ":=", "&", "MockTagIterator", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockTagIteratorMockRecorder", "{", "...
// NewMockTagIterator creates a new mock instance
[ "NewMockTagIterator", "creates", "a", "new", "mock", "instance" ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/ident/ident_mock.go#L136-L140
2,955
m3db/m3x
ident/ident_mock.go
Current
func (m *MockTagIterator) Current() Tag { ret := m.ctrl.Call(m, "Current") ret0, _ := ret[0].(Tag) return ret0 }
go
func (m *MockTagIterator) Current() Tag { ret := m.ctrl.Call(m, "Current") ret0, _ := ret[0].(Tag) return ret0 }
[ "func", "(", "m", "*", "MockTagIterator", ")", "Current", "(", ")", "Tag", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "Tag", ")", "\n", "ret...
// Current mocks base method
[ "Current", "mocks", "base", "method" ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/ident/ident_mock.go#L158-L162
2,956
m3db/m3x
ident/ident_mock.go
Duplicate
func (m *MockTagIterator) Duplicate() TagIterator { ret := m.ctrl.Call(m, "Duplicate") ret0, _ := ret[0].(TagIterator) return ret0 }
go
func (m *MockTagIterator) Duplicate() TagIterator { ret := m.ctrl.Call(m, "Duplicate") ret0, _ := ret[0].(TagIterator) return ret0 }
[ "func", "(", "m", "*", "MockTagIterator", ")", "Duplicate", "(", ")", "TagIterator", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "TagIterator", "...
// Duplicate mocks base method
[ "Duplicate", "mocks", "base", "method" ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/ident/ident_mock.go#L182-L186
2,957
m3db/m3x
ident/ident_mock.go
Len
func (mr *MockTagIteratorMockRecorder) Len() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Len", reflect.TypeOf((*MockTagIterator)(nil).Len)) }
go
func (mr *MockTagIteratorMockRecorder) Len() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Len", reflect.TypeOf((*MockTagIterator)(nil).Len)) }
[ "func", "(", "mr", "*", "MockTagIteratorMockRecorder", ")", "Len", "(", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", "\"", ",", "reflect", ".", "Type...
// Len indicates an expected call of Len
[ "Len", "indicates", "an", "expected", "call", "of", "Len" ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/ident/ident_mock.go#L213-L215
2,958
m3db/m3x
ident/ident_mock.go
Next
func (m *MockTagIterator) Next() bool { ret := m.ctrl.Call(m, "Next") ret0, _ := ret[0].(bool) return ret0 }
go
func (m *MockTagIterator) Next() bool { ret := m.ctrl.Call(m, "Next") ret0, _ := ret[0].(bool) return ret0 }
[ "func", "(", "m", "*", "MockTagIterator", ")", "Next", "(", ")", "bool", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "bool", ")", "\n", "retu...
// Next mocks base method
[ "Next", "mocks", "base", "method" ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/ident/ident_mock.go#L218-L222
2,959
m3db/m3x
ident/ident_mock.go
Remaining
func (m *MockTagIterator) Remaining() int { ret := m.ctrl.Call(m, "Remaining") ret0, _ := ret[0].(int) return ret0 }
go
func (m *MockTagIterator) Remaining() int { ret := m.ctrl.Call(m, "Remaining") ret0, _ := ret[0].(int) return ret0 }
[ "func", "(", "m", "*", "MockTagIterator", ")", "Remaining", "(", ")", "int", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "int", ")", "\n", "r...
// Remaining mocks base method
[ "Remaining", "mocks", "base", "method" ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/ident/ident_mock.go#L230-L234
2,960
m3db/m3x
checked/bytes.go
NewBytes
func NewBytes(value []byte, opts BytesOptions) Bytes { if opts == nil { opts = defaultBytesOptions } b := &bytesRef{ opts: opts, value: value, } b.SetFinalizer(b) // NB(r): Tracking objects causes interface allocation // so avoid if we are not performing any leak detection. if leakDetectionEnabled() { b.TrackObject(b.value) } return b }
go
func NewBytes(value []byte, opts BytesOptions) Bytes { if opts == nil { opts = defaultBytesOptions } b := &bytesRef{ opts: opts, value: value, } b.SetFinalizer(b) // NB(r): Tracking objects causes interface allocation // so avoid if we are not performing any leak detection. if leakDetectionEnabled() { b.TrackObject(b.value) } return b }
[ "func", "NewBytes", "(", "value", "[", "]", "byte", ",", "opts", "BytesOptions", ")", "Bytes", "{", "if", "opts", "==", "nil", "{", "opts", "=", "defaultBytesOptions", "\n", "}", "\n", "b", ":=", "&", "bytesRef", "{", "opts", ":", "opts", ",", "value...
// NewBytes returns a new checked byte slice.
[ "NewBytes", "returns", "a", "new", "checked", "byte", "slice", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/checked/bytes.go#L65-L80
2,961
m3db/m3x
server/options.go
NewOptions
func NewOptions() Options { return &options{ instrumentOpts: instrument.NewOptions(), retryOpts: retry.NewOptions(), tcpConnectionKeepAlive: defaultTCPConnectionKeepAlive, tcpConnectionKeepAlivePeriod: defaultTCPConnectionKeepAlivePeriod, } }
go
func NewOptions() Options { return &options{ instrumentOpts: instrument.NewOptions(), retryOpts: retry.NewOptions(), tcpConnectionKeepAlive: defaultTCPConnectionKeepAlive, tcpConnectionKeepAlivePeriod: defaultTCPConnectionKeepAlivePeriod, } }
[ "func", "NewOptions", "(", ")", "Options", "{", "return", "&", "options", "{", "instrumentOpts", ":", "instrument", ".", "NewOptions", "(", ")", ",", "retryOpts", ":", "retry", ".", "NewOptions", "(", ")", ",", "tcpConnectionKeepAlive", ":", "defaultTCPConnect...
// NewOptions creates a new set of server options
[ "NewOptions", "creates", "a", "new", "set", "of", "server", "options" ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/server/options.go#L77-L84
2,962
m3db/m3x
pool/pool_mock.go
NewMockCheckedBytesPool
func NewMockCheckedBytesPool(ctrl *gomock.Controller) *MockCheckedBytesPool { mock := &MockCheckedBytesPool{ctrl: ctrl} mock.recorder = &MockCheckedBytesPoolMockRecorder{mock} return mock }
go
func NewMockCheckedBytesPool(ctrl *gomock.Controller) *MockCheckedBytesPool { mock := &MockCheckedBytesPool{ctrl: ctrl} mock.recorder = &MockCheckedBytesPoolMockRecorder{mock} return mock }
[ "func", "NewMockCheckedBytesPool", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockCheckedBytesPool", "{", "mock", ":=", "&", "MockCheckedBytesPool", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockCheckedBytesPoolMockR...
// NewMockCheckedBytesPool creates a new mock instance
[ "NewMockCheckedBytesPool", "creates", "a", "new", "mock", "instance" ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/pool/pool_mock.go#L47-L51
2,963
m3db/m3x
pool/pool_mock.go
BytesPool
func (m *MockCheckedBytesPool) BytesPool() BytesPool { ret := m.ctrl.Call(m, "BytesPool") ret0, _ := ret[0].(BytesPool) return ret0 }
go
func (m *MockCheckedBytesPool) BytesPool() BytesPool { ret := m.ctrl.Call(m, "BytesPool") ret0, _ := ret[0].(BytesPool) return ret0 }
[ "func", "(", "m", "*", "MockCheckedBytesPool", ")", "BytesPool", "(", ")", "BytesPool", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "BytesPool", ...
// BytesPool mocks base method
[ "BytesPool", "mocks", "base", "method" ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/pool/pool_mock.go#L59-L63
2,964
m3db/m3x
pool/pool_mock.go
BytesPool
func (mr *MockCheckedBytesPoolMockRecorder) BytesPool() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BytesPool", reflect.TypeOf((*MockCheckedBytesPool)(nil).BytesPool)) }
go
func (mr *MockCheckedBytesPoolMockRecorder) BytesPool() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BytesPool", reflect.TypeOf((*MockCheckedBytesPool)(nil).BytesPool)) }
[ "func", "(", "mr", "*", "MockCheckedBytesPoolMockRecorder", ")", "BytesPool", "(", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", "\"", ",", "reflect", "...
// BytesPool indicates an expected call of BytesPool
[ "BytesPool", "indicates", "an", "expected", "call", "of", "BytesPool" ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/pool/pool_mock.go#L66-L68
2,965
m3db/m3x
pool/pool_mock.go
NewMockBytesPool
func NewMockBytesPool(ctrl *gomock.Controller) *MockBytesPool { mock := &MockBytesPool{ctrl: ctrl} mock.recorder = &MockBytesPoolMockRecorder{mock} return mock }
go
func NewMockBytesPool(ctrl *gomock.Controller) *MockBytesPool { mock := &MockBytesPool{ctrl: ctrl} mock.recorder = &MockBytesPoolMockRecorder{mock} return mock }
[ "func", "NewMockBytesPool", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockBytesPool", "{", "mock", ":=", "&", "MockBytesPool", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockBytesPoolMockRecorder", "{", "mock", ...
// NewMockBytesPool creates a new mock instance
[ "NewMockBytesPool", "creates", "a", "new", "mock", "instance" ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/pool/pool_mock.go#L104-L108
2,966
m3db/m3x
ident/identifier.go
BinaryID
func BinaryID(v checked.Bytes) ID { v.IncRef() return &id{data: v} }
go
func BinaryID(v checked.Bytes) ID { v.IncRef() return &id{data: v} }
[ "func", "BinaryID", "(", "v", "checked", ".", "Bytes", ")", "ID", "{", "v", ".", "IncRef", "(", ")", "\n", "return", "&", "id", "{", "data", ":", "v", "}", "\n", "}" ]
// BinaryID constructs a new ID based on a binary value.
[ "BinaryID", "constructs", "a", "new", "ID", "based", "on", "a", "binary", "value", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/ident/identifier.go#L30-L33
2,967
m3db/m3x
ident/identifier.go
Bytes
func (v *id) Bytes() []byte { if v.data == nil { return nil } return v.data.Bytes() }
go
func (v *id) Bytes() []byte { if v.data == nil { return nil } return v.data.Bytes() }
[ "func", "(", "v", "*", "id", ")", "Bytes", "(", ")", "[", "]", "byte", "{", "if", "v", ".", "data", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "v", ".", "data", ".", "Bytes", "(", ")", "\n", "}" ]
// Bytes directly returns the underlying bytes of an ID, it is not safe // to hold a reference to this slice and is only valid during the lifetime // of the the ID itself.
[ "Bytes", "directly", "returns", "the", "underlying", "bytes", "of", "an", "ID", "it", "is", "not", "safe", "to", "hold", "a", "reference", "to", "this", "slice", "and", "is", "only", "valid", "during", "the", "lifetime", "of", "the", "the", "ID", "itself...
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/ident/identifier.go#L49-L54
2,968
m3db/m3x
close/close.go
TryClose
func TryClose(r interface{}) error { if r, ok := r.(Closer); ok { return r.Close() } if r, ok := r.(SimpleCloser); ok { r.Close() return nil } return ErrNotCloseable }
go
func TryClose(r interface{}) error { if r, ok := r.(Closer); ok { return r.Close() } if r, ok := r.(SimpleCloser); ok { r.Close() return nil } return ErrNotCloseable }
[ "func", "TryClose", "(", "r", "interface", "{", "}", ")", "error", "{", "if", "r", ",", "ok", ":=", "r", ".", "(", "Closer", ")", ";", "ok", "{", "return", "r", ".", "Close", "(", ")", "\n", "}", "\n", "if", "r", ",", "ok", ":=", "r", ".", ...
// TryClose attempts to close a resource, the resource is expected to // implement either Closeable or CloseableResult.
[ "TryClose", "attempts", "to", "close", "a", "resource", "the", "resource", "is", "expected", "to", "implement", "either", "Closeable", "or", "CloseableResult", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/close/close.go#L47-L56
2,969
m3db/m3x
pool/floats.go
NewFloatsPool
func NewFloatsPool(sizes []Bucket, opts ObjectPoolOptions) FloatsPool { return &floatsPool{pool: NewBucketizedObjectPool(sizes, opts)} }
go
func NewFloatsPool(sizes []Bucket, opts ObjectPoolOptions) FloatsPool { return &floatsPool{pool: NewBucketizedObjectPool(sizes, opts)} }
[ "func", "NewFloatsPool", "(", "sizes", "[", "]", "Bucket", ",", "opts", "ObjectPoolOptions", ")", "FloatsPool", "{", "return", "&", "floatsPool", "{", "pool", ":", "NewBucketizedObjectPool", "(", "sizes", ",", "opts", ")", "}", "\n", "}" ]
// NewFloatsPool creates a new floats pool
[ "NewFloatsPool", "creates", "a", "new", "floats", "pool" ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/pool/floats.go#L28-L30
2,970
apcera/util
restclient/restclient.go
NewDisableKeepAlives
func NewDisableKeepAlives(baseurl string) (*Client, error) { base, err := url.ParseRequestURI(baseurl) if err != nil { return nil, err } else if !base.IsAbs() || base.Host == "" { return nil, fmt.Errorf("URL is not absolute: %s", baseurl) } transport := http.DefaultTransport.(*http.Transport) transport.DisableKeepAlives = true // create the client client := &Client{ Driver: &http.Client{ Transport: transport, }, // Don't use default client; shares by reference Headers: http.Header(make(map[string][]string)), base: base, KeepAlives: false, } return client, nil }
go
func NewDisableKeepAlives(baseurl string) (*Client, error) { base, err := url.ParseRequestURI(baseurl) if err != nil { return nil, err } else if !base.IsAbs() || base.Host == "" { return nil, fmt.Errorf("URL is not absolute: %s", baseurl) } transport := http.DefaultTransport.(*http.Transport) transport.DisableKeepAlives = true // create the client client := &Client{ Driver: &http.Client{ Transport: transport, }, // Don't use default client; shares by reference Headers: http.Header(make(map[string][]string)), base: base, KeepAlives: false, } return client, nil }
[ "func", "NewDisableKeepAlives", "(", "baseurl", "string", ")", "(", "*", "Client", ",", "error", ")", "{", "base", ",", "err", ":=", "url", ".", "ParseRequestURI", "(", "baseurl", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", ...
// NewWithoutKeepAlives returns a new client with keepalives disabled.
[ "NewWithoutKeepAlives", "returns", "a", "new", "client", "with", "keepalives", "disabled", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/restclient/restclient.go#L81-L103
2,971
apcera/util
restclient/restclient.go
SetAccessToken
func (c *Client) SetAccessToken(token string) { c.Headers.Set(http.CanonicalHeaderKey("Authorization"), "Bearer "+token) }
go
func (c *Client) SetAccessToken(token string) { c.Headers.Set(http.CanonicalHeaderKey("Authorization"), "Bearer "+token) }
[ "func", "(", "c", "*", "Client", ")", "SetAccessToken", "(", "token", "string", ")", "{", "c", ".", "Headers", ".", "Set", "(", "http", ".", "CanonicalHeaderKey", "(", "\"", "\"", ")", ",", "\"", "\"", "+", "token", ")", "\n", "}" ]
// Set the access Token
[ "Set", "the", "access", "Token" ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/restclient/restclient.go#L112-L114
2,972
apcera/util
restclient/restclient.go
SetTimeout
func (c *Client) SetTimeout(duration time.Duration) { c.Driver.Timeout = duration }
go
func (c *Client) SetTimeout(duration time.Duration) { c.Driver.Timeout = duration }
[ "func", "(", "c", "*", "Client", ")", "SetTimeout", "(", "duration", "time", ".", "Duration", ")", "{", "c", ".", "Driver", ".", "Timeout", "=", "duration", "\n", "}" ]
// SetTimeout sets the timeout of a client to the given duration.
[ "SetTimeout", "sets", "the", "timeout", "of", "a", "client", "to", "the", "given", "duration", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/restclient/restclient.go#L117-L119
2,973
apcera/util
restclient/restclient.go
Result
func (c *Client) Result(req *Request, resp interface{}) error { result, err := c.Do(req) if err != nil { return err } return unmarshal(result, resp) }
go
func (c *Client) Result(req *Request, resp interface{}) error { result, err := c.Do(req) if err != nil { return err } return unmarshal(result, resp) }
[ "func", "(", "c", "*", "Client", ")", "Result", "(", "req", "*", "Request", ",", "resp", "interface", "{", "}", ")", "error", "{", "result", ",", "err", ":=", "c", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err"...
// Result performs the request described by req and unmarshals a successful // HTTP response into resp. If resp is nil, the response is discarded.
[ "Result", "performs", "the", "request", "described", "by", "req", "and", "unmarshals", "a", "successful", "HTTP", "response", "into", "resp", ".", "If", "resp", "is", "nil", "the", "response", "is", "discarded", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/restclient/restclient.go#L155-L161
2,974
apcera/util
restclient/restclient.go
NewRequest
func (c *Client) NewRequest(method Method, endpoint string, ctype string, body io.Reader) (req *Request) { req = c.newRequest(method, endpoint) if body == nil { return } req.prepare = func(hr *http.Request) error { rc, ok := body.(io.ReadCloser) if !ok { rc = ioutil.NopCloser(body) } hr.Body = rc hr.Header.Set("Content-Type", ctype) return nil } return }
go
func (c *Client) NewRequest(method Method, endpoint string, ctype string, body io.Reader) (req *Request) { req = c.newRequest(method, endpoint) if body == nil { return } req.prepare = func(hr *http.Request) error { rc, ok := body.(io.ReadCloser) if !ok { rc = ioutil.NopCloser(body) } hr.Body = rc hr.Header.Set("Content-Type", ctype) return nil } return }
[ "func", "(", "c", "*", "Client", ")", "NewRequest", "(", "method", "Method", ",", "endpoint", "string", ",", "ctype", "string", ",", "body", "io", ".", "Reader", ")", "(", "req", "*", "Request", ")", "{", "req", "=", "c", ".", "newRequest", "(", "m...
// NewRequest generates a new Request object that will send bytes read from body // to the endpoint.
[ "NewRequest", "generates", "a", "new", "Request", "object", "that", "will", "send", "bytes", "read", "from", "body", "to", "the", "endpoint", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/restclient/restclient.go#L194-L210
2,975
apcera/util
restclient/restclient.go
NewJsonRequest
func (c *Client) NewJsonRequest(method Method, endpoint string, obj interface{}) (req *Request) { req = c.newRequest(method, endpoint) if obj == nil { return } req.prepare = func(httpReq *http.Request) error { var buffer bytes.Buffer encoder := json.NewEncoder(&buffer) if err := encoder.Encode(obj); err != nil { return err } // set to the request httpReq.Body = ioutil.NopCloser(&buffer) httpReq.ContentLength = int64(buffer.Len()) httpReq.Header.Set("Content-Type", "application/json") return nil } return req }
go
func (c *Client) NewJsonRequest(method Method, endpoint string, obj interface{}) (req *Request) { req = c.newRequest(method, endpoint) if obj == nil { return } req.prepare = func(httpReq *http.Request) error { var buffer bytes.Buffer encoder := json.NewEncoder(&buffer) if err := encoder.Encode(obj); err != nil { return err } // set to the request httpReq.Body = ioutil.NopCloser(&buffer) httpReq.ContentLength = int64(buffer.Len()) httpReq.Header.Set("Content-Type", "application/json") return nil } return req }
[ "func", "(", "c", "*", "Client", ")", "NewJsonRequest", "(", "method", "Method", ",", "endpoint", "string", ",", "obj", "interface", "{", "}", ")", "(", "req", "*", "Request", ")", "{", "req", "=", "c", ".", "newRequest", "(", "method", ",", "endpoin...
// NewJsonRequest generates a new Request object and JSON encodes the provided // obj. The JSON object will be set as the body and included in the request.
[ "NewJsonRequest", "generates", "a", "new", "Request", "object", "and", "JSON", "encodes", "the", "provided", "obj", ".", "The", "JSON", "object", "will", "be", "set", "as", "the", "body", "and", "included", "in", "the", "request", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/restclient/restclient.go#L214-L235
2,976
apcera/util
restclient/restclient.go
NewFormRequest
func (c *Client) NewFormRequest(method Method, endpoint string, params map[string]string) *Request { req := c.newRequest(method, endpoint) // set how to generate the body req.prepare = func(httpReq *http.Request) error { form := url.Values{} for k, v := range params { form.Set(k, v) } encoded := form.Encode() // set to the request httpReq.Body = ioutil.NopCloser(bytes.NewReader([]byte(encoded))) httpReq.ContentLength = int64(len(encoded)) httpReq.Header.Set("Content-Type", "application/x-www-form-urlencoded") return nil } return req }
go
func (c *Client) NewFormRequest(method Method, endpoint string, params map[string]string) *Request { req := c.newRequest(method, endpoint) // set how to generate the body req.prepare = func(httpReq *http.Request) error { form := url.Values{} for k, v := range params { form.Set(k, v) } encoded := form.Encode() // set to the request httpReq.Body = ioutil.NopCloser(bytes.NewReader([]byte(encoded))) httpReq.ContentLength = int64(len(encoded)) httpReq.Header.Set("Content-Type", "application/x-www-form-urlencoded") return nil } return req }
[ "func", "(", "c", "*", "Client", ")", "NewFormRequest", "(", "method", "Method", ",", "endpoint", "string", ",", "params", "map", "[", "string", "]", "string", ")", "*", "Request", "{", "req", ":=", "c", ".", "newRequest", "(", "method", ",", "endpoint...
// NewFormRequest generates a new Request object with a form encoded body based // on the params map.
[ "NewFormRequest", "generates", "a", "new", "Request", "object", "with", "a", "form", "encoded", "body", "based", "on", "the", "params", "map", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/restclient/restclient.go#L239-L258
2,977
apcera/util
hashutil/sha1util.go
NewSha1
func NewSha1(r io.Reader) *Sha1Reader { s := new(Sha1Reader) s.hashReader = newHashReader(sha1.New(), r) return s }
go
func NewSha1(r io.Reader) *Sha1Reader { s := new(Sha1Reader) s.hashReader = newHashReader(sha1.New(), r) return s }
[ "func", "NewSha1", "(", "r", "io", ".", "Reader", ")", "*", "Sha1Reader", "{", "s", ":=", "new", "(", "Sha1Reader", ")", "\n", "s", ".", "hashReader", "=", "newHashReader", "(", "sha1", ".", "New", "(", ")", ",", "r", ")", "\n", "return", "s", "\...
// Returns a new Sha1Reader.
[ "Returns", "a", "new", "Sha1Reader", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/hashutil/sha1util.go#L34-L38
2,978
apcera/util
hashutil/sha1util.go
Sha1
func (s *Sha1Reader) Sha1() string { return hex.EncodeToString(s.hash.Sum(nil)) }
go
func (s *Sha1Reader) Sha1() string { return hex.EncodeToString(s.hash.Sum(nil)) }
[ "func", "(", "s", "*", "Sha1Reader", ")", "Sha1", "(", ")", "string", "{", "return", "hex", ".", "EncodeToString", "(", "s", ".", "hash", ".", "Sum", "(", "nil", ")", ")", "\n", "}" ]
// Returns the SHA1 for all data that has been passed through this Reader // already. This should ideally be called after the Reader is Closed, but // otherwise its safe to call any time.
[ "Returns", "the", "SHA1", "for", "all", "data", "that", "has", "been", "passed", "through", "this", "Reader", "already", ".", "This", "should", "ideally", "be", "called", "after", "the", "Reader", "is", "Closed", "but", "otherwise", "its", "safe", "to", "c...
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/hashutil/sha1util.go#L43-L45
2,979
apcera/util
iprange/allocator.go
NewAllocator
func NewAllocator(ipr *IPRange) *IPRangeAllocator { a := &IPRangeAllocator{ ipRange: ipr, reserved: make(map[int64]bool), startIsIPv4: bytes.Compare(ipr.Start.To16()[0:12], ipv6in4) == 0, } // calculate the size of the range a.startBig = big.NewInt(0) a.startBig.SetBytes(a.ipRange.Start) endBig := big.NewInt(0) endBig.SetBytes(a.ipRange.End) sizeBig := endBig.Sub(endBig, a.startBig) // 1 is added to the size because the end IP is inclusive a.size = sizeBig.Int64() + 1 a.remaining = a.size return a }
go
func NewAllocator(ipr *IPRange) *IPRangeAllocator { a := &IPRangeAllocator{ ipRange: ipr, reserved: make(map[int64]bool), startIsIPv4: bytes.Compare(ipr.Start.To16()[0:12], ipv6in4) == 0, } // calculate the size of the range a.startBig = big.NewInt(0) a.startBig.SetBytes(a.ipRange.Start) endBig := big.NewInt(0) endBig.SetBytes(a.ipRange.End) sizeBig := endBig.Sub(endBig, a.startBig) // 1 is added to the size because the end IP is inclusive a.size = sizeBig.Int64() + 1 a.remaining = a.size return a }
[ "func", "NewAllocator", "(", "ipr", "*", "IPRange", ")", "*", "IPRangeAllocator", "{", "a", ":=", "&", "IPRangeAllocator", "{", "ipRange", ":", "ipr", ",", "reserved", ":", "make", "(", "map", "[", "int64", "]", "bool", ")", ",", "startIsIPv4", ":", "b...
// NewAllocator creates a new IPRangeAllocator for the provided IPRange.
[ "NewAllocator", "creates", "a", "new", "IPRangeAllocator", "for", "the", "provided", "IPRange", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/iprange/allocator.go#L29-L48
2,980
apcera/util
iprange/allocator.go
Allocate
func (a *IPRangeAllocator) Allocate() net.IP { a.mutex.Lock() defer a.mutex.Unlock() // ensure we have some IPs first if a.remaining <= 0 { return nil } // get a random number within the size to start with idx := rand.Int63n(a.size) // find the next available index after the random number that is available idx = a.findNextAvailbleIndex(idx) // if idx is now -1, then it couldn't find one, which is very unlikely, // however if that is, treat it as no more remaining and ensure remaining is // now 0 if idx == -1 { a.remaining = 0 return nil } // reserve the idx, get the IP bytes a.reserved[idx] = true a.remaining-- newBig := big.NewInt(0).Add(a.startBig, big.NewInt(idx)) return a.bigIntToIP(newBig) }
go
func (a *IPRangeAllocator) Allocate() net.IP { a.mutex.Lock() defer a.mutex.Unlock() // ensure we have some IPs first if a.remaining <= 0 { return nil } // get a random number within the size to start with idx := rand.Int63n(a.size) // find the next available index after the random number that is available idx = a.findNextAvailbleIndex(idx) // if idx is now -1, then it couldn't find one, which is very unlikely, // however if that is, treat it as no more remaining and ensure remaining is // now 0 if idx == -1 { a.remaining = 0 return nil } // reserve the idx, get the IP bytes a.reserved[idx] = true a.remaining-- newBig := big.NewInt(0).Add(a.startBig, big.NewInt(idx)) return a.bigIntToIP(newBig) }
[ "func", "(", "a", "*", "IPRangeAllocator", ")", "Allocate", "(", ")", "net", ".", "IP", "{", "a", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "// ensure we have some IPs first", "if", "a", "...
// Allocate can be used to allocate a new IP address within the provided // range. It will ensure that it is unique. If the allocator has no additional // IP addresses available, then it will return nil.
[ "Allocate", "can", "be", "used", "to", "allocate", "a", "new", "IP", "address", "within", "the", "provided", "range", ".", "It", "will", "ensure", "that", "it", "is", "unique", ".", "If", "the", "allocator", "has", "no", "additional", "IP", "addresses", ...
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/iprange/allocator.go#L53-L82
2,981
apcera/util
iprange/allocator.go
Reserve
func (a *IPRangeAllocator) Reserve(ip net.IP) { a.mutex.Lock() defer a.mutex.Unlock() // ensure the specified IP is within the range if !a.ipRange.Contains(ip) { return } // calculate the idx from the start ipBig := big.NewInt(0) ipBig.SetBytes(ip) idx := ipBig.Sub(ipBig, a.startBig).Int64() // if it isn't already reserved, then mark it reserved and decrement the // remaining count if !a.reserved[idx] { a.reserved[idx] = true a.remaining-- } }
go
func (a *IPRangeAllocator) Reserve(ip net.IP) { a.mutex.Lock() defer a.mutex.Unlock() // ensure the specified IP is within the range if !a.ipRange.Contains(ip) { return } // calculate the idx from the start ipBig := big.NewInt(0) ipBig.SetBytes(ip) idx := ipBig.Sub(ipBig, a.startBig).Int64() // if it isn't already reserved, then mark it reserved and decrement the // remaining count if !a.reserved[idx] { a.reserved[idx] = true a.remaining-- } }
[ "func", "(", "a", "*", "IPRangeAllocator", ")", "Reserve", "(", "ip", "net", ".", "IP", ")", "{", "a", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "// ensure the specified IP is within the range...
// Reserve allows reserving a specific IP address within the specified range to // ensure it is not allocated.
[ "Reserve", "allows", "reserving", "a", "specific", "IP", "address", "within", "the", "specified", "range", "to", "ensure", "it", "is", "not", "allocated", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/iprange/allocator.go#L86-L106
2,982
apcera/util
iprange/allocator.go
Release
func (a *IPRangeAllocator) Release(ip net.IP) { a.mutex.Lock() defer a.mutex.Unlock() // calculate the idx from the start ipBig := big.NewInt(0) ipBig.SetBytes(ip) idx := ipBig.Sub(ipBig, a.startBig).Int64() // check if the idx is reserved if a.reserved[idx] { delete(a.reserved, idx) a.remaining++ } }
go
func (a *IPRangeAllocator) Release(ip net.IP) { a.mutex.Lock() defer a.mutex.Unlock() // calculate the idx from the start ipBig := big.NewInt(0) ipBig.SetBytes(ip) idx := ipBig.Sub(ipBig, a.startBig).Int64() // check if the idx is reserved if a.reserved[idx] { delete(a.reserved, idx) a.remaining++ } }
[ "func", "(", "a", "*", "IPRangeAllocator", ")", "Release", "(", "ip", "net", ".", "IP", ")", "{", "a", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "// calculate the idx from the start", "ipBig...
// Release can be used to release an IP address that had previously been // allocated or reserved.
[ "Release", "can", "be", "used", "to", "release", "an", "IP", "address", "that", "had", "previously", "been", "allocated", "or", "reserved", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/iprange/allocator.go#L110-L124
2,983
apcera/util
iprange/allocator.go
Subtract
func (a *IPRangeAllocator) Subtract(iprange *IPRange) { curBig := big.NewInt(0) curBig.SetBytes(iprange.Start) endBig := big.NewInt(0) endBig.SetBytes(iprange.End) for ; curBig.Cmp(endBig) < 1; curBig = curBig.Add(big.NewInt(1), curBig) { ip := a.bigIntToIP(curBig) if a.ipRange.Contains(ip) { a.Reserve(ip) } } }
go
func (a *IPRangeAllocator) Subtract(iprange *IPRange) { curBig := big.NewInt(0) curBig.SetBytes(iprange.Start) endBig := big.NewInt(0) endBig.SetBytes(iprange.End) for ; curBig.Cmp(endBig) < 1; curBig = curBig.Add(big.NewInt(1), curBig) { ip := a.bigIntToIP(curBig) if a.ipRange.Contains(ip) { a.Reserve(ip) } } }
[ "func", "(", "a", "*", "IPRangeAllocator", ")", "Subtract", "(", "iprange", "*", "IPRange", ")", "{", "curBig", ":=", "big", ".", "NewInt", "(", "0", ")", "\n", "curBig", ".", "SetBytes", "(", "iprange", ".", "Start", ")", "\n", "endBig", ":=", "big"...
// Subtract marks all of the IPs from another IPRange as reserved in the current // allocator.
[ "Subtract", "marks", "all", "of", "the", "IPs", "from", "another", "IPRange", "as", "reserved", "in", "the", "current", "allocator", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/iprange/allocator.go#L128-L140
2,984
apcera/util
iprange/allocator.go
IPRange
func (a *IPRangeAllocator) IPRange() *IPRange { a.mutex.Lock() defer a.mutex.Unlock() return &IPRange{ Start: a.ipRange.Start, End: a.ipRange.End, Mask: a.ipRange.Mask, } }
go
func (a *IPRangeAllocator) IPRange() *IPRange { a.mutex.Lock() defer a.mutex.Unlock() return &IPRange{ Start: a.ipRange.Start, End: a.ipRange.End, Mask: a.ipRange.Mask, } }
[ "func", "(", "a", "*", "IPRangeAllocator", ")", "IPRange", "(", ")", "*", "IPRange", "{", "a", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "return", "&", "IPRange", "{", "Start", ":", "a...
// IPRange returns a copy of the IPRange provided to the allocator.
[ "IPRange", "returns", "a", "copy", "of", "the", "IPRange", "provided", "to", "the", "allocator", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/iprange/allocator.go#L143-L152
2,985
apcera/util
iprange/allocator.go
Size
func (a *IPRangeAllocator) Size() int64 { a.mutex.Lock() defer a.mutex.Unlock() return a.size }
go
func (a *IPRangeAllocator) Size() int64 { a.mutex.Lock() defer a.mutex.Unlock() return a.size }
[ "func", "(", "a", "*", "IPRangeAllocator", ")", "Size", "(", ")", "int64", "{", "a", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "mutex", ".", "Unlock", "(", ")", "\n", "return", "a", ".", "size", "\n", "}" ]
// Size returns the size of the allowable IP addresses specified by the range.
[ "Size", "returns", "the", "size", "of", "the", "allowable", "IP", "addresses", "specified", "by", "the", "range", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/iprange/allocator.go#L155-L159
2,986
apcera/util
iprange/allocator.go
Remaining
func (a *IPRangeAllocator) Remaining() int64 { a.mutex.Lock() defer a.mutex.Unlock() return a.remaining }
go
func (a *IPRangeAllocator) Remaining() int64 { a.mutex.Lock() defer a.mutex.Unlock() return a.remaining }
[ "func", "(", "a", "*", "IPRangeAllocator", ")", "Remaining", "(", ")", "int64", "{", "a", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "mutex", ".", "Unlock", "(", ")", "\n", "return", "a", ".", "remaining", "\n", "}" ]
// Remaining returns the number of remaining IP addresses within the provided // range that have not been already allocated.
[ "Remaining", "returns", "the", "number", "of", "remaining", "IP", "addresses", "within", "the", "provided", "range", "that", "have", "not", "been", "already", "allocated", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/iprange/allocator.go#L163-L167
2,987
apcera/util
iprange/allocator.go
findNextAvailbleIndex
func (a *IPRangeAllocator) findNextAvailbleIndex(idx int64) int64 { // walk up from the index for i := idx; i < a.size; i++ { if !a.reserved[i] { return i } } // nothing above that one... lets try to walk down to find something for i := idx - 1; i >= 0; i-- { if !a.reserved[i] { return i } } // ok, everything is probably taken return -1 }
go
func (a *IPRangeAllocator) findNextAvailbleIndex(idx int64) int64 { // walk up from the index for i := idx; i < a.size; i++ { if !a.reserved[i] { return i } } // nothing above that one... lets try to walk down to find something for i := idx - 1; i >= 0; i-- { if !a.reserved[i] { return i } } // ok, everything is probably taken return -1 }
[ "func", "(", "a", "*", "IPRangeAllocator", ")", "findNextAvailbleIndex", "(", "idx", "int64", ")", "int64", "{", "// walk up from the index", "for", "i", ":=", "idx", ";", "i", "<", "a", ".", "size", ";", "i", "++", "{", "if", "!", "a", ".", "reserved"...
// findNextAvailableIndex finds the value of idx which is available and not in // the reserved list.
[ "findNextAvailableIndex", "finds", "the", "value", "of", "idx", "which", "is", "available", "and", "not", "in", "the", "reserved", "list", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/iprange/allocator.go#L171-L188
2,988
apcera/util
terminal/terminal_state_unix.go
Isatty
func Isatty(fd uintptr) bool { var termios syscall.Termios _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, uintptr(syscallGetTermios), uintptr(unsafe.Pointer(&termios)), 0, 0, 0) return err == 0 }
go
func Isatty(fd uintptr) bool { var termios syscall.Termios _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, uintptr(syscallGetTermios), uintptr(unsafe.Pointer(&termios)), 0, 0, 0) return err == 0 }
[ "func", "Isatty", "(", "fd", "uintptr", ")", "bool", "{", "var", "termios", "syscall", ".", "Termios", "\n\n", "_", ",", "_", ",", "err", ":=", "syscall", ".", "Syscall6", "(", "syscall", ".", "SYS_IOCTL", ",", "fd", ",", "uintptr", "(", "syscallGetTer...
// isatty checks whether FD is a tty. Doesn't work on Windows.
[ "isatty", "checks", "whether", "FD", "is", "a", "tty", ".", "Doesn", "t", "work", "on", "Windows", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/terminal/terminal_state_unix.go#L20-L27
2,989
apcera/util
proc/parser.go
ReadInt64
func ReadInt64(file string) (int64, error) { f, err := os.Open(file) if err != nil { return 0, err } defer f.Close() buf := make([]byte, 19) n, err := f.Read(buf) if err != nil { return 0, err } p := strings.Split(string(buf[0:n]), "\n") v, err := strconv.ParseInt(p[0], 10, 64) if err != nil { return 0, err } return v, nil }
go
func ReadInt64(file string) (int64, error) { f, err := os.Open(file) if err != nil { return 0, err } defer f.Close() buf := make([]byte, 19) n, err := f.Read(buf) if err != nil { return 0, err } p := strings.Split(string(buf[0:n]), "\n") v, err := strconv.ParseInt(p[0], 10, 64) if err != nil { return 0, err } return v, nil }
[ "func", "ReadInt64", "(", "file", "string", ")", "(", "int64", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "defer", "f", ...
// ReadInt64 reads one int64 number from the first line of a file.
[ "ReadInt64", "reads", "one", "int64", "number", "from", "the", "first", "line", "of", "a", "file", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/proc/parser.go#L13-L33
2,990
apcera/util
proc/parser.go
ParseSimpleProcFile
func ParseSimpleProcFile( filename string, lf func(index int, line string) error, ef func(line, index int, elm string) error) error { fd, err := os.Open(filename) if err != nil { return err } defer fd.Close() contentsBytes, err := ioutil.ReadAll(fd) if err != nil { return err } // Setup base handlers if they were passed in as nil. if lf == nil { lf = func(index int, line string) error { return nil } } if ef == nil { ef = func(line, index int, elm string) error { return nil } } contents := string(contentsBytes) lines := strings.Split(contents, "\n") for li, l := range lines { for ei, e := range strings.Fields(l) { if err := ef(li, ei, e); err != nil { return err } } if err := lf(li, l); err != nil { return err } } return nil }
go
func ParseSimpleProcFile( filename string, lf func(index int, line string) error, ef func(line, index int, elm string) error) error { fd, err := os.Open(filename) if err != nil { return err } defer fd.Close() contentsBytes, err := ioutil.ReadAll(fd) if err != nil { return err } // Setup base handlers if they were passed in as nil. if lf == nil { lf = func(index int, line string) error { return nil } } if ef == nil { ef = func(line, index int, elm string) error { return nil } } contents := string(contentsBytes) lines := strings.Split(contents, "\n") for li, l := range lines { for ei, e := range strings.Fields(l) { if err := ef(li, ei, e); err != nil { return err } } if err := lf(li, l); err != nil { return err } } return nil }
[ "func", "ParseSimpleProcFile", "(", "filename", "string", ",", "lf", "func", "(", "index", "int", ",", "line", "string", ")", "error", ",", "ef", "func", "(", "line", ",", "index", "int", ",", "elm", "string", ")", "error", ")", "error", "{", "fd", "...
// Parses the given file into various elements. This function assumes basic // white space semantics (' ' and '\t' for column splitting, and '\n' for // row splitting.
[ "Parses", "the", "given", "file", "into", "various", "elements", ".", "This", "function", "assumes", "basic", "white", "space", "semantics", "(", "and", "\\", "t", "for", "column", "splitting", "and", "\\", "n", "for", "row", "splitting", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/proc/parser.go#L38-L77
2,991
apcera/util
timeoutwg/timeoutwg.go
Add
func (twg *TimeoutWaitGroup) Add(delta int) { twg.mutex.Lock() defer twg.mutex.Unlock() if twg.workers == 0 { // waitgroups are reusable once workers is 0 twg.last = nil } else if twg.workers > 0 && twg.last != nil { // This mimics normal WG behavior. Cannot add after Wait() has been // called, unless workers is 0. Prevents races on Wait() panic("TimeoutWaitGroup misuse: Add called concurrently with Wait") } twg.workers += delta }
go
func (twg *TimeoutWaitGroup) Add(delta int) { twg.mutex.Lock() defer twg.mutex.Unlock() if twg.workers == 0 { // waitgroups are reusable once workers is 0 twg.last = nil } else if twg.workers > 0 && twg.last != nil { // This mimics normal WG behavior. Cannot add after Wait() has been // called, unless workers is 0. Prevents races on Wait() panic("TimeoutWaitGroup misuse: Add called concurrently with Wait") } twg.workers += delta }
[ "func", "(", "twg", "*", "TimeoutWaitGroup", ")", "Add", "(", "delta", "int", ")", "{", "twg", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "twg", ".", "mutex", ".", "Unlock", "(", ")", "\n", "if", "twg", ".", "workers", "==", "0", "{", ...
// Add increments the wait group's count of active workers by delta.
[ "Add", "increments", "the", "wait", "group", "s", "count", "of", "active", "workers", "by", "delta", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/timeoutwg/timeoutwg.go#L21-L33
2,992
apcera/util
timeoutwg/timeoutwg.go
Done
func (twg *TimeoutWaitGroup) Done() { twg.mutex.Lock() defer twg.mutex.Unlock() twg.workers-- if twg.workers < 0 { panic("TimeoutWaitGroup: negative counter") } if twg.workers == 0 && twg.last != nil { close(twg.last) } }
go
func (twg *TimeoutWaitGroup) Done() { twg.mutex.Lock() defer twg.mutex.Unlock() twg.workers-- if twg.workers < 0 { panic("TimeoutWaitGroup: negative counter") } if twg.workers == 0 && twg.last != nil { close(twg.last) } }
[ "func", "(", "twg", "*", "TimeoutWaitGroup", ")", "Done", "(", ")", "{", "twg", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "twg", ".", "mutex", ".", "Unlock", "(", ")", "\n", "twg", ".", "workers", "--", "\n", "if", "twg", ".", "workers"...
// Done decrements the wait group count by one.
[ "Done", "decrements", "the", "wait", "group", "count", "by", "one", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/timeoutwg/timeoutwg.go#L36-L46
2,993
apcera/util
proc/proc.go
InterfaceStats
func InterfaceStats() (map[string]InterfaceStat, error) { ret := make(map[string]InterfaceStat, 0) var current InterfaceStat lastline := -1 lastindex := -1 lf := func(index int, line string) error { if lastline == index && lastindex == 16 { ret[current.Device] = current } current = InterfaceStat{} return nil } el := func(line int, index int, elm string) (err error) { switch index { case 0: current.Device = strings.Split(elm, ":")[0] case 1: current.RxBytes, err = strconv.ParseUint(elm, 10, 64) case 2: current.RxPackets, err = strconv.ParseUint(elm, 10, 64) case 3: current.RxErrors, err = strconv.ParseUint(elm, 10, 64) case 4: current.RxDrop, err = strconv.ParseUint(elm, 10, 64) case 5: current.RxFifo, err = strconv.ParseUint(elm, 10, 64) case 6: current.RxFrame, err = strconv.ParseUint(elm, 10, 64) case 7: current.RxCompressed, err = strconv.ParseUint(elm, 10, 64) case 8: current.RxMulticast, err = strconv.ParseUint(elm, 10, 64) case 9: current.TxBytes, err = strconv.ParseUint(elm, 10, 64) case 10: current.TxPackets, err = strconv.ParseUint(elm, 10, 64) case 11: current.TxErrors, err = strconv.ParseUint(elm, 10, 64) case 12: current.TxDrop, err = strconv.ParseUint(elm, 10, 64) case 13: current.TxFifo, err = strconv.ParseUint(elm, 10, 64) case 14: current.TxFrame, err = strconv.ParseUint(elm, 10, 64) case 15: current.TxCompressed, err = strconv.ParseUint(elm, 10, 64) case 16: current.TxMulticast, err = strconv.ParseUint(elm, 10, 64) } lastline = line lastindex = index return } // Now actually attempt to parse the config if err := ParseSimpleProcFile(DeviceStatsFile, lf, el); err != nil { return nil, err } return ret, nil }
go
func InterfaceStats() (map[string]InterfaceStat, error) { ret := make(map[string]InterfaceStat, 0) var current InterfaceStat lastline := -1 lastindex := -1 lf := func(index int, line string) error { if lastline == index && lastindex == 16 { ret[current.Device] = current } current = InterfaceStat{} return nil } el := func(line int, index int, elm string) (err error) { switch index { case 0: current.Device = strings.Split(elm, ":")[0] case 1: current.RxBytes, err = strconv.ParseUint(elm, 10, 64) case 2: current.RxPackets, err = strconv.ParseUint(elm, 10, 64) case 3: current.RxErrors, err = strconv.ParseUint(elm, 10, 64) case 4: current.RxDrop, err = strconv.ParseUint(elm, 10, 64) case 5: current.RxFifo, err = strconv.ParseUint(elm, 10, 64) case 6: current.RxFrame, err = strconv.ParseUint(elm, 10, 64) case 7: current.RxCompressed, err = strconv.ParseUint(elm, 10, 64) case 8: current.RxMulticast, err = strconv.ParseUint(elm, 10, 64) case 9: current.TxBytes, err = strconv.ParseUint(elm, 10, 64) case 10: current.TxPackets, err = strconv.ParseUint(elm, 10, 64) case 11: current.TxErrors, err = strconv.ParseUint(elm, 10, 64) case 12: current.TxDrop, err = strconv.ParseUint(elm, 10, 64) case 13: current.TxFifo, err = strconv.ParseUint(elm, 10, 64) case 14: current.TxFrame, err = strconv.ParseUint(elm, 10, 64) case 15: current.TxCompressed, err = strconv.ParseUint(elm, 10, 64) case 16: current.TxMulticast, err = strconv.ParseUint(elm, 10, 64) } lastline = line lastindex = index return } // Now actually attempt to parse the config if err := ParseSimpleProcFile(DeviceStatsFile, lf, el); err != nil { return nil, err } return ret, nil }
[ "func", "InterfaceStats", "(", ")", "(", "map", "[", "string", "]", "InterfaceStat", ",", "error", ")", "{", "ret", ":=", "make", "(", "map", "[", "string", "]", "InterfaceStat", ",", "0", ")", "\n", "var", "current", "InterfaceStat", "\n", "lastline", ...
// Returns the interface statistics as a map keyed off the interface name.
[ "Returns", "the", "interface", "statistics", "as", "a", "map", "keyed", "off", "the", "interface", "name", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/proc/proc.go#L103-L164
2,994
apcera/util
s3util/s3util.go
NewS3Uploader
func NewS3Uploader(bucket, permission string, quiet bool) (*S3Uploader, error) { u := &url.URL{ Scheme: scheme, Host: fmt.Sprintf("%s.%s", bucket, S3_URL), } permission = strings.ToLower(permission) if err := validatePermission(permission); err != nil { return nil, err } uploader := &S3Uploader{ s3url: u, bucketName: bucket, permission: permission, out: os.Stdout, } if quiet { uploader.out = ioutil.Discard } return uploader, nil }
go
func NewS3Uploader(bucket, permission string, quiet bool) (*S3Uploader, error) { u := &url.URL{ Scheme: scheme, Host: fmt.Sprintf("%s.%s", bucket, S3_URL), } permission = strings.ToLower(permission) if err := validatePermission(permission); err != nil { return nil, err } uploader := &S3Uploader{ s3url: u, bucketName: bucket, permission: permission, out: os.Stdout, } if quiet { uploader.out = ioutil.Discard } return uploader, nil }
[ "func", "NewS3Uploader", "(", "bucket", ",", "permission", "string", ",", "quiet", "bool", ")", "(", "*", "S3Uploader", ",", "error", ")", "{", "u", ":=", "&", "url", ".", "URL", "{", "Scheme", ":", "scheme", ",", "Host", ":", "fmt", ".", "Sprintf", ...
// NewS3Uploader configures a new S3 uploader from a uri.
[ "NewS3Uploader", "configures", "a", "new", "S3", "uploader", "from", "a", "uri", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/s3util/s3util.go#L46-L67
2,995
apcera/util
s3util/s3util.go
UploadToS3
func (s *S3Uploader) UploadToS3(fPath string, buf *bytes.Buffer) error { fmt.Fprintf(s.out, "Preparing %q for upload to s3 bucket %q...", filepath.Base(fPath), s.s3url.String()) req, err := s.buildS3Request(filepath.Base(fPath), buf) if err != nil { fmt.Fprintln(s.out, " error") return err } fmt.Fprintln(s.out, " done") fmt.Fprint(s.out, "Uploading...") resp, err := http.DefaultClient.Do(req) if err != nil { fmt.Fprintln(s.out, " error") return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { fmt.Fprintln(s.out, " error") if resp.StatusCode == 403 { fmt.Fprintln(s.out, "Encountered authorization error! Are your keys set correctly?") } errMsg := fmt.Sprintf("received code %d, should have received %d", resp.StatusCode, http.StatusOK) b, err := ioutil.ReadAll(resp.Body) if err == nil { errMsg = fmt.Sprintf("%s\n\nReceived S3 Response: %q", errMsg, string(b)) } return fmt.Errorf(errMsg) } fmt.Fprintln(s.out, " done") return nil }
go
func (s *S3Uploader) UploadToS3(fPath string, buf *bytes.Buffer) error { fmt.Fprintf(s.out, "Preparing %q for upload to s3 bucket %q...", filepath.Base(fPath), s.s3url.String()) req, err := s.buildS3Request(filepath.Base(fPath), buf) if err != nil { fmt.Fprintln(s.out, " error") return err } fmt.Fprintln(s.out, " done") fmt.Fprint(s.out, "Uploading...") resp, err := http.DefaultClient.Do(req) if err != nil { fmt.Fprintln(s.out, " error") return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { fmt.Fprintln(s.out, " error") if resp.StatusCode == 403 { fmt.Fprintln(s.out, "Encountered authorization error! Are your keys set correctly?") } errMsg := fmt.Sprintf("received code %d, should have received %d", resp.StatusCode, http.StatusOK) b, err := ioutil.ReadAll(resp.Body) if err == nil { errMsg = fmt.Sprintf("%s\n\nReceived S3 Response: %q", errMsg, string(b)) } return fmt.Errorf(errMsg) } fmt.Fprintln(s.out, " done") return nil }
[ "func", "(", "s", "*", "S3Uploader", ")", "UploadToS3", "(", "fPath", "string", ",", "buf", "*", "bytes", ".", "Buffer", ")", "error", "{", "fmt", ".", "Fprintf", "(", "s", ".", "out", ",", "\"", "\"", ",", "filepath", ".", "Base", "(", "fPath", ...
// UploadToS3 prepares a buffer for upload to S3.
[ "UploadToS3", "prepares", "a", "buffer", "for", "upload", "to", "S3", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/s3util/s3util.go#L90-L122
2,996
apcera/util
s3util/s3util.go
buildS3Request
func (s *S3Uploader) buildS3Request(fileBase string, buffer *bytes.Buffer) (*http.Request, error) { u := &url.URL{ Scheme: s.s3url.Scheme, Host: s.s3url.Host, Path: fileBase, } // This is a PUT request containing the data buffer. req, err := http.NewRequest("PUT", u.String(), buffer) if err != nil { return nil, err } // FIXME: Send 'Connection: close' header on HTTP requests // as reusing the connection is still prone to EOF/Connection reset errors // in certain network environments... // See: ENGT-9670 // https://stackoverflow.com/questions/17714494/golang-http-request-results-in-eof-errors req.Close = true // Generate MD5 to ensure reliable delivery h := md5.New() if _, err := h.Write(buffer.Bytes()); err != nil { return nil, err } md5 := base64.StdEncoding.EncodeToString(h.Sum(nil)) // Get current time in UTC format for Date header. curTime := time.Now().UTC().Format(time.RFC1123) req.Header.Add("Date", curTime) req.Header.Add("Content-Md5", md5) req.Header.Add("Content-Type", "application/x-gzip") req.Header.Add("X-Amz-Acl", s.permission) authHeader, err := s.buildAuthHeader(md5, curTime, fileBase) if err != nil { return nil, err } req.Header.Add("Authorization", authHeader) // Set content length so we avoid chunked requests. req.ContentLength = int64(buffer.Len()) return req, nil }
go
func (s *S3Uploader) buildS3Request(fileBase string, buffer *bytes.Buffer) (*http.Request, error) { u := &url.URL{ Scheme: s.s3url.Scheme, Host: s.s3url.Host, Path: fileBase, } // This is a PUT request containing the data buffer. req, err := http.NewRequest("PUT", u.String(), buffer) if err != nil { return nil, err } // FIXME: Send 'Connection: close' header on HTTP requests // as reusing the connection is still prone to EOF/Connection reset errors // in certain network environments... // See: ENGT-9670 // https://stackoverflow.com/questions/17714494/golang-http-request-results-in-eof-errors req.Close = true // Generate MD5 to ensure reliable delivery h := md5.New() if _, err := h.Write(buffer.Bytes()); err != nil { return nil, err } md5 := base64.StdEncoding.EncodeToString(h.Sum(nil)) // Get current time in UTC format for Date header. curTime := time.Now().UTC().Format(time.RFC1123) req.Header.Add("Date", curTime) req.Header.Add("Content-Md5", md5) req.Header.Add("Content-Type", "application/x-gzip") req.Header.Add("X-Amz-Acl", s.permission) authHeader, err := s.buildAuthHeader(md5, curTime, fileBase) if err != nil { return nil, err } req.Header.Add("Authorization", authHeader) // Set content length so we avoid chunked requests. req.ContentLength = int64(buffer.Len()) return req, nil }
[ "func", "(", "s", "*", "S3Uploader", ")", "buildS3Request", "(", "fileBase", "string", ",", "buffer", "*", "bytes", ".", "Buffer", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "u", ":=", "&", "url", ".", "URL", "{", "Scheme", ":",...
// buildS3Request constructs an http request for the upload
[ "buildS3Request", "constructs", "an", "http", "request", "for", "the", "upload" ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/s3util/s3util.go#L125-L167
2,997
apcera/util
s3util/s3util.go
buildAuthHeader
func (s *S3Uploader) buildAuthHeader(md5, headerTime, fileName string) (string, error) { access, err := getAuthCredentials() if err != nil { return "", err } // Docs: http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html verStr := fmt.Sprintf("PUT\n%s\napplication/x-gzip\n%s\nx-amz-acl:%s\n/%s", md5, headerTime, s.permission, path.Join(s.bucketName, fileName)) encodedStr := hmac.ComputeHmacSha1(verStr, access.SecretKey) return fmt.Sprintf("AWS %s:%s", access.AccessKey, encodedStr), nil }
go
func (s *S3Uploader) buildAuthHeader(md5, headerTime, fileName string) (string, error) { access, err := getAuthCredentials() if err != nil { return "", err } // Docs: http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html verStr := fmt.Sprintf("PUT\n%s\napplication/x-gzip\n%s\nx-amz-acl:%s\n/%s", md5, headerTime, s.permission, path.Join(s.bucketName, fileName)) encodedStr := hmac.ComputeHmacSha1(verStr, access.SecretKey) return fmt.Sprintf("AWS %s:%s", access.AccessKey, encodedStr), nil }
[ "func", "(", "s", "*", "S3Uploader", ")", "buildAuthHeader", "(", "md5", ",", "headerTime", ",", "fileName", "string", ")", "(", "string", ",", "error", ")", "{", "access", ",", "err", ":=", "getAuthCredentials", "(", ")", "\n", "if", "err", "!=", "nil...
// buildAuthHeader builds an authorization header for S3.
[ "buildAuthHeader", "builds", "an", "authorization", "header", "for", "S3", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/s3util/s3util.go#L170-L181
2,998
apcera/util
procstat/procstat_linux.go
GetProcessStats
func GetProcessStats(pid int) (*ProcessStats, error) { p := &ProcessStats{} // Load and Parse /proc/{pid}/stat to get all the data we need filename := fmt.Sprintf("/proc/%d/stat", pid) b, err := ioutil.ReadFile(filename) if err != nil { return nil, fmt.Errorf("failed to read process stats: %v", err) } fields := strings.Fields(string(b)) // Magic number is the total fields in the file, as documented by proc. if len(fields) != 52 { return nil, fmt.Errorf("failed to parse proc stat file") } // Calculate the ticks for the process. Indexes based on the proc(5) manpage // for user/kernel ticks, as well as its children's user/kernel ticks. totalTicks, err := sum(fields[13], fields[14], fields[15], fields[16]) if err != nil { return nil, fmt.Errorf("failed to calculate process CPU usage: %v", err) } // use float in going from ticks to time to ensure we preserve granularity // below 1 second. p.CpuNs = time.Duration(float64(totalTicks) / float64(ticks) * float64(time.Second)) // Calculate the total resident set pages/size. Index based on man proc(5). totalPages, err := sum(fields[23]) if err != nil { return nil, err } p.RssBytes = totalPages * pagesize return p, nil }
go
func GetProcessStats(pid int) (*ProcessStats, error) { p := &ProcessStats{} // Load and Parse /proc/{pid}/stat to get all the data we need filename := fmt.Sprintf("/proc/%d/stat", pid) b, err := ioutil.ReadFile(filename) if err != nil { return nil, fmt.Errorf("failed to read process stats: %v", err) } fields := strings.Fields(string(b)) // Magic number is the total fields in the file, as documented by proc. if len(fields) != 52 { return nil, fmt.Errorf("failed to parse proc stat file") } // Calculate the ticks for the process. Indexes based on the proc(5) manpage // for user/kernel ticks, as well as its children's user/kernel ticks. totalTicks, err := sum(fields[13], fields[14], fields[15], fields[16]) if err != nil { return nil, fmt.Errorf("failed to calculate process CPU usage: %v", err) } // use float in going from ticks to time to ensure we preserve granularity // below 1 second. p.CpuNs = time.Duration(float64(totalTicks) / float64(ticks) * float64(time.Second)) // Calculate the total resident set pages/size. Index based on man proc(5). totalPages, err := sum(fields[23]) if err != nil { return nil, err } p.RssBytes = totalPages * pagesize return p, nil }
[ "func", "GetProcessStats", "(", "pid", "int", ")", "(", "*", "ProcessStats", ",", "error", ")", "{", "p", ":=", "&", "ProcessStats", "{", "}", "\n\n", "// Load and Parse /proc/{pid}/stat to get all the data we need", "filename", ":=", "fmt", ".", "Sprintf", "(", ...
// GetProcessStats will return the ProcessStats object associated with the given // PID. If it fails to load the stats, then it will return an error.
[ "GetProcessStats", "will", "return", "the", "ProcessStats", "object", "associated", "with", "the", "given", "PID", ".", "If", "it", "fails", "to", "load", "the", "stats", "then", "it", "will", "return", "an", "error", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/procstat/procstat_linux.go#L25-L59
2,999
apcera/util
procstat/procstat_linux.go
sum
func sum(s ...string) (int64, error) { var total int64 for _, v := range s { i, err := strconv.ParseInt(v, 10, 64) if err != nil { return 0, err } total += i } return total, nil }
go
func sum(s ...string) (int64, error) { var total int64 for _, v := range s { i, err := strconv.ParseInt(v, 10, 64) if err != nil { return 0, err } total += i } return total, nil }
[ "func", "sum", "(", "s", "...", "string", ")", "(", "int64", ",", "error", ")", "{", "var", "total", "int64", "\n", "for", "_", ",", "v", ":=", "range", "s", "{", "i", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "v", ",", "10", ",", "6...
// sum will convert the list of strings into int64s and total them together.
[ "sum", "will", "convert", "the", "list", "of", "strings", "into", "int64s", "and", "total", "them", "together", "." ]
7a50bc84ee48450f6838847f84fde2d806f8a33a
https://github.com/apcera/util/blob/7a50bc84ee48450f6838847f84fde2d806f8a33a/procstat/procstat_linux.go#L62-L72