_id
stringlengths
2
7
title
stringlengths
1
118
partition
stringclasses
3 values
text
stringlengths
52
85.5k
language
stringclasses
1 value
meta_information
dict
q37100
deleteAssociatedReportsForDevice
train
func deleteAssociatedReportsForDevice(d models.Device, w http.ResponseWriter) error { reports, err := dbClient.GetDeviceReportByDeviceName(d.Name) if err != nil { http.Error(w, err.Error(), http.StatusServiceUnavailable) LoggingClient.Error(err.Error()) return err } // Delete the associated reports for _, r...
go
{ "resource": "" }
q37101
setLastConnected
train
func setLastConnected(d models.Device, time int64, notify bool, w http.ResponseWriter, ctx context.Context) error { d.LastConnected = time if err := dbClient.UpdateDevice(d); err != nil { LoggingClient.Error(err.Error()) http.Error(w, err.Error(), http.StatusServiceUnavailable) return err } if notify { not...
go
{ "resource": "" }
q37102
notifyDeviceAssociates
train
func notifyDeviceAssociates(d models.Device, action string, ctx context.Context) error { // Post the notification to the notifications service postNotification(d.Name, action, ctx) // Callback for device service ds, err := dbClient.GetDeviceServiceById(d.Service.Id) if err != nil { LoggingClient.Error(err.Error...
go
{ "resource": "" }
q37103
Retry
train
func Retry(useProfile string, timeout int, wait *sync.WaitGroup, ch chan error) { until := time.Now().Add(time.Millisecond * time.Duration(timeout)) for time.Now().Before(until) { var err error //When looping, only handle configuration if it hasn't already been set. if Configuration == nil { Configuration, e...
go
{ "resource": "" }
q37104
getBody
train
func getBody(resp *http.Response) ([]byte, error) { body, err := ioutil.ReadAll(resp.Body) return body, err }
go
{ "resource": "" }
q37105
LoadScheduler
train
func LoadScheduler() error { // ensure maps are clean clearMaps() // ensure queue is empty clearQueue() LoggingClient.Info("loading intervals, interval actions ...") // load data from support-scheduler database err := loadSupportSchedulerDBInformation() if err != nil { LoggingClient.Error("failed to load ...
go
{ "resource": "" }
q37106
getSchedulerDBIntervals
train
func getSchedulerDBIntervals() ([]contract.Interval, error) { var err error var intervals []contract.Interval intervals, err = dbClient.Intervals() if err != nil { LoggingClient.Error("failed connecting to metadata and retrieving intervals:" + err.Error()) return intervals, err } if intervals != nil { Lo...
go
{ "resource": "" }
q37107
getSchedulerDBIntervalActions
train
func getSchedulerDBIntervalActions() ([]contract.IntervalAction, error) { var err error var intervalActions []contract.IntervalAction intervalActions, err = dbClient.IntervalActions() if err != nil { LoggingClient.Error("error connecting to metadata and retrieving interval actions:" + err.Error()) return inter...
go
{ "resource": "" }
q37108
addReceivedIntervals
train
func addReceivedIntervals(intervals []contract.Interval) error { for _, interval := range intervals { err := scClient.AddIntervalToQueue(interval) if err != nil { LoggingClient.Info("problem adding support-scheduler interval name: %s - %s", interval.Name, err.Error()) return err } LoggingClient.Info("add...
go
{ "resource": "" }
q37109
addIntervalToSchedulerDB
train
func addIntervalToSchedulerDB(interval contract.Interval) (string, error) { var err error var id string id, err = dbClient.AddInterval(interval) if err != nil { LoggingClient.Error("problem trying to add interval to support-scheduler service:" + err.Error()) return "", err } interval.ID = id LoggingClient...
go
{ "resource": "" }
q37110
addIntervalActionToSchedulerDB
train
func addIntervalActionToSchedulerDB(intervalAction contract.IntervalAction) (string, error) { var err error var id string id, err = dbClient.AddIntervalAction(intervalAction) if err != nil { LoggingClient.Error("problem trying to add interval action to support-scheduler service:" + err.Error()) return "", err ...
go
{ "resource": "" }
q37111
loadConfigIntervalActions
train
func loadConfigIntervalActions() error { intervalActions := Configuration.IntervalActions for ia := range intervalActions { intervalAction := contract.IntervalAction{ Name: intervalActions[ia].Name, Interval: intervalActions[ia].Interval, Parameters: intervalActions[ia].Parameters, Target: ...
go
{ "resource": "" }
q37112
loadSupportSchedulerDBInformation
train
func loadSupportSchedulerDBInformation() error { receivedIntervals, err := getSchedulerDBIntervals() if err != nil { LoggingClient.Error("failed to receive intervals from support-scheduler database:" + err.Error()) return err } err = addReceivedIntervals(receivedIntervals) if err != nil { LoggingClient.Err...
go
{ "resource": "" }
q37113
newMqttSender
train
func newMqttSender(addr contract.Addressable, cert string, key string) sender { protocol := strings.ToLower(addr.Protocol) opts := MQTT.NewClientOptions() broker := protocol + "://" + addr.Address + ":" + strconv.Itoa(addr.Port) + addr.Path opts.AddBroker(broker) opts.SetClientID(addr.Publisher) opts.SetUsername...
go
{ "resource": "" }
q37114
deleteEvent
train
func deleteEvent(e contract.Event) error { for _, reading := range e.Readings { if err := deleteReadingById(reading.Id); err != nil { return err } } if err := dbClient.DeleteEventById(e.ID); err != nil { return err } return nil }
go
{ "resource": "" }
q37115
putEventOnQueue
train
func putEventOnQueue(e contract.Event, ctx context.Context) { LoggingClient.Info("Putting event on message queue") // Have multiple implementations (start with ZeroMQ) evt := models.Event{} evt.Event = e evt.CorrelationId = correlation.FromContext(ctx) payload, err := json.Marshal(evt) if err != nil { LoggingC...
go
{ "resource": "" }
q37116
pingHandler
train
func pingHandler(w http.ResponseWriter, _ *http.Request) { w.Header().Set(CONTENTTYPE, TEXTPLAIN) w.Write([]byte(PINGRESPONSE)) }
go
{ "resource": "" }
q37117
validateFormatString
train
func validateFormatString(v contract.ValueDescriptor) error { // No formatting specified if v.Formatting == "" { return nil } match, err := regexp.MatchString(formatSpecifier, v.Formatting) if err != nil { LoggingClient.Error("Error checking for format string for value descriptor " + v.Name) return err } ...
go
{ "resource": "" }
q37118
restAddAddressable
train
func restAddAddressable(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() var a models.Addressable err := json.NewDecoder(r.Body).Decode(&a) if err != nil { LoggingClient.Error(err.Error()) http.Error(w, err.Error(), http.StatusBadRequest) return } id, err := addAddressable(a) if err != nil {...
go
{ "resource": "" }
q37119
isAddressableStillInUse
train
func isAddressableStillInUse(a models.Addressable) (bool, error) { // Check device services ds, err := dbClient.GetDeviceServicesByAddressableId(a.Id) if err != nil { return false, err } if len(ds) > 0 { return true, nil } return false, nil }
go
{ "resource": "" }
q37120
getSystemTimes
train
func getSystemTimes(idleTime, kernelTime, userTime *FileTime) bool { ret, _, _ := procGetSystemTimes.Call( uintptr(unsafe.Pointer(idleTime)), uintptr(unsafe.Pointer(kernelTime)), uintptr(unsafe.Pointer(userTime))) return ret != 0 }
go
{ "resource": "" }
q37121
detectConfigFileType
train
func detectConfigFileType(path, def string) string { switch ext := filepath.Ext(path); ext { case ".toml": return "toml" case ".yaml", ".yml": return "yaml" case ".json": return "json" default: return def } }
go
{ "resource": "" }
q37122
FlatUpdate
train
func FlatUpdate(f1, f2 map[string]string) error { conflict := false for k2, v2 := range f2 { if v1, ok := f1[k2]; ok { f1[k2] = v1 + ";" + v2 conflict = true } else { f1[k2] = v2 } } if conflict { return fmt.Errorf("keys conflict") } else { return nil } }
go
{ "resource": "" }
q37123
Calculate
train
func (dest *Destination) Calculate(newPath *Path) *Update { oldKnownPathList := make([]*Path, len(dest.knownPathList)) copy(oldKnownPathList, dest.knownPathList) if newPath.IsWithdraw { p := dest.explicitWithdraw(newPath) if p != nil { if id := p.GetNlri().PathLocalIdentifier(); id != 0 { dest.localIdMap...
go
{ "resource": "" }
q37124
implicitWithdraw
train
func (dest *Destination) implicitWithdraw(newPath *Path) { found := -1 for i, path := range dest.knownPathList { if newPath.NoImplicitWithdraw() { continue } // Here we just check if source is same and not check if path // version num. as newPaths are implicit withdrawal of old // paths and when doing Ro...
go
{ "resource": "" }
q37125
newTCPListener
train
func newTCPListener(address string, port uint32, ch chan *net.TCPConn) (*tcpListener, error) { proto := "tcp4" if ip := net.ParseIP(address); ip == nil { return nil, fmt.Errorf("can't listen on %s", address) } else if ip.To4() == nil { proto = "tcp6" } addr, err := net.ResolveTCPAddr(proto, net.JoinHostPort(ad...
go
{ "resource": "" }
q37126
update
train
func (r ribout) update(p *table.Path) bool { key := p.GetNlri().String() // TODO expose (*Path).getPrefix() l := r[key] if p.IsWithdraw { if len(l) == 0 { return false } n := make([]*table.Path, 0, len(l)) for _, q := range l { if p.GetSource() == q.GetSource() { continue } n = append(n, q) ...
go
{ "resource": "" }
q37127
newAdministrativeCommunication
train
func newAdministrativeCommunication(communication string) (data []byte) { if communication == "" { return nil } com := []byte(communication) if len(com) > bgp.BGP_ERROR_ADMINISTRATIVE_COMMUNICATION_MAX { data = []byte{bgp.BGP_ERROR_ADMINISTRATIVE_COMMUNICATION_MAX} data = append(data, com[:bgp.BGP_ERROR_ADMIN...
go
{ "resource": "" }
q37128
decodeAdministrativeCommunication
train
func decodeAdministrativeCommunication(data []byte) (string, []byte) { if len(data) == 0 { return "", data } communicationLen := int(data[0]) if communicationLen > bgp.BGP_ERROR_ADMINISTRATIVE_COMMUNICATION_MAX { communicationLen = bgp.BGP_ERROR_ADMINISTRATIVE_COMMUNICATION_MAX } if communicationLen > len(dat...
go
{ "resource": "" }
q37129
Clone
train
func (path *Path) Clone(isWithdraw bool) *Path { return &Path{ parent: path, IsWithdraw: isWithdraw, IsNexthopInvalid: path.IsNexthopInvalid, attrsHash: path.attrsHash, } }
go
{ "resource": "" }
q37130
String
train
func (path *Path) String() string { s := bytes.NewBuffer(make([]byte, 0, 64)) if path.IsEOR() { s.WriteString(fmt.Sprintf("{ %s EOR | src: %s }", path.GetRouteFamily(), path.GetSource())) return s.String() } s.WriteString(fmt.Sprintf("{ %s | ", path.getPrefix())) s.WriteString(fmt.Sprintf("src: %s", path.GetSo...
go
{ "resource": "" }
q37131
GetAsPathLen
train
func (path *Path) GetAsPathLen() int { var length int = 0 if aspath := path.GetAsPath(); aspath != nil { for _, as := range aspath.Value { length += as.ASLen() } } return length }
go
{ "resource": "" }
q37132
SetCommunities
train
func (path *Path) SetCommunities(communities []uint32, doReplace bool) { if len(communities) == 0 && doReplace { // clear communities path.delPathAttr(bgp.BGP_ATTR_TYPE_COMMUNITIES) return } newList := make([]uint32, 0) attr := path.getPathAttr(bgp.BGP_ATTR_TYPE_COMMUNITIES) if attr != nil { c := attr.(*...
go
{ "resource": "" }
q37133
RemoveCommunities
train
func (path *Path) RemoveCommunities(communities []uint32) int { if len(communities) == 0 { // do nothing return 0 } find := func(val uint32) bool { for _, com := range communities { if com == val { return true } } return false } count := 0 attr := path.getPathAttr(bgp.BGP_ATTR_TYPE_COMMUNIT...
go
{ "resource": "" }
q37134
SetMed
train
func (path *Path) SetMed(med int64, doReplace bool) error { parseMed := func(orgMed uint32, med int64, doReplace bool) (*bgp.PathAttributeMultiExitDisc, error) { if doReplace { return bgp.NewPathAttributeMultiExitDisc(uint32(med)), nil } medVal := int64(orgMed) + med if medVal < 0 { return nil, fmt.Erro...
go
{ "resource": "" }
q37135
Evaluate
train
func (c *NextHopCondition) Evaluate(path *Path, options *PolicyOptions) bool { if len(c.set.list) == 0 { log.WithFields(log.Fields{ "Topic": "Policy", }).Debug("NextHop doesn't have elements") return true } nexthop := path.GetNexthop() // In cases where we advertise routes from iBGP to eBGP, we want to f...
go
{ "resource": "" }
q37136
Evaluate
train
func (c *PrefixCondition) Evaluate(path *Path, _ *PolicyOptions) bool { var key string var masklen uint8 keyf := func(ip net.IP, ones int) string { var buffer bytes.Buffer for i := 0; i < len(ip) && i < ones; i++ { buffer.WriteString(fmt.Sprintf("%08b", ip[i])) } return buffer.String()[:ones] } family :...
go
{ "resource": "" }
q37137
Evaluate
train
func (c *NeighborCondition) Evaluate(path *Path, options *PolicyOptions) bool { if len(c.set.list) == 0 { log.WithFields(log.Fields{ "Topic": "Policy", }).Debug("NeighborList doesn't have elements") return true } neighbor := path.GetSource().Address if options != nil && options.Info != nil && options.Info...
go
{ "resource": "" }
q37138
Evaluate
train
func (c *AsPathLengthCondition) Evaluate(path *Path, _ *PolicyOptions) bool { length := uint32(path.GetAsPathLen()) result := false switch c.operator { case ATTRIBUTE_EQ: result = c.length == length case ATTRIBUTE_GE: result = c.length <= length case ATTRIBUTE_LE: result = c.length >= length } return re...
go
{ "resource": "" }
q37139
NewAsPathPrependAction
train
func NewAsPathPrependAction(action config.SetAsPathPrepend) (*AsPathPrependAction, error) { a := &AsPathPrependAction{ repeat: action.RepeatN, } switch action.As { case "": if a.repeat == 0 { return nil, nil } return nil, fmt.Errorf("specify as to prepend") case "last-as": a.useLeftMost = true defaul...
go
{ "resource": "" }
q37140
Evaluate
train
func (s *Statement) Evaluate(p *Path, options *PolicyOptions) bool { for _, c := range s.Conditions { if !c.Evaluate(p, options) { return false } } return true }
go
{ "resource": "" }
q37141
Apply
train
func (p *Policy) Apply(path *Path, options *PolicyOptions) (RouteType, *Path) { for _, stmt := range p.Statements { var result RouteType result, path = stmt.Apply(path, options) if result != ROUTE_TYPE_NONE { return result, path } } return ROUTE_TYPE_NONE, path }
go
{ "resource": "" }
q37142
ChannelClose
train
func ChannelClose(ch chan *Message) bool { select { case _, ok := <-ch: if ok { close(ch) return true } default: } return false }
go
{ "resource": "" }
q37143
validatePathAttributeFlags
train
func validatePathAttributeFlags(t BGPAttrType, flags BGPAttrFlag) string { /* * RFC 4271 P.17 For well-known attributes, the Transitive bit MUST be set to 1. */ if flags&BGP_ATTR_FLAG_OPTIONAL == 0 && flags&BGP_ATTR_FLAG_TRANSITIVE == 0 { eMsg := fmt.Sprintf("well-known attribute %s must have transitive flag 1...
go
{ "resource": "" }
q37144
build
train
func (c corsWrapper) build() gin.HandlerFunc { return func(ctx *gin.Context) { c.HandlerFunc(ctx.Writer, ctx.Request) if !c.optionPassthrough && ctx.Request.Method == http.MethodOptions && ctx.GetHeader("Access-Control-Request-Method") != "" { // Abort processing next Gin middlewares. ctx.AbortWithStat...
go
{ "resource": "" }
q37145
New
train
func New(options Options) gin.HandlerFunc { return corsWrapper{cors.New(options), options.OptionsPassthrough}.build() }
go
{ "resource": "" }
q37146
AllowAll
train
func AllowAll() *Cors { return New(Options{ AllowedOrigins: []string{"*"}, AllowedMethods: []string{ http.MethodHead, http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete, }, AllowedHeaders: []string{"*"}, AllowCredentials: false, }) }
go
{ "resource": "" }
q37147
Handler
train
func (c *Cors) Handler(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" { c.logf("Handler: Preflight request") c.handlePreflight(w, r) // Preflight requests are stand...
go
{ "resource": "" }
q37148
HandlerFunc
train
func (c *Cors) HandlerFunc(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" { c.logf("HandlerFunc: Preflight request") c.handlePreflight(w, r) } else { c.logf("HandlerFunc: Actual request") c.handleActualRequest(w, r) } }
go
{ "resource": "" }
q37149
areHeadersAllowed
train
func (c *Cors) areHeadersAllowed(requestedHeaders []string) bool { if c.allowedHeadersAll || len(requestedHeaders) == 0 { return true } for _, header := range requestedHeaders { header = http.CanonicalHeaderKey(header) found := false for _, h := range c.allowedHeaders { if h == header { found = true ...
go
{ "resource": "" }
q37150
newNode
train
func newNode(id, network, address string) (*node, error) { if len(id) != 20 { return nil, errors.New("node id should be a 20-length string") } addr, err := net.ResolveUDPAddr(network, address) if err != nil { return nil, err } return &node{newBitmapFromString(id), addr, time.Now()}, nil }
go
{ "resource": "" }
q37151
newNodeFromCompactInfo
train
func newNodeFromCompactInfo( compactNodeInfo string, network string) (*node, error) { if len(compactNodeInfo) != 26 { return nil, errors.New("compactNodeInfo should be a 26-length string") } id := compactNodeInfo[:20] ip, port, _ := decodeCompactIPPortInfo(compactNodeInfo[20:]) return newNode(id, network, ge...
go
{ "resource": "" }
q37152
newPeer
train
func newPeer(ip net.IP, port int, token string) *Peer { return &Peer{ IP: ip, Port: port, token: token, } }
go
{ "resource": "" }
q37153
Insert
train
func (pm *peersManager) Insert(infoHash string, peer *Peer) { pm.Lock() if _, ok := pm.table.Get(infoHash); !ok { pm.table.Set(infoHash, newKeyedDeque()) } pm.Unlock() v, _ := pm.table.Get(infoHash) queue := v.(*keyedDeque) queue.Push(peer.CompactIPPortInfo(), peer) if queue.Len() > pm.dht.K { queue.Remov...
go
{ "resource": "" }
q37154
GetPeers
train
func (pm *peersManager) GetPeers(infoHash string, size int) []*Peer { peers := make([]*Peer, 0, size) v, ok := pm.table.Get(infoHash) if !ok { return peers } for e := range v.(*keyedDeque).Iter() { peers = append(peers, e.Value.(*Peer)) } if len(peers) > size { peers = peers[len(peers)-size:] } return...
go
{ "resource": "" }
q37155
newKBucket
train
func newKBucket(prefix *bitmap) *kbucket { bucket := &kbucket{ nodes: newKeyedDeque(), candidates: newKeyedDeque(), lastChanged: time.Now(), prefix: prefix, } return bucket }
go
{ "resource": "" }
q37156
LastChanged
train
func (bucket *kbucket) LastChanged() time.Time { bucket.RLock() defer bucket.RUnlock() return bucket.lastChanged }
go
{ "resource": "" }
q37157
RandomChildID
train
func (bucket *kbucket) RandomChildID() string { prefixLen := bucket.prefix.Size / 8 return strings.Join([]string{ bucket.prefix.RawString()[:prefixLen], randomString(20 - prefixLen), }, "") }
go
{ "resource": "" }
q37158
UpdateTimestamp
train
func (bucket *kbucket) UpdateTimestamp() { bucket.Lock() defer bucket.Unlock() bucket.lastChanged = time.Now() }
go
{ "resource": "" }
q37159
Insert
train
func (bucket *kbucket) Insert(no *node) bool { isNew := !bucket.nodes.HasKey(no.id.RawString()) bucket.nodes.Push(no.id.RawString(), no) bucket.UpdateTimestamp() return isNew }
go
{ "resource": "" }
q37160
Fresh
train
func (bucket *kbucket) Fresh(dht *DHT) { for e := range bucket.nodes.Iter() { no := e.Value.(*node) if time.Since(no.lastActiveTime) > dht.NodeExpriedAfter { dht.transactionManager.ping(no) } } }
go
{ "resource": "" }
q37161
newRoutingTableNode
train
func newRoutingTableNode(prefix *bitmap) *routingTableNode { return &routingTableNode{ children: make([]*routingTableNode, 2), bucket: newKBucket(prefix), } }
go
{ "resource": "" }
q37162
Child
train
func (tableNode *routingTableNode) Child(index int) *routingTableNode { if index >= 2 { return nil } tableNode.RLock() defer tableNode.RUnlock() return tableNode.children[index] }
go
{ "resource": "" }
q37163
SetChild
train
func (tableNode *routingTableNode) SetChild(index int, c *routingTableNode) { tableNode.Lock() defer tableNode.Unlock() tableNode.children[index] = c }
go
{ "resource": "" }
q37164
KBucket
train
func (tableNode *routingTableNode) KBucket() *kbucket { tableNode.RLock() defer tableNode.RUnlock() return tableNode.bucket }
go
{ "resource": "" }
q37165
SetKBucket
train
func (tableNode *routingTableNode) SetKBucket(bucket *kbucket) { tableNode.Lock() defer tableNode.Unlock() tableNode.bucket = bucket }
go
{ "resource": "" }
q37166
Split
train
func (tableNode *routingTableNode) Split() { prefixLen := tableNode.KBucket().prefix.Size if prefixLen == maxPrefixLength { return } for i := 0; i < 2; i++ { tableNode.SetChild(i, newRoutingTableNode(newBitmapFrom( tableNode.KBucket().prefix, prefixLen+1))) } tableNode.Lock() tableNode.children[1].buck...
go
{ "resource": "" }
q37167
newRoutingTable
train
func newRoutingTable(k int, dht *DHT) *routingTable { root := newRoutingTableNode(newBitmap(0)) rt := &routingTable{ RWMutex: &sync.RWMutex{}, k: k, root: root, cachedNodes: newSyncedMap(), cachedKBuckets: newKeyedDeque(), dht: dht, clearQueue: newSyncedL...
go
{ "resource": "" }
q37168
Insert
train
func (rt *routingTable) Insert(nd *node) bool { rt.Lock() defer rt.Unlock() if rt.dht.blackList.in(nd.addr.IP.String(), nd.addr.Port) || rt.cachedNodes.Len() >= rt.dht.MaxNodes { return false } var ( next *routingTableNode bucket *kbucket ) root := rt.root for prefixLen := 1; prefixLen <= maxPrefix...
go
{ "resource": "" }
q37169
GetNeighbors
train
func (rt *routingTable) GetNeighbors(id *bitmap, size int) []*node { rt.RLock() nodes := make([]interface{}, 0, rt.cachedNodes.Len()) for item := range rt.cachedNodes.Iter() { nodes = append(nodes, item.val.(*node)) } rt.RUnlock() neighbors := getTopK(nodes, id, size) result := make([]*node, len(neighbors)) ...
go
{ "resource": "" }
q37170
GetNeighborCompactInfos
train
func (rt *routingTable) GetNeighborCompactInfos(id *bitmap, size int) []string { neighbors := rt.GetNeighbors(id, size) infos := make([]string, len(neighbors)) for i, no := range neighbors { infos[i] = no.CompactNodeInfo() } return infos }
go
{ "resource": "" }
q37171
GetNodeKBucktByID
train
func (rt *routingTable) GetNodeKBucktByID(id *bitmap) ( nd *node, bucket *kbucket) { rt.RLock() defer rt.RUnlock() var next *routingTableNode root := rt.root for prefixLen := 1; prefixLen <= maxPrefixLength; prefixLen++ { next = root.Child(id.Bit(prefixLen - 1)) if next == nil { v, ok := root.KBucket()....
go
{ "resource": "" }
q37172
GetNodeByAddress
train
func (rt *routingTable) GetNodeByAddress(address string) (no *node, ok bool) { rt.RLock() defer rt.RUnlock() v, ok := rt.cachedNodes.Get(address) if ok { no = v.(*node) } return }
go
{ "resource": "" }
q37173
Remove
train
func (rt *routingTable) Remove(id *bitmap) { if nd, bucket := rt.GetNodeKBucktByID(id); nd != nil { bucket.Replace(nd) rt.cachedNodes.Delete(nd.addr.String()) rt.cachedKBuckets.Push(bucket.prefix.String(), bucket) } }
go
{ "resource": "" }
q37174
Fresh
train
func (rt *routingTable) Fresh() { now := time.Now() for e := range rt.cachedKBuckets.Iter() { bucket := e.Value.(*kbucket) if now.Sub(bucket.LastChanged()) < rt.dht.KBucketExpiredAfter || bucket.nodes.Len() == 0 { continue } i := 0 for e := range bucket.nodes.Iter() { if i < rt.dht.RefreshNodeNum...
go
{ "resource": "" }
q37175
Len
train
func (rt *routingTable) Len() int { rt.RLock() defer rt.RUnlock() return rt.cachedNodes.Len() }
go
{ "resource": "" }
q37176
find
train
func find(data []byte, start int, target rune) (index int) { index = bytes.IndexRune(data[start:], target) if index != -1 { return index + start } return index }
go
{ "resource": "" }
q37177
DecodeInt
train
func DecodeInt(data []byte, start int) ( result interface{}, index int, err error) { if start >= len(data) || data[start] != 'i' { err = errors.New("invalid int bencode") return } index = find(data, start+1, 'e') if index == -1 { err = errors.New("':' not found when decode int") return } result, err ...
go
{ "resource": "" }
q37178
decodeItem
train
func decodeItem(data []byte, i int) ( result interface{}, index int, err error) { var decodeFunc = []func([]byte, int) (interface{}, int, error){ DecodeString, DecodeInt, DecodeList, DecodeDict, } for _, f := range decodeFunc { result, index, err = f(data, i) if err == nil { return } } err = errors....
go
{ "resource": "" }
q37179
DecodeList
train
func DecodeList(data []byte, start int) ( result interface{}, index int, err error) { if start >= len(data) || data[start] != 'l' { err = errors.New("invalid list bencode") return } var item interface{} r := make([]interface{}, 0, 8) index = start + 1 for index < len(data) { char, _ := utf8.DecodeRune(d...
go
{ "resource": "" }
q37180
DecodeDict
train
func DecodeDict(data []byte, start int) ( result interface{}, index int, err error) { if start >= len(data) || data[start] != 'd' { err = errors.New("invalid dict bencode") return } var item, key interface{} r := make(map[string]interface{}) index = start + 1 for index < len(data) { char, _ := utf8.Deco...
go
{ "resource": "" }
q37181
Decode
train
func Decode(data []byte) (result interface{}, err error) { result, _, err = decodeItem(data, 0) return }
go
{ "resource": "" }
q37182
EncodeString
train
func EncodeString(data string) string { return strings.Join([]string{strconv.Itoa(len(data)), data}, ":") }
go
{ "resource": "" }
q37183
EncodeInt
train
func EncodeInt(data int) string { return strings.Join([]string{"i", strconv.Itoa(data), "e"}, "") }
go
{ "resource": "" }
q37184
encodeItem
train
func encodeItem(data interface{}) (item string) { switch v := data.(type) { case string: item = EncodeString(v) case int: item = EncodeInt(v) case []interface{}: item = EncodeList(v) case map[string]interface{}: item = EncodeDict(v) default: panic("invalid type when encode item") } return }
go
{ "resource": "" }
q37185
EncodeList
train
func EncodeList(data []interface{}) string { result := make([]string, len(data)) for i, item := range data { result[i] = encodeItem(item) } return strings.Join([]string{"l", strings.Join(result, ""), "e"}, "") }
go
{ "resource": "" }
q37186
EncodeDict
train
func EncodeDict(data map[string]interface{}) string { result, i := make([]string, len(data)), 0 for key, val := range data { result[i] = strings.Join( []string{EncodeString(key), encodeItem(val)}, "") i++ } return strings.Join([]string{"d", strings.Join(result, ""), "e"}, "") }
go
{ "resource": "" }
q37187
Encode
train
func Encode(data interface{}) string { switch v := data.(type) { case string: return EncodeString(v) case int: return EncodeInt(v) case []interface{}: return EncodeList(v) case map[string]interface{}: return EncodeDict(v) default: panic("invalid type when encode") } }
go
{ "resource": "" }
q37188
Get
train
func (smap *syncedMap) Get(key interface{}) (val interface{}, ok bool) { smap.RLock() defer smap.RUnlock() val, ok = smap.data[key] return }
go
{ "resource": "" }
q37189
Has
train
func (smap *syncedMap) Has(key interface{}) bool { _, ok := smap.Get(key) return ok }
go
{ "resource": "" }
q37190
Delete
train
func (smap *syncedMap) Delete(key interface{}) { smap.Lock() defer smap.Unlock() delete(smap.data, key) }
go
{ "resource": "" }
q37191
DeleteMulti
train
func (smap *syncedMap) DeleteMulti(keys []interface{}) { smap.Lock() defer smap.Unlock() for _, key := range keys { delete(smap.data, key) } }
go
{ "resource": "" }
q37192
Clear
train
func (smap *syncedMap) Clear() { smap.Lock() defer smap.Unlock() smap.data = make(map[interface{}]interface{}) }
go
{ "resource": "" }
q37193
Iter
train
func (smap *syncedMap) Iter() <-chan mapItem { ch := make(chan mapItem) go func() { smap.RLock() for key, val := range smap.data { ch <- mapItem{ key: key, val: val, } } smap.RUnlock() close(ch) }() return ch }
go
{ "resource": "" }
q37194
Len
train
func (smap *syncedMap) Len() int { smap.RLock() defer smap.RUnlock() return len(smap.data) }
go
{ "resource": "" }
q37195
Front
train
func (slist *syncedList) Front() *list.Element { slist.RLock() defer slist.RUnlock() return slist.queue.Front() }
go
{ "resource": "" }
q37196
Back
train
func (slist *syncedList) Back() *list.Element { slist.RLock() defer slist.RUnlock() return slist.queue.Back() }
go
{ "resource": "" }
q37197
PushFront
train
func (slist *syncedList) PushFront(v interface{}) *list.Element { slist.Lock() defer slist.Unlock() return slist.queue.PushFront(v) }
go
{ "resource": "" }
q37198
InsertBefore
train
func (slist *syncedList) InsertBefore( v interface{}, mark *list.Element) *list.Element { slist.Lock() defer slist.Unlock() return slist.queue.InsertBefore(v, mark) }
go
{ "resource": "" }
q37199
Remove
train
func (slist *syncedList) Remove(e *list.Element) interface{} { slist.Lock() defer slist.Unlock() return slist.queue.Remove(e) }
go
{ "resource": "" }