_id
stringlengths
2
7
title
stringlengths
1
118
partition
stringclasses
3 values
text
stringlengths
52
85.5k
language
stringclasses
1 value
meta_information
dict
q12000
Copy
train
func Copy(dest, source string) error { srcStat, err := os.Lstat(source) if err != nil { return err } if srcStat.IsDir() { files, err := ioutil.ReadDir(source) if err != nil { return err } if err := os.MkdirAll(dest, srcStat.Mode()); err != nil && !os.IsExist(err) { return err } for _, file := range files { if err := Copy(dest+"/"+file.Name(), source+"/"+file.Name()); err != nil { return err } } return nil // ### return, copy done ### } // Symlink handling if srcStat.Mode()&os.ModeSymlink != 0 { target, err := os.Readlink(source) if err != nil { return err } return os.Symlink(target, dest) // ### return, copy done ### } srcFile, err := os.Open(source) if err != nil { return err } defer srcFile.Close() dstFile, err := os.Create(dest) if err != nil { return err } defer dstFile.Close() if _, err = io.Copy(dstFile, srcFile); err != nil { return err } return os.Chmod(dest, srcStat.Mode()) }
go
{ "resource": "" }
q12001
Int64
train
func Int64(v interface{}) (int64, bool) { switch reflect.TypeOf(v).Kind() { case reflect.Int: return int64(v.(int)), true case reflect.Int8: return int64(v.(int8)), true case reflect.Int16: return int64(v.(int16)), true case reflect.Int32: return int64(v.(int32)), true case reflect.Int64: return v.(int64), true case reflect.Float32: return int64(v.(float32)), true case reflect.Float64: return int64(v.(float64)), true } return 0, false }
go
{ "resource": "" }
q12002
Uint64
train
func Uint64(v interface{}) (uint64, bool) { switch reflect.TypeOf(v).Kind() { case reflect.Uint: return uint64(v.(uint)), true case reflect.Uint8: return uint64(v.(uint8)), true case reflect.Uint16: return uint64(v.(uint16)), true case reflect.Uint32: return uint64(v.(uint32)), true case reflect.Uint64: return v.(uint64), true } return 0, false }
go
{ "resource": "" }
q12003
Float32
train
func Float32(v interface{}) (float32, bool) { switch reflect.TypeOf(v).Kind() { case reflect.Int: return float32(v.(int)), true case reflect.Uint: return float32(v.(uint)), true case reflect.Int8: return float32(v.(int8)), true case reflect.Uint8: return float32(v.(uint8)), true case reflect.Int16: return float32(v.(int16)), true case reflect.Uint16: return float32(v.(uint16)), true case reflect.Int32: return float32(v.(int32)), true case reflect.Uint32: return float32(v.(uint32)), true case reflect.Int64: return float32(v.(int64)), true case reflect.Uint64: return float32(v.(uint64)), true case reflect.Float32: return v.(float32), true case reflect.Float64: return float32(v.(float64)), true } return 0, false }
go
{ "resource": "" }
q12004
UnsafeCopy
train
func UnsafeCopy(dst, src interface{}) { dstValue := reflect.ValueOf(dst) srcValue := reflect.ValueOf(src) UnsafeCopyValue(dstValue, srcValue) }
go
{ "resource": "" }
q12005
SetMemberByName
train
func SetMemberByName(ptrToStruct interface{}, name string, data interface{}) { structVal := reflect.Indirect(reflect.ValueOf(ptrToStruct)) member := structVal.FieldByName(name) SetValue(member, data) }
go
{ "resource": "" }
q12006
SetMemberByIndex
train
func SetMemberByIndex(ptrToStruct interface{}, idx int, data interface{}) { structVal := reflect.Indirect(reflect.ValueOf(ptrToStruct)) member := structVal.Field(idx) SetValue(member, data) }
go
{ "resource": "" }
q12007
Write
train
func (b ByteWriter) Write(data []byte) (int, error) { start := len(*b.buffer) size := len(data) capacity := cap(*b.buffer) if start+size > capacity { size := capacity - start *b.buffer = (*b.buffer)[:capacity] copy((*b.buffer)[start:], data[:size]) return size, io.EOF } *b.buffer = (*b.buffer)[:start+size] copy((*b.buffer)[start:], data) return size, nil }
go
{ "resource": "" }
q12008
NewTransition
train
func NewTransition(nextState ParserStateID, flags ParserFlag, callback ParsedFunc) Transition { return Transition{ nextState: nextState, flags: flags, callback: callback, } }
go
{ "resource": "" }
q12009
NewTransitionParser
train
func NewTransitionParser() TransitionParser { return TransitionParser{ lookup: []string{}, tokens: []*tcontainer.TrieNode{}, stack: []ParserStateID{}, } }
go
{ "resource": "" }
q12010
GetStateID
train
func (parser *TransitionParser) GetStateID(stateName string) ParserStateID { if len(stateName) == 0 { return ParserStateStop } for id, name := range parser.lookup { if name == stateName { return ParserStateID(id) // ### return, found ### } } id := ParserStateID(len(parser.lookup)) parser.lookup = append(parser.lookup, stateName) parser.tokens = append(parser.tokens, nil) return id }
go
{ "resource": "" }
q12011
GetStateName
train
func (parser *TransitionParser) GetStateName(id ParserStateID) string { if id < ParserStateID(len(parser.lookup)) { return parser.lookup[id] } return "" }
go
{ "resource": "" }
q12012
AddDirectives
train
func (parser *TransitionParser) AddDirectives(directives []TransitionDirective) { for _, dir := range directives { parser.Add(dir.State, dir.Token, dir.NextState, dir.Flags, dir.Callback) } }
go
{ "resource": "" }
q12013
Add
train
func (parser *TransitionParser) Add(stateName string, token string, nextStateName string, flags ParserFlag, callback ParsedFunc) { nextStateID := parser.GetStateID(nextStateName) parser.AddTransition(stateName, NewTransition(nextStateID, flags, callback), token) }
go
{ "resource": "" }
q12014
Stop
train
func (parser *TransitionParser) Stop(stateName string, token string, flags ParserFlag, callback ParsedFunc) { parser.AddTransition(stateName, NewTransition(ParserStateStop, flags, callback), token) }
go
{ "resource": "" }
q12015
AddTransition
train
func (parser *TransitionParser) AddTransition(stateName string, newTrans Transition, token string) { stateID := parser.GetStateID(stateName) if state := parser.tokens[stateID]; state == nil { parser.tokens[stateID] = tcontainer.NewTrie([]byte(token), newTrans) } else { parser.tokens[stateID] = state.Add([]byte(token), newTrans) } }
go
{ "resource": "" }
q12016
Parse
train
func (parser *TransitionParser) Parse(data []byte, state string) ([]byte, ParserStateID) { currentStateID := parser.GetStateID(state) if currentStateID == ParserStateStop { return nil, currentStateID // ### return, immediate stop ### } currentState := parser.tokens[currentStateID] dataLen := len(data) readStartIdx := 0 continueIdx := 0 for parseIdx := 0; parseIdx < dataLen; parseIdx++ { node := currentState.MatchStart(data[parseIdx:]) if node == nil { continue // ### continue, no match ### } t := node.Payload.(Transition) if t.callback != nil { if t.flags&ParserFlagInclude != 0 { t.callback(data[readStartIdx:parseIdx+node.PathLen], currentStateID) } else { t.callback(data[readStartIdx:parseIdx], currentStateID) } } // Move the reader if t.flags&ParserFlagContinue == 0 { parseIdx += node.PathLen - 1 } else { parseIdx-- } continueIdx = parseIdx + 1 if t.flags&ParserFlagAppend == 0 { readStartIdx = continueIdx } nextStateID := t.nextState // Pop before push to allow both at the same time if t.flags&ParserFlagPop != 0 { stackLen := len(parser.stack) if stackLen > 0 { nextStateID = parser.stack[stackLen-1] parser.stack = parser.stack[:stackLen-1] } } if t.flags&ParserFlagPush != 0 { parser.stack = append(parser.stack, currentStateID) } // Transition to next currentStateID = nextStateID if currentStateID == ParserStateStop { break // ### break, stop state ### } currentState = parser.tokens[currentStateID] } if readStartIdx == dataLen { return nil, currentStateID // ### return, everything parsed ### } return data[readStartIdx:], currentStateID }
go
{ "resource": "" }
q12017
SplitAddressToURI
train
func SplitAddressToURI(addressString string, defaultProtocol string) (uri URI, err error) { portString := "" uri.Protocol, uri.Address, portString, err = SplitAddress(addressString, defaultProtocol) portNum, _ := strconv.ParseInt(portString, 10, 16) uri.Port = uint16(portNum) return uri, err }
go
{ "resource": "" }
q12018
IsDisconnectedError
train
func IsDisconnectedError(err error) bool { if err == io.EOF { return true // ### return, closed stream ### } netErr, isNetErr := err.(*net.OpError) if isNetErr { errno, isErrno := netErr.Err.(syscall.Errno) if isErrno { switch errno { default: case syscall.ECONNRESET: return true // ### return, close connection ### } } } return false }
go
{ "resource": "" }
q12019
String
train
func (c CursorPosition) String() string { return "\x1b[" + strconv.Itoa(c.X) + ";" + strconv.Itoa(c.Y) + "H" }
go
{ "resource": "" }
q12020
Add
train
func (wg *WaitGroup) Add(delta int) { atomic.AddInt32(&wg.counter, int32(delta)) }
go
{ "resource": "" }
q12021
IncWhenDone
train
func (wg *WaitGroup) IncWhenDone() { spin := NewSpinner(SpinPriorityHigh) for !atomic.CompareAndSwapInt32(&wg.counter, 0, 1) { spin.Yield() } }
go
{ "resource": "" }
q12022
Wait
train
func (wg *WaitGroup) Wait() { spin := NewSpinner(SpinPriorityHigh) for wg.Active() { spin.Yield() } }
go
{ "resource": "" }
q12023
WaitFor
train
func (wg *WaitGroup) WaitFor(timeout time.Duration) bool { if timeout == time.Duration(0) { wg.Wait() return true // ### return, always true ### } start := time.Now() spin := NewSpinner(SpinPriorityHigh) for wg.Active() { if time.Since(start) > timeout { return false // ### return, timed out ### } spin.Yield() } return true }
go
{ "resource": "" }
q12024
Write
train
func (log *logCache) Write(message []byte) (int, error) { log.flushing.Lock() defer log.flushing.Unlock() if len(message) > 0 { messageCopy := make([]byte, len(message)) copy(messageCopy, message) log.messages = append(log.messages, messageCopy) } return len(message), nil }
go
{ "resource": "" }
q12025
Flush
train
func (log *logCache) Flush(writer io.Writer) { log.flushing.Lock() defer log.flushing.Unlock() for _, message := range log.messages { writer.Write(message) } log.messages = [][]byte{} }
go
{ "resource": "" }
q12026
Get
train
func (b *BytePool) Get(size int) []byte { switch { case size == 0: return []byte{} case size <= tiny: return b.tinySlab.getSlice(size) case size <= small: return b.smallSlab.getSlice(size) case size <= medium: return b.mediumSlab.getSlice(size) case size <= large: return b.largeSlab.getSlice(size) case size <= huge: return b.hugeSlab.getSlice(size) default: return make([]byte, size) } }
go
{ "resource": "" }
q12027
ReturnAfter
train
func ReturnAfter(runtimeLimit time.Duration, callback func()) bool { timeout := time.NewTimer(runtimeLimit) callOk := make(chan bool) go func() { callback() timeout.Stop() callOk <- true }() select { case <-timeout.C: return false case <-callOk: return true } }
go
{ "resource": "" }
q12028
GetUid
train
func GetUid(name string) (int, error) { switch name { case "nobody": return NobodyUid, nil case "root": return RootUid, nil default: userInfo, err := user.Lookup(name) if err != nil { return 0, err } return strconv.Atoi(userInfo.Uid) } }
go
{ "resource": "" }
q12029
GetGid
train
func GetGid(name string) (int, error) { switch name { case "nobody": return NobodyGid, nil case "root": return RootGid, nil default: groupInfo, err := user.LookupGroup(name) if err != nil { return 0, err } return strconv.Atoi(groupInfo.Gid) } }
go
{ "resource": "" }
q12030
NewFuse
train
func NewFuse() *Fuse { return &Fuse{ signal: sync.NewCond(new(sync.Mutex)), burned: new(int32), } }
go
{ "resource": "" }
q12031
Wait
train
func (fuse Fuse) Wait() { fuse.signal.L.Lock() defer fuse.signal.L.Unlock() if fuse.IsBurned() { fuse.signal.Wait() } }
go
{ "resource": "" }
q12032
Max3I
train
func Max3I(a, b, c int) int { max := a if b > max { max = b } if c > max { max = c } return max }
go
{ "resource": "" }
q12033
Max3Int64
train
func Max3Int64(a, b, c int64) int64 { max := a if b > max { max = b } if c > max { max = c } return max }
go
{ "resource": "" }
q12034
Max3Uint64
train
func Max3Uint64(a, b, c uint64) uint64 { max := a if b > max { max = b } if c > max { max = c } return max }
go
{ "resource": "" }
q12035
Min3I
train
func Min3I(a, b, c int) int { min := a if b < min { min = b } if c < min { min = c } return min }
go
{ "resource": "" }
q12036
Min3Int64
train
func Min3Int64(a, b, c int64) int64 { min := a if b < min { min = b } if c < min { min = c } return min }
go
{ "resource": "" }
q12037
Min3Uint64
train
func Min3Uint64(a, b, c uint64) uint64 { min := a if b < min { min = b } if c < min { min = c } return min }
go
{ "resource": "" }
q12038
TryConvertToMarshalMap
train
func TryConvertToMarshalMap(value interface{}, formatKey func(string) string) interface{} { valueMeta := reflect.ValueOf(value) switch valueMeta.Kind() { default: return value case reflect.Array, reflect.Slice: arrayLen := valueMeta.Len() converted := make([]interface{}, arrayLen) for i := 0; i < arrayLen; i++ { converted[i] = TryConvertToMarshalMap(valueMeta.Index(i).Interface(), formatKey) } return converted case reflect.Map: converted := NewMarshalMap() keys := valueMeta.MapKeys() for _, keyMeta := range keys { strKey, isString := keyMeta.Interface().(string) if !isString { continue } if formatKey != nil { strKey = formatKey(strKey) } val := valueMeta.MapIndex(keyMeta).Interface() converted[strKey] = TryConvertToMarshalMap(val, formatKey) } return converted // ### return, converted MarshalMap ### } }
go
{ "resource": "" }
q12039
Clone
train
func (mmap MarshalMap) Clone() MarshalMap { clone := cloneMap(reflect.ValueOf(mmap)) return clone.Interface().(MarshalMap) }
go
{ "resource": "" }
q12040
Bool
train
func (mmap MarshalMap) Bool(key string) (bool, error) { val, exists := mmap.Value(key) if !exists { return false, fmt.Errorf(`"%s" is not set`, key) } boolValue, isBool := val.(bool) if !isBool { return false, fmt.Errorf(`"%s" is expected to be a boolean`, key) } return boolValue, nil }
go
{ "resource": "" }
q12041
Uint
train
func (mmap MarshalMap) Uint(key string) (uint64, error) { val, exists := mmap.Value(key) if !exists { return 0, fmt.Errorf(`"%s" is not set`, key) } if intVal, isNumber := treflect.Uint64(val); isNumber { return intVal, nil } return 0, fmt.Errorf(`"%s" is expected to be an unsigned number type`, key) }
go
{ "resource": "" }
q12042
Int
train
func (mmap MarshalMap) Int(key string) (int64, error) { val, exists := mmap.Value(key) if !exists { return 0, fmt.Errorf(`"%s" is not set`, key) } if intVal, isNumber := treflect.Int64(val); isNumber { return intVal, nil } return 0, fmt.Errorf(`"%s" is expected to be a signed number type`, key) }
go
{ "resource": "" }
q12043
Float
train
func (mmap MarshalMap) Float(key string) (float64, error) { val, exists := mmap.Value(key) if !exists { return 0, fmt.Errorf(`"%s" is not set`, key) } if floatVal, isNumber := treflect.Float64(val); isNumber { return floatVal, nil } return 0, fmt.Errorf(`"%s" is expected to be a signed number type`, key) }
go
{ "resource": "" }
q12044
Duration
train
func (mmap MarshalMap) Duration(key string) (time.Duration, error) { val, exists := mmap.Value(key) if !exists { return time.Duration(0), fmt.Errorf(`"%s" is not set`, key) } switch val.(type) { case time.Duration: return val.(time.Duration), nil case string: return time.ParseDuration(val.(string)) } return time.Duration(0), fmt.Errorf(`"%s" is expected to be a duration or string`, key) }
go
{ "resource": "" }
q12045
String
train
func (mmap MarshalMap) String(key string) (string, error) { val, exists := mmap.Value(key) if !exists { return "", fmt.Errorf(`"%s" is not set`, key) } strValue, isString := val.(string) if !isString { return "", fmt.Errorf(`"%s" is expected to be a string`, key) } return strValue, nil }
go
{ "resource": "" }
q12046
StringSlice
train
func (mmap MarshalMap) StringSlice(key string) ([]string, error) { return mmap.StringArray(key) }
go
{ "resource": "" }
q12047
Int64Slice
train
func (mmap MarshalMap) Int64Slice(key string) ([]int64, error) { return mmap.Int64Array(key) }
go
{ "resource": "" }
q12048
StringSliceMap
train
func (mmap MarshalMap) StringSliceMap(key string) (map[string][]string, error) { return mmap.StringArrayMap(key) }
go
{ "resource": "" }
q12049
Delete
train
func (mmap MarshalMap) Delete(key string) { mmap.resolvePath(key, mmap, func(p, k reflect.Value, v interface{}) { if v != nil { p.SetMapIndex(k, reflect.Value{}) } }) }
go
{ "resource": "" }
q12050
Set
train
func (mmap MarshalMap) Set(key string, val interface{}) { mmap.resolvePath(key, mmap, func(p, k reflect.Value, v interface{}) { p.SetMapIndex(k, reflect.ValueOf(val)) }) }
go
{ "resource": "" }
q12051
Clone
train
func Clone(v interface{}) interface{} { value := reflect.ValueOf(v) copy := clone(value) return copy.Interface() }
go
{ "resource": "" }
q12052
SwitchVar
train
func SwitchVar(flagVar *bool, short string, long string, usage string) *bool { return BoolVar(flagVar, short, long, false, usage) }
go
{ "resource": "" }
q12053
BoolVar
train
func BoolVar(flagVar *bool, short string, long string, value bool, usage string) *bool { flag.BoolVar(flagVar, short, value, usage) flag.BoolVar(flagVar, long, value, usage) addKeyDescription(short, long, value, usage) return flagVar }
go
{ "resource": "" }
q12054
IntVar
train
func IntVar(flagVar *int, short string, long string, value int, usage string) *int { flag.IntVar(flagVar, short, value, usage) flag.IntVar(flagVar, long, value, usage) addKeyDescription(short, long, value, usage) return flagVar }
go
{ "resource": "" }
q12055
Int64Var
train
func Int64Var(flagVar *int64, short string, long string, value int64, usage string) *int64 { flag.Int64Var(flagVar, short, value, usage) flag.Int64Var(flagVar, long, value, usage) addKeyDescription(short, long, value, usage) return flagVar }
go
{ "resource": "" }
q12056
Float64Var
train
func Float64Var(flagVar *float64, short string, long string, value float64, usage string) *float64 { flag.Float64Var(flagVar, short, value, usage) flag.Float64Var(flagVar, long, value, usage) addKeyDescription(short, long, value, usage) return flagVar }
go
{ "resource": "" }
q12057
StringVar
train
func StringVar(flagVar *string, short string, long string, value string, usage string) *string { flag.StringVar(flagVar, short, value, usage) flag.StringVar(flagVar, long, value, usage) addKeyDescription(short, long, value, usage) return flagVar }
go
{ "resource": "" }
q12058
Switch
train
func Switch(short string, long string, usage string) *bool { var flagVar bool return SwitchVar(&flagVar, short, long, usage) }
go
{ "resource": "" }
q12059
Bool
train
func Bool(short string, long string, value bool, usage string) *bool { flagVar := value return BoolVar(&flagVar, short, long, value, usage) }
go
{ "resource": "" }
q12060
Int
train
func Int(short string, long string, value int, usage string) *int { flagVar := value return IntVar(&flagVar, short, long, value, usage) }
go
{ "resource": "" }
q12061
Int64
train
func Int64(short string, long string, value int64, usage string) *int64 { flagVar := value return Int64Var(&flagVar, short, long, value, usage) }
go
{ "resource": "" }
q12062
Float64
train
func Float64(short string, long string, value float64, usage string) *float64 { flagVar := value return Float64Var(&flagVar, short, long, value, usage) }
go
{ "resource": "" }
q12063
String
train
func String(short string, long string, value string, usage string) *string { flagVar := value return StringVar(&flagVar, short, long, value, usage) }
go
{ "resource": "" }
q12064
PrintFlags
train
func PrintFlags(header string) { fmt.Println(header) valueFmt := fmt.Sprintf("%%-%ds\tdefault: %%-%ds\t%%-%ds\n", tabWidth[tabKey], tabWidth[tabValue], tabWidth[tabUsage]) for _, desc := range descriptions { fmt.Printf(valueFmt, desc.flagKey, desc.value, desc.usage) } }
go
{ "resource": "" }
q12065
Reset
train
func (buffer *BufferedReader) Reset(sequence uint64) { buffer.end = 0 buffer.incomplete = true }
go
{ "resource": "" }
q12066
ResetGetIncomplete
train
func (buffer *BufferedReader) ResetGetIncomplete() []byte { remains := buffer.data[:buffer.end] buffer.Reset(0) return remains }
go
{ "resource": "" }
q12067
extractMessage
train
func (buffer *BufferedReader) extractMessage(messageLen int, msgStartIdx int) ([]byte, int) { nextMsgIdx := msgStartIdx + messageLen if nextMsgIdx > buffer.end { return nil, 0 // ### return, incomplete ### } if buffer.flags&BufferedReaderFlagEverything != 0 { msgStartIdx = 0 } return buffer.data[msgStartIdx:nextMsgIdx], nextMsgIdx }
go
{ "resource": "" }
q12068
parseDelimiter
train
func (buffer *BufferedReader) parseDelimiter() ([]byte, int) { delimiterIdx := bytes.Index(buffer.data[:buffer.end], buffer.delimiter) if delimiterIdx == -1 { return nil, 0 // ### return, incomplete ### } messageLen := delimiterIdx if buffer.flags&BufferedReaderFlagEverything != 0 { messageLen += len(buffer.delimiter) } data, nextMsgIdx := buffer.extractMessage(messageLen, 0) if data != nil && buffer.flags&BufferedReaderFlagEverything == 0 { nextMsgIdx += len(buffer.delimiter) } return data, nextMsgIdx }
go
{ "resource": "" }
q12069
parseMLE16
train
func (buffer *BufferedReader) parseMLE16() ([]byte, int) { var messageLen uint16 reader := bytes.NewReader(buffer.data[buffer.paramMLE:buffer.end]) err := binary.Read(reader, buffer.encoding, &messageLen) if err != nil { return nil, -1 // ### return, malformed ### } return buffer.extractMessage(int(messageLen), buffer.paramMLE+2) }
go
{ "resource": "" }
q12070
parseDelimiterRegex
train
func (buffer *BufferedReader) parseDelimiterRegex() ([]byte, int) { startOffset := 0 for { delimiterIdx := buffer.delimiterRegexp.FindIndex(buffer.data[startOffset:buffer.end]) if delimiterIdx == nil { return nil, 0 // ### return, incomplete ### } // If we do end of message parsing, we're done if buffer.flags&BufferedReaderFlagRegexStart != BufferedReaderFlagRegexStart { return buffer.extractMessage(delimiterIdx[1], 0) // ### done, end of line ### } // We're done if this is the second pass (start offset > 0) // We're done if we have data before the match (incomplete message) if startOffset > 0 || delimiterIdx[0] > 0 { return buffer.extractMessage(delimiterIdx[0]+startOffset, 0) // ### done, start of line ### } // Found delimiter at start of data, look for the start of a second message. // We don't need to add startOffset here as we never reach this if startOffset != 0 startOffset = delimiterIdx[1] } }
go
{ "resource": "" }
q12071
ReadAll
train
func (buffer *BufferedReader) ReadAll(reader io.Reader, callback BufferReadCallback) error { for { data, more, err := buffer.ReadOne(reader) if data != nil && callback != nil { callback(data) } if err != nil { return err // ### return, error ### } if !more { return nil // ### return, done ### } } }
go
{ "resource": "" }
q12072
NewLogScope
train
func NewLogScope(name string) LogScope { scopeMarker := tfmt.Colorizef(tfmt.DarkGray, tfmt.NoBackground, "[%s] ", name) return LogScope{ name: name, Error: log.New(logLogger{Error}, scopeMarker, 0), Warning: log.New(logLogger{Warning}, scopeMarker, 0), Note: log.New(logLogger{Note}, scopeMarker, 0), Debug: log.New(logLogger{Debug}, scopeMarker, 0), } }
go
{ "resource": "" }
q12073
SetVerbosity
train
func SetVerbosity(loglevel Verbosity) { Error = log.New(logDisabled, "", 0) Warning = log.New(logDisabled, "", 0) Note = log.New(logDisabled, "", 0) Debug = log.New(logDisabled, "", 0) switch loglevel { default: fallthrough case VerbosityDebug: Debug = log.New(&logEnabled, tfmt.Colorize(tfmt.Cyan, tfmt.NoBackground, "Debug: "), 0) fallthrough case VerbosityNote: Note = log.New(&logEnabled, "", 0) fallthrough case VerbosityWarning: Warning = log.New(&logEnabled, tfmt.Colorize(tfmt.Yellow, tfmt.NoBackground, "Warning: "), 0) fallthrough case VerbosityError: Error = log.New(&logEnabled, tfmt.Colorize(tfmt.Red, tfmt.NoBackground, "ERROR: "), log.Lshortfile) } }
go
{ "resource": "" }
q12074
SetCacheWriter
train
func SetCacheWriter() { if _, isCache := logEnabled.writer.(*logCache); !isCache { logEnabled.writer = new(logCache) } }
go
{ "resource": "" }
q12075
RoundTrip
train
func (s SocketRoundtripper) RoundTrip(req *http.Request) (*http.Response, error) { if req.Body != nil { defer req.Body.Close() } socket, err := net.Dial("unix", s.path) if err != nil { return nil, err } defer socket.Close() socket.SetWriteDeadline(time.Now().Add(5 * time.Second)) if err := req.Write(socket); err != nil { return nil, err } socket.SetReadDeadline(time.Now().Add(5 * time.Second)) reader := bufio.NewReader(socket) return http.ReadResponse(reader, req) }
go
{ "resource": "" }
q12076
NewMetrics
train
func NewMetrics() *Metrics { return &Metrics{ store: make(map[string]*int64), rates: make(map[string]*rate), storeGuard: new(sync.RWMutex), rateGuard: new(sync.RWMutex), } }
go
{ "resource": "" }
q12077
Set
train
func (met *Metrics) Set(name string, value int64) { atomic.StoreInt64(met.get(name), value) }
go
{ "resource": "" }
q12078
Inc
train
func (met *Metrics) Inc(name string) { atomic.AddInt64(met.get(name), 1) }
go
{ "resource": "" }
q12079
Dec
train
func (met *Metrics) Dec(name string) { atomic.AddInt64(met.get(name), -1) }
go
{ "resource": "" }
q12080
Add
train
func (met *Metrics) Add(name string, value int64) { atomic.AddInt64(met.get(name), value) }
go
{ "resource": "" }
q12081
Get
train
func (met *Metrics) Get(name string) (int64, error) { if metric := met.tryGetMetric(name); metric != nil { return atomic.LoadInt64(metric), nil } if rate := met.tryGetRate(name); rate != nil { return *rate, nil } // Neither rate nor metric found return 0, fmt.Errorf("Metric %s not found", name) }
go
{ "resource": "" }
q12082
Dump
train
func (met *Metrics) Dump() ([]byte, error) { snapshot := make(map[string]int64) met.storeGuard.RLock() for key, value := range met.store { snapshot[key] = atomic.LoadInt64(value) } met.storeGuard.RUnlock() met.rateGuard.RLock() for key, rate := range met.rates { snapshot[key] = rate.value } met.rateGuard.RUnlock() return json.Marshal(snapshot) }
go
{ "resource": "" }
q12083
ResetMetrics
train
func (met *Metrics) ResetMetrics() { met.storeGuard.Lock() for key := range met.store { switch key { case MetricProcessStart, MetricGoRoutines, MetricGoVersion: // ignore default: *met.store[key] = 0 } } met.storeGuard.Unlock() met.rateGuard.Lock() for _, rate := range met.rates { rate.lastSample = 0 rate.value = 0 rate.index = 0 rate.samples.Set(0) } met.rateGuard.Unlock() }
go
{ "resource": "" }
q12084
FetchAndReset
train
func (met *Metrics) FetchAndReset(keys ...string) map[string]int64 { state := make(map[string]int64) met.storeGuard.Lock() for _, key := range keys { if val, exists := met.store[key]; exists { state[key] = *val *val = 0 } } met.storeGuard.Unlock() met.rateGuard.Lock() for _, key := range keys { if rate, exists := met.rates[key]; exists { rate.lastSample = 0 rate.value = 0 rate.index = 0 rate.samples.Set(0) } } met.rateGuard.Unlock() return state }
go
{ "resource": "" }
q12085
UpdateSystemMetrics
train
func (met *Metrics) UpdateSystemMetrics() { stats := new(runtime.MemStats) runtime.ReadMemStats(stats) met.SetI(MetricGoRoutines, runtime.NumGoroutine()) met.Set(MetricMemoryAllocated, int64(stats.Alloc)) met.SetB(MetricMemoryGCEnabled, stats.EnableGC) met.Set(MetricMemoryNumObjects, int64(stats.HeapObjects)) }
go
{ "resource": "" }
q12086
NewTrie
train
func NewTrie(data []byte, payload interface{}) *TrieNode { return &TrieNode{ suffix: data, children: []*TrieNode{}, longestPath: len(data), PathLen: len(data), Payload: payload, } }
go
{ "resource": "" }
q12087
ForEach
train
func (node *TrieNode) ForEach(callback func(*TrieNode)) { callback(node) for _, child := range node.children { child.ForEach(callback) } }
go
{ "resource": "" }
q12088
Match
train
func (node *TrieNode) Match(data []byte) *TrieNode { dataLen := len(data) suffixLen := len(node.suffix) if dataLen < suffixLen { return nil // ### return, cannot be fully matched ### } for i := 0; i < suffixLen; i++ { if data[i] != node.suffix[i] { return nil // ### return, no match ### } } if dataLen == suffixLen { if node.PathLen > 0 { return node // ### return, full match ### } return nil // ### return, invalid match ### } data = data[suffixLen:] numChildren := len(node.children) for i := 0; i < numChildren; i++ { matchedNode := node.children[i].Match(data) if matchedNode != nil { return matchedNode // ### return, match found ### } } return nil // ### return, no valid path ### }
go
{ "resource": "" }
q12089
Push
train
func (stack *ErrorStack) Push(err error) bool { if err != nil { stack.errors = append(stack.errors, err) return true } return false }
go
{ "resource": "" }
q12090
Pushf
train
func (stack *ErrorStack) Pushf(message string, args ...interface{}) { stack.errors = append(stack.errors, fmt.Errorf(message, args...)) }
go
{ "resource": "" }
q12091
PushAndDescribe
train
func (stack *ErrorStack) PushAndDescribe(message string, err error) bool { if err != nil { stack.errors = append(stack.errors, fmt.Errorf(message+" %s", err.Error())) return true } return false }
go
{ "resource": "" }
q12092
Pop
train
func (stack *ErrorStack) Pop() error { if len(stack.errors) == 0 { return nil } err := stack.errors[len(stack.errors)-1] stack.errors = stack.errors[:len(stack.errors)-1] return err }
go
{ "resource": "" }
q12093
Error
train
func (stack ErrorStack) Error() string { if len(stack.errors) == 0 { return "" } return stack.formatter(stack.errors) }
go
{ "resource": "" }
q12094
ErrorStackFormatNumbered
train
func ErrorStackFormatNumbered(errors []error) string { errString := "" lastIdx := len(errors) - 1 for i := 0; i < lastIdx; i++ { errString = fmt.Sprintf("%s%d: %s\n", errString, i+1, errors[i].Error()) } errString = fmt.Sprintf("%s%d: %s", errString, lastIdx+1, errors[lastIdx].Error()) return errString }
go
{ "resource": "" }
q12095
NewMetricServer
train
func NewMetricServer() *MetricServer { return &MetricServer{ metrics: Metric, running: false, updates: time.NewTicker(time.Second), } }
go
{ "resource": "" }
q12096
NewMetricServerFor
train
func NewMetricServerFor(m *Metrics) *MetricServer { return &MetricServer{ metrics: m, running: false, updates: time.NewTicker(time.Second), } }
go
{ "resource": "" }
q12097
Stop
train
func (server *MetricServer) Stop() { server.running = false server.updates.Stop() if server.listen != nil { if err := server.listen.Close(); err != nil { log.Print("Metrics: ", err) } } }
go
{ "resource": "" }
q12098
NewQueueWithSpinner
train
func NewQueueWithSpinner(capacity uint32, spinner Spinner) Queue { return Queue{ items: make([]interface{}, capacity), read: newQueueAccess(), write: newQueueAccess(), locked: new(int32), capacity: uint64(capacity), spin: spinner, } }
go
{ "resource": "" }
q12099
Push
train
func (q *Queue) Push(item interface{}) error { if atomic.LoadInt32(q.locked) == 1 { return LockedError{"Queue is locked"} // ### return, closed ### } // Get ticket and slot ticket := atomic.AddUint64(q.write.next, 1) - 1 slot := ticket % q.capacity spin := q.spin // Wait for pending reads on slot for ticket-atomic.LoadUint64(q.read.processing) >= q.capacity { spin.Yield() } q.items[slot] = item // Wait for previous writers to finish writing for ticket != atomic.LoadUint64(q.write.processing) { spin.Yield() } atomic.AddUint64(q.write.processing, 1) return nil }
go
{ "resource": "" }