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
partition
stringclasses
1 value
edgexfoundry/edgex-go
internal/pkg/db/redis/scheduler.go
UpdateIntervalAction
func (c *Client) UpdateIntervalAction(from contract.IntervalAction) (err error) { check, err := c.IntervalActionByName(from.Name) if err != nil && err != redis.ErrNil { return err } if err == nil && from.ID != check.ID { // IDs are different -> name not unique return db.ErrNotUnique } from.Modified = db.Ma...
go
func (c *Client) UpdateIntervalAction(from contract.IntervalAction) (err error) { check, err := c.IntervalActionByName(from.Name) if err != nil && err != redis.ErrNil { return err } if err == nil && from.ID != check.ID { // IDs are different -> name not unique return db.ErrNotUnique } from.Modified = db.Ma...
[ "func", "(", "c", "*", "Client", ")", "UpdateIntervalAction", "(", "from", "contract", ".", "IntervalAction", ")", "(", "err", "error", ")", "{", "check", ",", "err", ":=", "c", ".", "IntervalActionByName", "(", "from", ".", "Name", ")", "\n", "if", "e...
// Update schedule interval action
[ "Update", "schedule", "interval", "action" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/scheduler.go#L358-L389
train
edgexfoundry/edgex-go
internal/pkg/db/redis/scheduler.go
DeleteIntervalActionById
func (c *Client) DeleteIntervalActionById(id string) (err error) { check, err := c.IntervalActionById(id) if err != nil { if err == db.ErrNotFound { return nil } return } action := models.NewIntervalAction(check) conn := c.Pool.Get() defer conn.Close() _ = conn.Send("MULTI") deleteObject(action, id, ...
go
func (c *Client) DeleteIntervalActionById(id string) (err error) { check, err := c.IntervalActionById(id) if err != nil { if err == db.ErrNotFound { return nil } return } action := models.NewIntervalAction(check) conn := c.Pool.Get() defer conn.Close() _ = conn.Send("MULTI") deleteObject(action, id, ...
[ "func", "(", "c", "*", "Client", ")", "DeleteIntervalActionById", "(", "id", "string", ")", "(", "err", "error", ")", "{", "check", ",", "err", ":=", "c", ".", "IntervalActionById", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", ...
// Remove schedule interval action by id
[ "Remove", "schedule", "interval", "action", "by", "id" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/scheduler.go#L392-L411
train
edgexfoundry/edgex-go
internal/pkg/db/redis/data.go
EventCount
func (c *Client) EventCount() (count int, err error) { conn := c.Pool.Get() defer conn.Close() count, err = redis.Int(conn.Do("ZCARD", db.EventsCollection)) if err != nil { return 0, err } return count, nil }
go
func (c *Client) EventCount() (count int, err error) { conn := c.Pool.Get() defer conn.Close() count, err = redis.Int(conn.Do("ZCARD", db.EventsCollection)) if err != nil { return 0, err } return count, nil }
[ "func", "(", "c", "*", "Client", ")", "EventCount", "(", ")", "(", "count", "int", ",", "err", "error", ")", "{", "conn", ":=", "c", ".", "Pool", ".", "Get", "(", ")", "\n", "defer", "conn", ".", "Close", "(", ")", "\n\n", "count", ",", "err", ...
// Get the number of events in Core Data
[ "Get", "the", "number", "of", "events", "in", "Core", "Data" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/data.go#L135-L145
train
edgexfoundry/edgex-go
internal/pkg/db/redis/data.go
DeleteEventById
func (c *Client) DeleteEventById(id string) (err error) { conn := c.Pool.Get() defer conn.Close() err = deleteEvent(conn, id) if err != nil { if err == redis.ErrNil { return db.ErrNotFound } return err } return nil }
go
func (c *Client) DeleteEventById(id string) (err error) { conn := c.Pool.Get() defer conn.Close() err = deleteEvent(conn, id) if err != nil { if err == redis.ErrNil { return db.ErrNotFound } return err } return nil }
[ "func", "(", "c", "*", "Client", ")", "DeleteEventById", "(", "id", "string", ")", "(", "err", "error", ")", "{", "conn", ":=", "c", ".", "Pool", ".", "Get", "(", ")", "\n", "defer", "conn", ".", "Close", "(", ")", "\n\n", "err", "=", "deleteEven...
// Delete an event by ID. Readings are not deleted as this should be handled by the contract layer // 404 - Event not found // 503 - Unexpected problems
[ "Delete", "an", "event", "by", "ID", ".", "Readings", "are", "not", "deleted", "as", "this", "should", "be", "handled", "by", "the", "contract", "layer", "404", "-", "Event", "not", "found", "503", "-", "Unexpected", "problems" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/data.go#L163-L176
train
edgexfoundry/edgex-go
internal/pkg/db/redis/data.go
ScrubAllEvents
func (c *Client) ScrubAllEvents() (err error) { conn := c.Pool.Get() defer conn.Close() err = unlinkCollection(conn, db.EventsCollection) if err != nil { return err } err = unlinkCollection(conn, db.ReadingsCollection) if err != nil { return err } return nil }
go
func (c *Client) ScrubAllEvents() (err error) { conn := c.Pool.Get() defer conn.Close() err = unlinkCollection(conn, db.EventsCollection) if err != nil { return err } err = unlinkCollection(conn, db.ReadingsCollection) if err != nil { return err } return nil }
[ "func", "(", "c", "*", "Client", ")", "ScrubAllEvents", "(", ")", "(", "err", "error", ")", "{", "conn", ":=", "c", ".", "Pool", ".", "Get", "(", ")", "\n", "defer", "conn", ".", "Close", "(", ")", "\n\n", "err", "=", "unlinkCollection", "(", "co...
// Delete all readings and events
[ "Delete", "all", "readings", "and", "events" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/data.go#L297-L312
train
edgexfoundry/edgex-go
internal/pkg/db/redis/data.go
AddReading
func (c *Client) AddReading(r contract.Reading) (id string, err error) { conn := c.Pool.Get() defer conn.Close() if r.Id != "" { _, err = uuid.Parse(r.Id) if err != nil { return "", db.ErrInvalidObjectId } } return addReading(conn, true, r) }
go
func (c *Client) AddReading(r contract.Reading) (id string, err error) { conn := c.Pool.Get() defer conn.Close() if r.Id != "" { _, err = uuid.Parse(r.Id) if err != nil { return "", db.ErrInvalidObjectId } } return addReading(conn, true, r) }
[ "func", "(", "c", "*", "Client", ")", "AddReading", "(", "r", "contract", ".", "Reading", ")", "(", "id", "string", ",", "err", "error", ")", "{", "conn", ":=", "c", ".", "Pool", ".", "Get", "(", ")", "\n", "defer", "conn", ".", "Close", "(", "...
// Post a new reading // Check if valuedescriptor exists in the database
[ "Post", "a", "new", "reading", "Check", "if", "valuedescriptor", "exists", "in", "the", "database" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/data.go#L338-L349
train
edgexfoundry/edgex-go
internal/pkg/db/redis/data.go
ReadingCount
func (c *Client) ReadingCount() (int, error) { conn := c.Pool.Get() defer conn.Close() count, err := redis.Int(conn.Do("ZCARD", db.ReadingsCollection)) if err != nil { return 0, err } return count, nil }
go
func (c *Client) ReadingCount() (int, error) { conn := c.Pool.Get() defer conn.Close() count, err := redis.Int(conn.Do("ZCARD", db.ReadingsCollection)) if err != nil { return 0, err } return count, nil }
[ "func", "(", "c", "*", "Client", ")", "ReadingCount", "(", ")", "(", "int", ",", "error", ")", "{", "conn", ":=", "c", ".", "Pool", ".", "Get", "(", ")", "\n", "defer", "conn", ".", "Close", "(", ")", "\n\n", "count", ",", "err", ":=", "redis",...
// Get the number of readings in core data
[ "Get", "the", "number", "of", "readings", "in", "core", "data" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/data.go#L407-L417
train
edgexfoundry/edgex-go
internal/pkg/db/redis/data.go
ReadingsByCreationTime
func (c *Client) ReadingsByCreationTime(start, end int64, limit int) (readings []contract.Reading, err error) { conn := c.Pool.Get() defer conn.Close() if limit == 0 { return readings, nil } objects, err := getObjectsByScore(conn, db.ReadingsCollection+":created", start, end, limit) if err != nil { return r...
go
func (c *Client) ReadingsByCreationTime(start, end int64, limit int) (readings []contract.Reading, err error) { conn := c.Pool.Get() defer conn.Close() if limit == 0 { return readings, nil } objects, err := getObjectsByScore(conn, db.ReadingsCollection+":created", start, end, limit) if err != nil { return r...
[ "func", "(", "c", "*", "Client", ")", "ReadingsByCreationTime", "(", "start", ",", "end", "int64", ",", "limit", "int", ")", "(", "readings", "[", "]", "contract", ".", "Reading", ",", "err", "error", ")", "{", "conn", ":=", "c", ".", "Pool", ".", ...
// Return a list of readings whos created time is between the start and end times
[ "Return", "a", "list", "of", "readings", "whos", "created", "time", "is", "between", "the", "start", "and", "end", "times" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/data.go#L520-L542
train
edgexfoundry/edgex-go
internal/pkg/db/redis/data.go
DeleteValueDescriptorById
func (c *Client) DeleteValueDescriptorById(id string) error { conn := c.Pool.Get() defer conn.Close() err := deleteValue(conn, id) if err != nil { if err == redis.ErrNil { return db.ErrNotFound } return err } return nil }
go
func (c *Client) DeleteValueDescriptorById(id string) error { conn := c.Pool.Get() defer conn.Close() err := deleteValue(conn, id) if err != nil { if err == redis.ErrNil { return db.ErrNotFound } return err } return nil }
[ "func", "(", "c", "*", "Client", ")", "DeleteValueDescriptorById", "(", "id", "string", ")", "error", "{", "conn", ":=", "c", ".", "Pool", ".", "Get", "(", ")", "\n", "defer", "conn", ".", "Close", "(", ")", "\n\n", "err", ":=", "deleteValue", "(", ...
// Delete a value descriptor based on the ID
[ "Delete", "a", "value", "descriptor", "based", "on", "the", "ID" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/data.go#L618-L630
train
edgexfoundry/edgex-go
internal/pkg/db/redis/data.go
ValueDescriptorByName
func (c *Client) ValueDescriptorByName(name string) (value contract.ValueDescriptor, err error) { conn := c.Pool.Get() defer conn.Close() value, err = valueByName(conn, name) if err != nil { if err == redis.ErrNil { return value, db.ErrNotFound } return value, err } return value, nil }
go
func (c *Client) ValueDescriptorByName(name string) (value contract.ValueDescriptor, err error) { conn := c.Pool.Get() defer conn.Close() value, err = valueByName(conn, name) if err != nil { if err == redis.ErrNil { return value, db.ErrNotFound } return value, err } return value, nil }
[ "func", "(", "c", "*", "Client", ")", "ValueDescriptorByName", "(", "name", "string", ")", "(", "value", "contract", ".", "ValueDescriptor", ",", "err", "error", ")", "{", "conn", ":=", "c", ".", "Pool", ".", "Get", "(", ")", "\n", "defer", "conn", "...
// Return a value descriptor based on the name
[ "Return", "a", "value", "descriptor", "based", "on", "the", "name" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/data.go#L633-L646
train
edgexfoundry/edgex-go
internal/pkg/db/redis/data.go
ValueDescriptorsByName
func (c *Client) ValueDescriptorsByName(names []string) (values []contract.ValueDescriptor, err error) { conn := c.Pool.Get() defer conn.Close() for _, name := range names { value, err := valueByName(conn, name) if err != nil && err != redis.ErrNil { return nil, err } if err == nil { values = append(...
go
func (c *Client) ValueDescriptorsByName(names []string) (values []contract.ValueDescriptor, err error) { conn := c.Pool.Get() defer conn.Close() for _, name := range names { value, err := valueByName(conn, name) if err != nil && err != redis.ErrNil { return nil, err } if err == nil { values = append(...
[ "func", "(", "c", "*", "Client", ")", "ValueDescriptorsByName", "(", "names", "[", "]", "string", ")", "(", "values", "[", "]", "contract", ".", "ValueDescriptor", ",", "err", "error", ")", "{", "conn", ":=", "c", ".", "Pool", ".", "Get", "(", ")", ...
// Return value descriptors based on the names
[ "Return", "value", "descriptors", "based", "on", "the", "names" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/data.go#L649-L665
train
edgexfoundry/edgex-go
internal/pkg/db/redis/data.go
ValueDescriptorsByUomLabel
func (c *Client) ValueDescriptorsByUomLabel(uomLabel string) (values []contract.ValueDescriptor, err error) { conn := c.Pool.Get() defer conn.Close() objects, err := getObjectsByRange(conn, db.ValueDescriptorCollection+":uomlabel:"+uomLabel, 0, -1) if err != nil { if err != redis.ErrNil { return values, err ...
go
func (c *Client) ValueDescriptorsByUomLabel(uomLabel string) (values []contract.ValueDescriptor, err error) { conn := c.Pool.Get() defer conn.Close() objects, err := getObjectsByRange(conn, db.ValueDescriptorCollection+":uomlabel:"+uomLabel, 0, -1) if err != nil { if err != redis.ErrNil { return values, err ...
[ "func", "(", "c", "*", "Client", ")", "ValueDescriptorsByUomLabel", "(", "uomLabel", "string", ")", "(", "values", "[", "]", "contract", ".", "ValueDescriptor", ",", "err", "error", ")", "{", "conn", ":=", "c", ".", "Pool", ".", "Get", "(", ")", "\n", ...
// Return value descriptors based on the unit of measure label
[ "Return", "value", "descriptors", "based", "on", "the", "unit", "of", "measure", "label" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/data.go#L687-L707
train
edgexfoundry/edgex-go
internal/pkg/db/redis/data.go
ScrubAllValueDescriptors
func (c *Client) ScrubAllValueDescriptors() error { conn := c.Pool.Get() defer conn.Close() err := unlinkCollection(conn, db.ValueDescriptorCollection) if err != nil { return err } return nil }
go
func (c *Client) ScrubAllValueDescriptors() error { conn := c.Pool.Get() defer conn.Close() err := unlinkCollection(conn, db.ValueDescriptorCollection) if err != nil { return err } return nil }
[ "func", "(", "c", "*", "Client", ")", "ScrubAllValueDescriptors", "(", ")", "error", "{", "conn", ":=", "c", ".", "Pool", ".", "Get", "(", ")", "\n", "defer", "conn", ".", "Close", "(", ")", "\n\n", "err", ":=", "unlinkCollection", "(", "conn", ",", ...
// Delete all value descriptors
[ "Delete", "all", "value", "descriptors" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/data.go#L756-L766
train
edgexfoundry/edgex-go
internal/pkg/db/redis/data.go
addReading
func addReading(conn redis.Conn, tx bool, r contract.Reading) (id string, err error) { if r.Created == 0 { r.Created = db.MakeTimestamp() } if r.Id == "" { r.Id = uuid.New().String() } m, err := marshalObject(r) if err != nil { return r.Id, err } if tx { _ = conn.Send("MULTI") } _ = conn.Send("SET"...
go
func addReading(conn redis.Conn, tx bool, r contract.Reading) (id string, err error) { if r.Created == 0 { r.Created = db.MakeTimestamp() } if r.Id == "" { r.Id = uuid.New().String() } m, err := marshalObject(r) if err != nil { return r.Id, err } if tx { _ = conn.Send("MULTI") } _ = conn.Send("SET"...
[ "func", "addReading", "(", "conn", "redis", ".", "Conn", ",", "tx", "bool", ",", "r", "contract", ".", "Reading", ")", "(", "id", "string", ",", "err", "error", ")", "{", "if", "r", ".", "Created", "==", "0", "{", "r", ".", "Created", "=", "db", ...
// Add a reading to the database
[ "Add", "a", "reading", "to", "the", "database" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/data.go#L856-L883
train
edgexfoundry/edgex-go
internal/pkg/db/redis/metadata.go
DeleteCommandById
func (c *Client) DeleteCommandById(id string) error { conn := c.Pool.Get() defer conn.Close() // TODO: ??? Check if the command is still in use by device profiles return deleteCommand(conn, id) }
go
func (c *Client) DeleteCommandById(id string) error { conn := c.Pool.Get() defer conn.Close() // TODO: ??? Check if the command is still in use by device profiles return deleteCommand(conn, id) }
[ "func", "(", "c", "*", "Client", ")", "DeleteCommandById", "(", "id", "string", ")", "error", "{", "conn", ":=", "c", ".", "Pool", ".", "Get", "(", ")", "\n", "defer", "conn", ".", "Close", "(", ")", "\n\n", "// TODO: ??? Check if the command is still in u...
// Delete the command by ID
[ "Delete", "the", "command", "by", "ID" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/metadata.go#L1250-L1257
train
edgexfoundry/edgex-go
internal/export/distro/format.go
newAzureMessage
func newAzureMessage() (*AzureMessage, error) { msg := &AzureMessage{ Ack: none, Properties: make(map[string]string), Created: time.Now(), } id := uuid.New() msg.ID = id.String() correlationID := uuid.New() msg.CorrelationID = correlationID.String() return msg, nil }
go
func newAzureMessage() (*AzureMessage, error) { msg := &AzureMessage{ Ack: none, Properties: make(map[string]string), Created: time.Now(), } id := uuid.New() msg.ID = id.String() correlationID := uuid.New() msg.CorrelationID = correlationID.String() return msg, nil }
[ "func", "newAzureMessage", "(", ")", "(", "*", "AzureMessage", ",", "error", ")", "{", "msg", ":=", "&", "AzureMessage", "{", "Ack", ":", "none", ",", "Properties", ":", "make", "(", "map", "[", "string", "]", "string", ")", ",", "Created", ":", "tim...
// newAzureMessage creates a new Azure message and sets // Body and default fields values.
[ "newAzureMessage", "creates", "a", "new", "Azure", "message", "and", "sets", "Body", "and", "default", "fields", "values", "." ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/export/distro/format.go#L117-L131
train
edgexfoundry/edgex-go
internal/export/distro/format.go
AddProperty
func (am *AzureMessage) AddProperty(key, value string) error { am.Properties[key] = value return nil }
go
func (am *AzureMessage) AddProperty(key, value string) error { am.Properties[key] = value return nil }
[ "func", "(", "am", "*", "AzureMessage", ")", "AddProperty", "(", "key", ",", "value", "string", ")", "error", "{", "am", ".", "Properties", "[", "key", "]", "=", "value", "\n", "return", "nil", "\n", "}" ]
// AddProperty method ads property performing key check.
[ "AddProperty", "method", "ads", "property", "performing", "key", "check", "." ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/export/distro/format.go#L134-L137
train
edgexfoundry/edgex-go
internal/export/distro/format.go
newBIoTMessage
func newBIoTMessage() (*BIoTMessage, error) { msg := &BIoTMessage{ Severity: "1", MsgType: "Q", } id := uuid.New() msg.MsgId = id.String() return msg, nil }
go
func newBIoTMessage() (*BIoTMessage, error) { msg := &BIoTMessage{ Severity: "1", MsgType: "Q", } id := uuid.New() msg.MsgId = id.String() return msg, nil }
[ "func", "newBIoTMessage", "(", ")", "(", "*", "BIoTMessage", ",", "error", ")", "{", "msg", ":=", "&", "BIoTMessage", "{", "Severity", ":", "\"", "\"", ",", "MsgType", ":", "\"", "\"", ",", "}", "\n\n", "id", ":=", "uuid", ".", "New", "(", ")", "...
// newBIoTMessage creates a new Brightics IoT message and sets // Body and default fields values.
[ "newBIoTMessage", "creates", "a", "new", "Brightics", "IoT", "message", "and", "sets", "Body", "and", "default", "fields", "values", "." ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/export/distro/format.go#L239-L249
train
edgexfoundry/edgex-go
internal/export/distro/iotcore.go
newIoTCoreSender
func newIoTCoreSender(addr models.Addressable) sender { protocol := strings.ToLower(addr.Protocol) broker := fmt.Sprintf("%s%s", addr.GetBaseURL(), addr.Path) deviceID := extractDeviceID(addr.Publisher) opts := MQTT.NewClientOptions() opts.AddBroker(broker) opts.SetClientID(addr.Publisher) opts.SetUsername(addr...
go
func newIoTCoreSender(addr models.Addressable) sender { protocol := strings.ToLower(addr.Protocol) broker := fmt.Sprintf("%s%s", addr.GetBaseURL(), addr.Path) deviceID := extractDeviceID(addr.Publisher) opts := MQTT.NewClientOptions() opts.AddBroker(broker) opts.SetClientID(addr.Publisher) opts.SetUsername(addr...
[ "func", "newIoTCoreSender", "(", "addr", "models", ".", "Addressable", ")", "sender", "{", "protocol", ":=", "strings", ".", "ToLower", "(", "addr", ".", "Protocol", ")", "\n", "broker", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "addr", ".", "...
// newIoTCoreSender returns new Google IoT Core sender instance.
[ "newIoTCoreSender", "returns", "new", "Google", "IoT", "Core", "sender", "instance", "." ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/export/distro/iotcore.go#L32-L67
train
edgexfoundry/edgex-go
internal/pkg/correlation/models/event.go
ToContract
func (e Event) ToContract() *contract.Event { event := contract.Event{ ID: e.ID, Pushed: e.Pushed, Device: e.Device, Created: e.Created, Modified: e.Modified, Origin: e.Origin, } for _, r := range e.Readings { event.Readings = append(event.Readings, r) } return &event }
go
func (e Event) ToContract() *contract.Event { event := contract.Event{ ID: e.ID, Pushed: e.Pushed, Device: e.Device, Created: e.Created, Modified: e.Modified, Origin: e.Origin, } for _, r := range e.Readings { event.Readings = append(event.Readings, r) } return &event }
[ "func", "(", "e", "Event", ")", "ToContract", "(", ")", "*", "contract", ".", "Event", "{", "event", ":=", "contract", ".", "Event", "{", "ID", ":", "e", ".", "ID", ",", "Pushed", ":", "e", ".", "Pushed", ",", "Device", ":", "e", ".", "Device", ...
// Returns an instance of just the public contract portion of the model Event. // I don't like returning a pointer from this method but I have to in order to // satisfy the Filter, Format interfaces.
[ "Returns", "an", "instance", "of", "just", "the", "public", "contract", "portion", "of", "the", "model", "Event", ".", "I", "don", "t", "like", "returning", "a", "pointer", "from", "this", "method", "but", "I", "have", "to", "in", "order", "to", "satisfy...
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/correlation/models/event.go#L31-L45
train
edgexfoundry/edgex-go
internal/core/metadata/rest_device.go
updateDeviceFields
func updateDeviceFields(from models.Device, to *models.Device) error { if (from.Service.String() != models.DeviceService{}.String()) { // Check if the new service exists // Try ID first ds, err := dbClient.GetDeviceServiceById(from.Service.Id) if err != nil { // Then try name ds, err = dbClient.GetDevic...
go
func updateDeviceFields(from models.Device, to *models.Device) error { if (from.Service.String() != models.DeviceService{}.String()) { // Check if the new service exists // Try ID first ds, err := dbClient.GetDeviceServiceById(from.Service.Id) if err != nil { // Then try name ds, err = dbClient.GetDevic...
[ "func", "updateDeviceFields", "(", "from", "models", ".", "Device", ",", "to", "*", "models", ".", "Device", ")", "error", "{", "if", "(", "from", ".", "Service", ".", "String", "(", ")", "!=", "models", ".", "DeviceService", "{", "}", ".", "String", ...
// Update the device fields
[ "Update", "the", "device", "fields" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_device.go#L176-L261
train
edgexfoundry/edgex-go
internal/core/metadata/rest_device.go
restGetDeviceByServiceName
func restGetDeviceByServiceName(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) sn, err := url.QueryUnescape(vars[SERVICENAME]) if err != nil { LoggingClient.Error(err.Error()) http.Error(w, err.Error(), http.StatusServiceUnavailable) return } // Check if the device service exists ds, err := ...
go
func restGetDeviceByServiceName(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) sn, err := url.QueryUnescape(vars[SERVICENAME]) if err != nil { LoggingClient.Error(err.Error()) http.Error(w, err.Error(), http.StatusServiceUnavailable) return } // Check if the device service exists ds, err := ...
[ "func", "restGetDeviceByServiceName", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "vars", ":=", "mux", ".", "Vars", "(", "r", ")", "\n", "sn", ",", "err", ":=", "url", ".", "QueryUnescape", "(", "vars", "...
// If the result array is empty, don't return http.NotFound, just return empty array
[ "If", "the", "result", "array", "is", "empty", "don", "t", "return", "http", ".", "NotFound", "just", "return", "empty", "array" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_device.go#L338-L369
train
edgexfoundry/edgex-go
internal/core/metadata/rest_device.go
restCheckForDevice
func restCheckForDevice(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) token := vars[ID] //referring to this as "token" for now since the source variable is double purposed //Check for name first since we're using that meaning by default. dev, err := dbClient.GetDeviceByName(token) if err != nil { ...
go
func restCheckForDevice(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) token := vars[ID] //referring to this as "token" for now since the source variable is double purposed //Check for name first since we're using that meaning by default. dev, err := dbClient.GetDeviceByName(token) if err != nil { ...
[ "func", "restCheckForDevice", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "vars", ":=", "mux", ".", "Vars", "(", "r", ")", "\n", "token", ":=", "vars", "[", "ID", "]", "//referring to this as \"token\" for now ...
//Shouldn't need "rest" in any of these methods. Adding it here for consistency right now.
[ "Shouldn", "t", "need", "rest", "in", "any", "of", "these", "methods", ".", "Adding", "it", "here", "for", "consistency", "right", "now", "." ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_device.go#L423-L456
train
edgexfoundry/edgex-go
internal/core/metadata/rest_device.go
deleteDevice
func deleteDevice(d models.Device, w http.ResponseWriter, ctx context.Context) error { if err := deleteAssociatedReportsForDevice(d, w); err != nil { http.Error(w, err.Error(), http.StatusServiceUnavailable) return err } if err := dbClient.DeleteDeviceById(d.Id); err != nil { http.Error(w, err.Error(), http.S...
go
func deleteDevice(d models.Device, w http.ResponseWriter, ctx context.Context) error { if err := deleteAssociatedReportsForDevice(d, w); err != nil { http.Error(w, err.Error(), http.StatusServiceUnavailable) return err } if err := dbClient.DeleteDeviceById(d.Id); err != nil { http.Error(w, err.Error(), http.S...
[ "func", "deleteDevice", "(", "d", "models", ".", "Device", ",", "w", "http", ".", "ResponseWriter", ",", "ctx", "context", ".", "Context", ")", "error", "{", "if", "err", ":=", "deleteAssociatedReportsForDevice", "(", "d", ",", "w", ")", ";", "err", "!="...
// Delete the device
[ "Delete", "the", "device" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_device.go#L695-L713
train
edgexfoundry/edgex-go
internal/core/metadata/rest_device.go
deleteAssociatedReportsForDevice
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
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...
[ "func", "deleteAssociatedReportsForDevice", "(", "d", "models", ".", "Device", ",", "w", "http", ".", "ResponseWriter", ")", "error", "{", "reports", ",", "err", ":=", "dbClient", ".", "GetDeviceReportByDeviceName", "(", "d", ".", "Name", ")", "\n", "if", "e...
// Delete the associated device reports for the device
[ "Delete", "the", "associated", "device", "reports", "for", "the", "device" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_device.go#L716-L735
train
edgexfoundry/edgex-go
internal/core/metadata/rest_device.go
setLastConnected
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
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...
[ "func", "setLastConnected", "(", "d", "models", ".", "Device", ",", "time", "int64", ",", "notify", "bool", ",", "w", "http", ".", "ResponseWriter", ",", "ctx", "context", ".", "Context", ")", "error", "{", "d", ".", "LastConnected", "=", "time", "\n", ...
// Update the last connected value for the device
[ "Update", "the", "last", "connected", "value", "for", "the", "device" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_device.go#L893-L906
train
edgexfoundry/edgex-go
internal/core/metadata/rest_device.go
notifyDeviceAssociates
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
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...
[ "func", "notifyDeviceAssociates", "(", "d", "models", ".", "Device", ",", "action", "string", ",", "ctx", "context", ".", "Context", ")", "error", "{", "// Post the notification to the notifications service", "postNotification", "(", "d", ".", "Name", ",", "action",...
// Notify the associated device service for the device
[ "Notify", "the", "associated", "device", "service", "for", "the", "device" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_device.go#L1101-L1117
train
edgexfoundry/edgex-go
internal/seed/config/init.go
Retry
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
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...
[ "func", "Retry", "(", "useProfile", "string", ",", "timeout", "int", ",", "wait", "*", "sync", ".", "WaitGroup", ",", "ch", "chan", "error", ")", "{", "until", ":=", "time", ".", "Now", "(", ")", ".", "Add", "(", "time", ".", "Millisecond", "*", "t...
// The purpose of Retry is different here than in other services. In this case, we use a retry in order // to initialize the RegistryClient that will be used to write configuration information. Other services // use Retry to read their information. Config-seed writes information.
[ "The", "purpose", "of", "Retry", "is", "different", "here", "than", "in", "other", "services", ".", "In", "this", "case", "we", "use", "a", "retry", "in", "order", "to", "initialize", "the", "RegistryClient", "that", "will", "be", "used", "to", "write", ...
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/seed/config/init.go#L40-L76
train
edgexfoundry/edgex-go
internal/seed/config/init.go
getBody
func getBody(resp *http.Response) ([]byte, error) { body, err := ioutil.ReadAll(resp.Body) return body, err }
go
func getBody(resp *http.Response) ([]byte, error) { body, err := ioutil.ReadAll(resp.Body) return body, err }
[ "func", "getBody", "(", "resp", "*", "http", ".", "Response", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "resp", ".", "Body", ")", "\n\n", "return", "body", ",", "err", "\n", "}" ]
// Helper method to get the body from the response after making the request
[ "Helper", "method", "to", "get", "the", "body", "from", "the", "response", "after", "making", "the", "request" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/seed/config/init.go#L115-L119
train
edgexfoundry/edgex-go
internal/support/scheduler/loader.go
LoadScheduler
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
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 ...
[ "func", "LoadScheduler", "(", ")", "error", "{", "// ensure maps are clean", "clearMaps", "(", ")", "\n\n", "// ensure queue is empty", "clearQueue", "(", ")", "\n\n", "LoggingClient", ".", "Info", "(", "\"", "\"", ")", "\n\n", "// load data from support-scheduler dat...
// Utility function for adding configured locally intervals and scheduled events
[ "Utility", "function", "for", "adding", "configured", "locally", "intervals", "and", "scheduled", "events" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/support/scheduler/loader.go#L21-L55
train
edgexfoundry/edgex-go
internal/support/scheduler/loader.go
getSchedulerDBIntervals
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
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...
[ "func", "getSchedulerDBIntervals", "(", ")", "(", "[", "]", "contract", ".", "Interval", ",", "error", ")", "{", "var", "err", "error", "\n", "var", "intervals", "[", "]", "contract", ".", "Interval", "\n\n", "intervals", ",", "err", "=", "dbClient", "."...
// Query support-scheduler scheduler client get intervals
[ "Query", "support", "-", "scheduler", "scheduler", "client", "get", "intervals" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/support/scheduler/loader.go#L58-L76
train
edgexfoundry/edgex-go
internal/support/scheduler/loader.go
getSchedulerDBIntervalActions
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
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...
[ "func", "getSchedulerDBIntervalActions", "(", ")", "(", "[", "]", "contract", ".", "IntervalAction", ",", "error", ")", "{", "var", "err", "error", "\n", "var", "intervalActions", "[", "]", "contract", ".", "IntervalAction", "\n\n", "intervalActions", ",", "er...
// Query support-scheduler schedulerEvent client get scheduledEvents
[ "Query", "support", "-", "scheduler", "schedulerEvent", "client", "get", "scheduledEvents" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/support/scheduler/loader.go#L79-L97
train
edgexfoundry/edgex-go
internal/support/scheduler/loader.go
addReceivedIntervals
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
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...
[ "func", "addReceivedIntervals", "(", "intervals", "[", "]", "contract", ".", "Interval", ")", "error", "{", "for", "_", ",", "interval", ":=", "range", "intervals", "{", "err", ":=", "scClient", ".", "AddIntervalToQueue", "(", "interval", ")", "\n", "if", ...
// Iterate over the received intervals add them to scheduler memory queue
[ "Iterate", "over", "the", "received", "intervals", "add", "them", "to", "scheduler", "memory", "queue" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/support/scheduler/loader.go#L100-L110
train
edgexfoundry/edgex-go
internal/support/scheduler/loader.go
addIntervalToSchedulerDB
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
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...
[ "func", "addIntervalToSchedulerDB", "(", "interval", "contract", ".", "Interval", ")", "(", "string", ",", "error", ")", "{", "var", "err", "error", "\n", "var", "id", "string", "\n\n", "id", ",", "err", "=", "dbClient", ".", "AddInterval", "(", "interval"...
// Add interval to support-scheduler
[ "Add", "interval", "to", "support", "-", "scheduler" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/support/scheduler/loader.go#L126-L141
train
edgexfoundry/edgex-go
internal/support/scheduler/loader.go
addIntervalActionToSchedulerDB
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
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 ...
[ "func", "addIntervalActionToSchedulerDB", "(", "intervalAction", "contract", ".", "IntervalAction", ")", "(", "string", ",", "error", ")", "{", "var", "err", "error", "\n", "var", "id", "string", "\n\n", "id", ",", "err", "=", "dbClient", ".", "AddIntervalActi...
// Add interval event to support-scheduler
[ "Add", "interval", "event", "to", "support", "-", "scheduler" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/support/scheduler/loader.go#L144-L156
train
edgexfoundry/edgex-go
internal/support/scheduler/loader.go
loadConfigIntervalActions
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
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: ...
[ "func", "loadConfigIntervalActions", "(", ")", "error", "{", "intervalActions", ":=", "Configuration", ".", "IntervalActions", "\n\n", "for", "ia", ":=", "range", "intervalActions", "{", "intervalAction", ":=", "contract", ".", "IntervalAction", "{", "Name", ":", ...
// Load interval actions if required
[ "Load", "interval", "actions", "if", "required" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/support/scheduler/loader.go#L204-L248
train
edgexfoundry/edgex-go
internal/support/scheduler/loader.go
loadSupportSchedulerDBInformation
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
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...
[ "func", "loadSupportSchedulerDBInformation", "(", ")", "error", "{", "receivedIntervals", ",", "err", ":=", "getSchedulerDBIntervals", "(", ")", "\n", "if", "err", "!=", "nil", "{", "LoggingClient", ".", "Error", "(", "\"", "\"", "+", "err", ".", "Error", "(...
// Query support-scheduler database information
[ "Query", "support", "-", "scheduler", "database", "information" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/support/scheduler/loader.go#L251-L278
train
edgexfoundry/edgex-go
internal/export/distro/mqtt.go
newMqttSender
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
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...
[ "func", "newMqttSender", "(", "addr", "contract", ".", "Addressable", ",", "cert", "string", ",", "key", "string", ")", "sender", "{", "protocol", ":=", "strings", ".", "ToLower", "(", "addr", ".", "Protocol", ")", "\n\n", "opts", ":=", "MQTT", ".", "New...
// newMqttSender - create new mqtt sender
[ "newMqttSender", "-", "create", "new", "mqtt", "sender" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/export/distro/mqtt.go#L29-L64
train
edgexfoundry/edgex-go
internal/core/data/event.go
deleteEvent
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
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 }
[ "func", "deleteEvent", "(", "e", "contract", ".", "Event", ")", "error", "{", "for", "_", ",", "reading", ":=", "range", "e", ".", "Readings", "{", "if", "err", ":=", "deleteReadingById", "(", "reading", ".", "Id", ")", ";", "err", "!=", "nil", "{", ...
// Delete the event and readings
[ "Delete", "the", "event", "and", "readings" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/data/event.go#L167-L178
train
edgexfoundry/edgex-go
internal/core/data/event.go
putEventOnQueue
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
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...
[ "func", "putEventOnQueue", "(", "e", "contract", ".", "Event", ",", "ctx", "context", ".", "Context", ")", "{", "LoggingClient", ".", "Info", "(", "\"", "\"", ")", "\n", "//\tHave multiple implementations (start with ZeroMQ)", "evt", ":=", "models", ".", "Event"...
// Put event on the message queue to be processed by the rules engine
[ "Put", "event", "on", "the", "message", "queue", "to", "be", "processed", "by", "the", "rules", "engine" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/data/event.go#L210-L231
train
edgexfoundry/edgex-go
internal/core/command/rest.go
pingHandler
func pingHandler(w http.ResponseWriter, _ *http.Request) { w.Header().Set(CONTENTTYPE, TEXTPLAIN) w.Write([]byte(PINGRESPONSE)) }
go
func pingHandler(w http.ResponseWriter, _ *http.Request) { w.Header().Set(CONTENTTYPE, TEXTPLAIN) w.Write([]byte(PINGRESPONSE)) }
[ "func", "pingHandler", "(", "w", "http", ".", "ResponseWriter", ",", "_", "*", "http", ".", "Request", ")", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "CONTENTTYPE", ",", "TEXTPLAIN", ")", "\n", "w", ".", "Write", "(", "[", "]", "byte", ...
// Respond with PINGRESPONSE to see if the service is alive
[ "Respond", "with", "PINGRESPONSE", "to", "see", "if", "the", "service", "is", "alive" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/command/rest.go#L72-L75
train
edgexfoundry/edgex-go
internal/core/data/valuedescriptor.go
validateFormatString
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
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 } ...
[ "func", "validateFormatString", "(", "v", "contract", ".", "ValueDescriptor", ")", "error", "{", "// No formatting specified", "if", "v", ".", "Formatting", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n\n", "match", ",", "err", ":=", "regexp", ".", ...
// Check if the value descriptor matches the format string regular expression
[ "Check", "if", "the", "value", "descriptor", "matches", "the", "format", "string", "regular", "expression" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/data/valuedescriptor.go#L34-L53
train
edgexfoundry/edgex-go
internal/core/metadata/rest_addressable.go
restAddAddressable
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
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 {...
[ "func", "restAddAddressable", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "defer", "r", ".", "Body", ".", "Close", "(", ")", "\n", "var", "a", "models", ".", "Addressable", "\n", "err", ":=", "json", ".",...
// Add a new addressable // The name must be unique
[ "Add", "a", "new", "addressable", "The", "name", "must", "be", "unique" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_addressable.go#L50-L78
train
edgexfoundry/edgex-go
internal/core/metadata/rest_addressable.go
isAddressableStillInUse
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
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 }
[ "func", "isAddressableStillInUse", "(", "a", "models", ".", "Addressable", ")", "(", "bool", ",", "error", ")", "{", "// Check device services", "ds", ",", "err", ":=", "dbClient", ".", "GetDeviceServicesByAddressableId", "(", "a", ".", "Id", ")", "\n", "if", ...
// Helper function to determine if an addressable is still referenced by a device or device service
[ "Helper", "function", "to", "determine", "if", "an", "addressable", "is", "still", "referenced", "by", "a", "device", "or", "device", "service" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_addressable.go#L208-L219
train
edgexfoundry/edgex-go
internal/pkg/telemetry/windows_cpu.go
getSystemTimes
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
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 }
[ "func", "getSystemTimes", "(", "idleTime", ",", "kernelTime", ",", "userTime", "*", "FileTime", ")", "bool", "{", "ret", ",", "_", ",", "_", ":=", "procGetSystemTimes", ".", "Call", "(", "uintptr", "(", "unsafe", ".", "Pointer", "(", "idleTime", ")", ")"...
// getSystemTimes makes the system call to windows to get the system data
[ "getSystemTimes", "makes", "the", "system", "call", "to", "windows", "to", "get", "the", "system", "data" ]
c67086fe10c4d34caeefffaee5379490103dd63f
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/telemetry/windows_cpu.go#L63-L70
train
osrg/gobgp
internal/pkg/config/util.go
detectConfigFileType
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
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 } }
[ "func", "detectConfigFileType", "(", "path", ",", "def", "string", ")", "string", "{", "switch", "ext", ":=", "filepath", ".", "Ext", "(", "path", ")", ";", "ext", "{", "case", "\"", "\"", ":", "return", "\"", "\"", "\n", "case", "\"", "\"", ",", "...
// Returns config file type by retrieving extension from the given path. // If no corresponding type found, returns the given def as the default value.
[ "Returns", "config", "file", "type", "by", "retrieving", "extension", "from", "the", "given", "path", ".", "If", "no", "corresponding", "type", "found", "returns", "the", "given", "def", "as", "the", "default", "value", "." ]
cc267fad9e6410705420af220d73d25d288e8a58
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/config/util.go#L36-L47
train
osrg/gobgp
pkg/packet/bgp/bgp.go
FlatUpdate
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
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 } }
[ "func", "FlatUpdate", "(", "f1", ",", "f2", "map", "[", "string", "]", "string", ")", "error", "{", "conflict", ":=", "false", "\n", "for", "k2", ",", "v2", ":=", "range", "f2", "{", "if", "v1", ",", "ok", ":=", "f1", "[", "k2", "]", ";", "ok",...
// Update a Flat representation by adding elements of the second // one. If two elements use same keys, values are separated with // ';'. In this case, it returns an error but the update has been // realized.
[ "Update", "a", "Flat", "representation", "by", "adding", "elements", "of", "the", "second", "one", ".", "If", "two", "elements", "use", "same", "keys", "values", "are", "separated", "with", ";", ".", "In", "this", "case", "it", "returns", "an", "error", ...
cc267fad9e6410705420af220d73d25d288e8a58
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/pkg/packet/bgp/bgp.go#L12968-L12983
train
osrg/gobgp
internal/pkg/table/destination.go
Calculate
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
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...
[ "func", "(", "dest", "*", "Destination", ")", "Calculate", "(", "newPath", "*", "Path", ")", "*", "Update", "{", "oldKnownPathList", ":=", "make", "(", "[", "]", "*", "Path", ",", "len", "(", "dest", ".", "knownPathList", ")", ")", "\n", "copy", "(",...
// Calculates best-path among known paths for this destination. // // Modifies destination's state related to stored paths. Removes withdrawn // paths from known paths. Also, adds new paths to known paths.
[ "Calculates", "best", "-", "path", "among", "known", "paths", "for", "this", "destination", ".", "Modifies", "destination", "s", "state", "related", "to", "stored", "paths", ".", "Removes", "withdrawn", "paths", "from", "known", "paths", ".", "Also", "adds", ...
cc267fad9e6410705420af220d73d25d288e8a58
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/destination.go#L262-L297
train
osrg/gobgp
internal/pkg/table/destination.go
implicitWithdraw
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
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...
[ "func", "(", "dest", "*", "Destination", ")", "implicitWithdraw", "(", "newPath", "*", "Path", ")", "{", "found", ":=", "-", "1", "\n", "for", "i", ",", "path", ":=", "range", "dest", ".", "knownPathList", "{", "if", "newPath", ".", "NoImplicitWithdraw",...
// Identifies which of known paths are old and removes them. // // Known paths will no longer have paths whose new version is present in // new paths.
[ "Identifies", "which", "of", "known", "paths", "are", "old", "and", "removes", "them", ".", "Known", "paths", "will", "no", "longer", "have", "paths", "whose", "new", "version", "is", "present", "in", "new", "paths", "." ]
cc267fad9e6410705420af220d73d25d288e8a58
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/destination.go#L352-L377
train
osrg/gobgp
pkg/server/server.go
newTCPListener
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
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...
[ "func", "newTCPListener", "(", "address", "string", ",", "port", "uint32", ",", "ch", "chan", "*", "net", ".", "TCPConn", ")", "(", "*", "tcpListener", ",", "error", ")", "{", "proto", ":=", "\"", "\"", "\n", "if", "ip", ":=", "net", ".", "ParseIP", ...
// avoid mapped IPv6 address
[ "avoid", "mapped", "IPv6", "address" ]
cc267fad9e6410705420af220d73d25d288e8a58
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/pkg/server/server.go#L55-L99
train
osrg/gobgp
pkg/server/bmp.go
update
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
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) ...
[ "func", "(", "r", "ribout", ")", "update", "(", "p", "*", "table", ".", "Path", ")", "bool", "{", "key", ":=", "p", ".", "GetNlri", "(", ")", ".", "String", "(", ")", "// TODO expose (*Path).getPrefix()", "\n", "l", ":=", "r", "[", "key", "]", "\n"...
// return true if we need to send the path to the BMP server
[ "return", "true", "if", "we", "need", "to", "send", "the", "path", "to", "the", "BMP", "server" ]
cc267fad9e6410705420af220d73d25d288e8a58
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/pkg/server/bmp.go#L40-L82
train
osrg/gobgp
pkg/server/util.go
newAdministrativeCommunication
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
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...
[ "func", "newAdministrativeCommunication", "(", "communication", "string", ")", "(", "data", "[", "]", "byte", ")", "{", "if", "communication", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n", "com", ":=", "[", "]", "byte", "(", "communication", "...
// Returns the binary formatted Administrative Shutdown Communication from the // given string value.
[ "Returns", "the", "binary", "formatted", "Administrative", "Shutdown", "Communication", "from", "the", "given", "string", "value", "." ]
cc267fad9e6410705420af220d73d25d288e8a58
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/pkg/server/util.go#L37-L50
train
osrg/gobgp
pkg/server/util.go
decodeAdministrativeCommunication
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
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...
[ "func", "decodeAdministrativeCommunication", "(", "data", "[", "]", "byte", ")", "(", "string", ",", "[", "]", "byte", ")", "{", "if", "len", "(", "data", ")", "==", "0", "{", "return", "\"", "\"", ",", "data", "\n", "}", "\n", "communicationLen", ":...
// Parses the given NOTIFICATION message data as a binary value and returns // the Administrative Shutdown Communication in string and the rest binary.
[ "Parses", "the", "given", "NOTIFICATION", "message", "data", "as", "a", "binary", "value", "and", "returns", "the", "Administrative", "Shutdown", "Communication", "in", "string", "and", "the", "rest", "binary", "." ]
cc267fad9e6410705420af220d73d25d288e8a58
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/pkg/server/util.go#L54-L66
train
osrg/gobgp
internal/pkg/table/path.go
Clone
func (path *Path) Clone(isWithdraw bool) *Path { return &Path{ parent: path, IsWithdraw: isWithdraw, IsNexthopInvalid: path.IsNexthopInvalid, attrsHash: path.attrsHash, } }
go
func (path *Path) Clone(isWithdraw bool) *Path { return &Path{ parent: path, IsWithdraw: isWithdraw, IsNexthopInvalid: path.IsNexthopInvalid, attrsHash: path.attrsHash, } }
[ "func", "(", "path", "*", "Path", ")", "Clone", "(", "isWithdraw", "bool", ")", "*", "Path", "{", "return", "&", "Path", "{", "parent", ":", "path", ",", "IsWithdraw", ":", "isWithdraw", ",", "IsNexthopInvalid", ":", "path", ".", "IsNexthopInvalid", ",",...
// create new PathAttributes
[ "create", "new", "PathAttributes" ]
cc267fad9e6410705420af220d73d25d288e8a58
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/path.go#L335-L342
train
osrg/gobgp
internal/pkg/table/path.go
String
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
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...
[ "func", "(", "path", "*", "Path", ")", "String", "(", ")", "string", "{", "s", ":=", "bytes", ".", "NewBuffer", "(", "make", "(", "[", "]", "byte", ",", "0", ",", "64", ")", ")", "\n", "if", "path", ".", "IsEOR", "(", ")", "{", "s", ".", "W...
// return Path's string representation
[ "return", "Path", "s", "string", "representation" ]
cc267fad9e6410705420af220d73d25d288e8a58
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/path.go#L567-L584
train
osrg/gobgp
internal/pkg/table/path.go
GetAsPathLen
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
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 }
[ "func", "(", "path", "*", "Path", ")", "GetAsPathLen", "(", ")", "int", "{", "var", "length", "int", "=", "0", "\n", "if", "aspath", ":=", "path", ".", "GetAsPath", "(", ")", ";", "aspath", "!=", "nil", "{", "for", "_", ",", "as", ":=", "range", ...
// GetAsPathLen returns the number of AS_PATH
[ "GetAsPathLen", "returns", "the", "number", "of", "AS_PATH" ]
cc267fad9e6410705420af220d73d25d288e8a58
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/path.go#L599-L608
train
osrg/gobgp
internal/pkg/table/path.go
SetCommunities
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
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.(*...
[ "func", "(", "path", "*", "Path", ")", "SetCommunities", "(", "communities", "[", "]", "uint32", ",", "doReplace", "bool", ")", "{", "if", "len", "(", "communities", ")", "==", "0", "&&", "doReplace", "{", "// clear communities", "path", ".", "delPathAttr"...
// SetCommunities adds or replaces communities with new ones. // If the length of communities is 0 and doReplace is true, it clears communities.
[ "SetCommunities", "adds", "or", "replaces", "communities", "with", "new", "ones", ".", "If", "the", "length", "of", "communities", "is", "0", "and", "doReplace", "is", "true", "it", "clears", "communities", "." ]
cc267fad9e6410705420af220d73d25d288e8a58
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/path.go#L800-L823
train
osrg/gobgp
internal/pkg/table/path.go
RemoveCommunities
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
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...
[ "func", "(", "path", "*", "Path", ")", "RemoveCommunities", "(", "communities", "[", "]", "uint32", ")", "int", "{", "if", "len", "(", "communities", ")", "==", "0", "{", "// do nothing", "return", "0", "\n", "}", "\n\n", "find", ":=", "func", "(", "...
// RemoveCommunities removes specific communities. // If the length of communities is 0, it does nothing. // If all communities are removed, it removes Communities path attribute itself.
[ "RemoveCommunities", "removes", "specific", "communities", ".", "If", "the", "length", "of", "communities", "is", "0", "it", "does", "nothing", ".", "If", "all", "communities", "are", "removed", "it", "removes", "Communities", "path", "attribute", "itself", "." ...
cc267fad9e6410705420af220d73d25d288e8a58
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/path.go#L828-L865
train
osrg/gobgp
internal/pkg/table/path.go
SetMed
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
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...
[ "func", "(", "path", "*", "Path", ")", "SetMed", "(", "med", "int64", ",", "doReplace", "bool", ")", "error", "{", "parseMed", ":=", "func", "(", "orgMed", "uint32", ",", "med", "int64", ",", "doReplace", "bool", ")", "(", "*", "bgp", ".", "PathAttri...
// SetMed replace, add or subtraction med with new ones.
[ "SetMed", "replace", "add", "or", "subtraction", "med", "with", "new", "ones", "." ]
cc267fad9e6410705420af220d73d25d288e8a58
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/path.go#L926-L952
train
osrg/gobgp
internal/pkg/table/policy.go
Evaluate
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
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...
[ "func", "(", "c", "*", "NextHopCondition", ")", "Evaluate", "(", "path", "*", "Path", ",", "options", "*", "PolicyOptions", ")", "bool", "{", "if", "len", "(", "c", ".", "set", ".", "list", ")", "==", "0", "{", "log", ".", "WithFields", "(", "log",...
// compare next-hop ipaddress of this condition and source address of path // and, subsequent comparisons are skipped if that matches the conditions. // If NextHopSet's length is zero, return true.
[ "compare", "next", "-", "hop", "ipaddress", "of", "this", "condition", "and", "source", "address", "of", "path", "and", "subsequent", "comparisons", "are", "skipped", "if", "that", "matches", "the", "conditions", ".", "If", "NextHopSet", "s", "length", "is", ...
cc267fad9e6410705420af220d73d25d288e8a58
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/policy.go#L1387-L1417
train
osrg/gobgp
internal/pkg/table/policy.go
Evaluate
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
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 :...
[ "func", "(", "c", "*", "PrefixCondition", ")", "Evaluate", "(", "path", "*", "Path", ",", "_", "*", "PolicyOptions", ")", "bool", "{", "var", "key", "string", "\n", "var", "masklen", "uint8", "\n", "keyf", ":=", "func", "(", "ip", "net", ".", "IP", ...
// compare prefixes in this condition and nlri of path and // subsequent comparison is skipped if that matches the conditions. // If PrefixList's length is zero, return true.
[ "compare", "prefixes", "in", "this", "condition", "and", "nlri", "of", "path", "and", "subsequent", "comparison", "is", "skipped", "if", "that", "matches", "the", "conditions", ".", "If", "PrefixList", "s", "length", "is", "zero", "return", "true", "." ]
cc267fad9e6410705420af220d73d25d288e8a58
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/policy.go#L1454-L1495
train
osrg/gobgp
internal/pkg/table/policy.go
Evaluate
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
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...
[ "func", "(", "c", "*", "NeighborCondition", ")", "Evaluate", "(", "path", "*", "Path", ",", "options", "*", "PolicyOptions", ")", "bool", "{", "if", "len", "(", "c", ".", "set", ".", "list", ")", "==", "0", "{", "log", ".", "WithFields", "(", "log"...
// compare neighbor ipaddress of this condition and source address of path // and, subsequent comparisons are skipped if that matches the conditions. // If NeighborList's length is zero, return true.
[ "compare", "neighbor", "ipaddress", "of", "this", "condition", "and", "source", "address", "of", "path", "and", "subsequent", "comparisons", "are", "skipped", "if", "that", "matches", "the", "conditions", ".", "If", "NeighborList", "s", "length", "is", "zero", ...
cc267fad9e6410705420af220d73d25d288e8a58
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/policy.go#L1535-L1564
train
osrg/gobgp
internal/pkg/table/policy.go
Evaluate
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
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...
[ "func", "(", "c", "*", "AsPathLengthCondition", ")", "Evaluate", "(", "path", "*", "Path", ",", "_", "*", "PolicyOptions", ")", "bool", "{", "length", ":=", "uint32", "(", "path", ".", "GetAsPathLen", "(", ")", ")", "\n", "result", ":=", "false", "\n",...
// compare AS_PATH length in the message's AS_PATH attribute with // the one in condition.
[ "compare", "AS_PATH", "length", "in", "the", "message", "s", "AS_PATH", "attribute", "with", "the", "one", "in", "condition", "." ]
cc267fad9e6410705420af220d73d25d288e8a58
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/policy.go#L1855-L1869
train
osrg/gobgp
internal/pkg/table/policy.go
NewAsPathPrependAction
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
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...
[ "func", "NewAsPathPrependAction", "(", "action", "config", ".", "SetAsPathPrepend", ")", "(", "*", "AsPathPrependAction", ",", "error", ")", "{", "a", ":=", "&", "AsPathPrependAction", "{", "repeat", ":", "action", ".", "RepeatN", ",", "}", "\n", "switch", "...
// NewAsPathPrependAction creates AsPathPrependAction object. // If ASN cannot be parsed, nil will be returned.
[ "NewAsPathPrependAction", "creates", "AsPathPrependAction", "object", ".", "If", "ASN", "cannot", "be", "parsed", "nil", "will", "be", "returned", "." ]
cc267fad9e6410705420af220d73d25d288e8a58
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/policy.go#L2574-L2594
train
osrg/gobgp
internal/pkg/table/policy.go
Evaluate
func (s *Statement) Evaluate(p *Path, options *PolicyOptions) bool { for _, c := range s.Conditions { if !c.Evaluate(p, options) { return false } } return true }
go
func (s *Statement) Evaluate(p *Path, options *PolicyOptions) bool { for _, c := range s.Conditions { if !c.Evaluate(p, options) { return false } } return true }
[ "func", "(", "s", "*", "Statement", ")", "Evaluate", "(", "p", "*", "Path", ",", "options", "*", "PolicyOptions", ")", "bool", "{", "for", "_", ",", "c", ":=", "range", "s", ".", "Conditions", "{", "if", "!", "c", ".", "Evaluate", "(", "p", ",", ...
// evaluate each condition in the statement according to MatchSetOptions
[ "evaluate", "each", "condition", "in", "the", "statement", "according", "to", "MatchSetOptions" ]
cc267fad9e6410705420af220d73d25d288e8a58
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/policy.go#L2657-L2664
train
osrg/gobgp
internal/pkg/table/policy.go
Apply
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
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 }
[ "func", "(", "p", "*", "Policy", ")", "Apply", "(", "path", "*", "Path", ",", "options", "*", "PolicyOptions", ")", "(", "RouteType", ",", "*", "Path", ")", "{", "for", "_", ",", "stmt", ":=", "range", "p", ".", "Statements", "{", "var", "result", ...
// Compare path with a policy's condition in stored order in the policy. // If a condition match, then this function stops evaluation and // subsequent conditions are skipped.
[ "Compare", "path", "with", "a", "policy", "s", "condition", "in", "stored", "order", "in", "the", "policy", ".", "If", "a", "condition", "match", "then", "this", "function", "stops", "evaluation", "and", "subsequent", "conditions", "are", "skipped", "." ]
cc267fad9e6410705420af220d73d25d288e8a58
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/policy.go#L2990-L2999
train
osrg/gobgp
internal/pkg/zebra/zapi.go
ChannelClose
func ChannelClose(ch chan *Message) bool { select { case _, ok := <-ch: if ok { close(ch) return true } default: } return false }
go
func ChannelClose(ch chan *Message) bool { select { case _, ok := <-ch: if ok { close(ch) return true } default: } return false }
[ "func", "ChannelClose", "(", "ch", "chan", "*", "Message", ")", "bool", "{", "select", "{", "case", "_", ",", "ok", ":=", "<-", "ch", ":", "if", "ok", "{", "close", "(", "ch", ")", "\n", "return", "true", "\n", "}", "\n", "default", ":", "}", "...
// for avoiding double close
[ "for", "avoiding", "double", "close" ]
cc267fad9e6410705420af220d73d25d288e8a58
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/zebra/zapi.go#L1415-L1425
train
osrg/gobgp
pkg/packet/bgp/validate.go
validatePathAttributeFlags
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
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...
[ "func", "validatePathAttributeFlags", "(", "t", "BGPAttrType", ",", "flags", "BGPAttrFlag", ")", "string", "{", "/*\n\t * RFC 4271 P.17 For well-known attributes, the Transitive bit MUST be set to 1.\n\t */", "if", "flags", "&", "BGP_ATTR_FLAG_OPTIONAL", "==", "0", "&&", "flags...
// validator for PathAttribute
[ "validator", "for", "PathAttribute" ]
cc267fad9e6410705420af220d73d25d288e8a58
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/pkg/packet/bgp/validate.go#L227-L257
train
rs/cors
wrapper/gin/gin.go
build
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
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...
[ "func", "(", "c", "corsWrapper", ")", "build", "(", ")", "gin", ".", "HandlerFunc", "{", "return", "func", "(", "ctx", "*", "gin", ".", "Context", ")", "{", "c", ".", "HandlerFunc", "(", "ctx", ".", "Writer", ",", "ctx", ".", "Request", ")", "\n", ...
// build transforms wrapped cors.Cors handler into Gin middleware.
[ "build", "transforms", "wrapped", "cors", ".", "Cors", "handler", "into", "Gin", "middleware", "." ]
76f58f330d76a55c5badc74f6212e8a15e742c77
https://github.com/rs/cors/blob/76f58f330d76a55c5badc74f6212e8a15e742c77/wrapper/gin/gin.go#L23-L33
train
rs/cors
wrapper/gin/gin.go
New
func New(options Options) gin.HandlerFunc { return corsWrapper{cors.New(options), options.OptionsPassthrough}.build() }
go
func New(options Options) gin.HandlerFunc { return corsWrapper{cors.New(options), options.OptionsPassthrough}.build() }
[ "func", "New", "(", "options", "Options", ")", "gin", ".", "HandlerFunc", "{", "return", "corsWrapper", "{", "cors", ".", "New", "(", "options", ")", ",", "options", ".", "OptionsPassthrough", "}", ".", "build", "(", ")", "\n", "}" ]
// New creates a new CORS Gin middleware with the provided options.
[ "New", "creates", "a", "new", "CORS", "Gin", "middleware", "with", "the", "provided", "options", "." ]
76f58f330d76a55c5badc74f6212e8a15e742c77
https://github.com/rs/cors/blob/76f58f330d76a55c5badc74f6212e8a15e742c77/wrapper/gin/gin.go#L48-L50
train
rs/cors
cors.go
AllowAll
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
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, }) }
[ "func", "AllowAll", "(", ")", "*", "Cors", "{", "return", "New", "(", "Options", "{", "AllowedOrigins", ":", "[", "]", "string", "{", "\"", "\"", "}", ",", "AllowedMethods", ":", "[", "]", "string", "{", "http", ".", "MethodHead", ",", "http", ".", ...
// AllowAll create a new Cors handler with permissive configuration allowing all // origins with all standard methods with any header and credentials.
[ "AllowAll", "create", "a", "new", "Cors", "handler", "with", "permissive", "configuration", "allowing", "all", "origins", "with", "all", "standard", "methods", "with", "any", "header", "and", "credentials", "." ]
76f58f330d76a55c5badc74f6212e8a15e742c77
https://github.com/rs/cors/blob/76f58f330d76a55c5badc74f6212e8a15e742c77/cors.go#L179-L193
train
rs/cors
cors.go
Handler
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
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...
[ "func", "(", "c", "*", "Cors", ")", "Handler", "(", "h", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")...
// Handler apply the CORS specification on the request, and add relevant CORS headers // as necessary.
[ "Handler", "apply", "the", "CORS", "specification", "on", "the", "request", "and", "add", "relevant", "CORS", "headers", "as", "necessary", "." ]
76f58f330d76a55c5badc74f6212e8a15e742c77
https://github.com/rs/cors/blob/76f58f330d76a55c5badc74f6212e8a15e742c77/cors.go#L197-L217
train
rs/cors
cors.go
HandlerFunc
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
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) } }
[ "func", "(", "c", "*", "Cors", ")", "HandlerFunc", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "r", ".", "Method", "==", "http", ".", "MethodOptions", "&&", "r", ".", "Header", ".", "Get", "(", ...
// HandlerFunc provides Martini compatible handler
[ "HandlerFunc", "provides", "Martini", "compatible", "handler" ]
76f58f330d76a55c5badc74f6212e8a15e742c77
https://github.com/rs/cors/blob/76f58f330d76a55c5badc74f6212e8a15e742c77/cors.go#L220-L228
train
rs/cors
cors.go
areHeadersAllowed
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
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 ...
[ "func", "(", "c", "*", "Cors", ")", "areHeadersAllowed", "(", "requestedHeaders", "[", "]", "string", ")", "bool", "{", "if", "c", ".", "allowedHeadersAll", "||", "len", "(", "requestedHeaders", ")", "==", "0", "{", "return", "true", "\n", "}", "\n", "...
// areHeadersAllowed checks if a given list of headers are allowed to used within // a cross-domain request.
[ "areHeadersAllowed", "checks", "if", "a", "given", "list", "of", "headers", "are", "allowed", "to", "used", "within", "a", "cross", "-", "domain", "request", "." ]
76f58f330d76a55c5badc74f6212e8a15e742c77
https://github.com/rs/cors/blob/76f58f330d76a55c5badc74f6212e8a15e742c77/cors.go#L407-L424
train
shiyanhui/dht
routingtable.go
newNode
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
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 }
[ "func", "newNode", "(", "id", ",", "network", ",", "address", "string", ")", "(", "*", "node", ",", "error", ")", "{", "if", "len", "(", "id", ")", "!=", "20", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", ...
// newNode returns a node pointer.
[ "newNode", "returns", "a", "node", "pointer", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L23-L34
train
shiyanhui/dht
routingtable.go
newNodeFromCompactInfo
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
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...
[ "func", "newNodeFromCompactInfo", "(", "compactNodeInfo", "string", ",", "network", "string", ")", "(", "*", "node", ",", "error", ")", "{", "if", "len", "(", "compactNodeInfo", ")", "!=", "26", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"",...
// newNodeFromCompactInfo parses compactNodeInfo and returns a node pointer.
[ "newNodeFromCompactInfo", "parses", "compactNodeInfo", "and", "returns", "a", "node", "pointer", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L37-L48
train
shiyanhui/dht
routingtable.go
newPeer
func newPeer(ip net.IP, port int, token string) *Peer { return &Peer{ IP: ip, Port: port, token: token, } }
go
func newPeer(ip net.IP, port int, token string) *Peer { return &Peer{ IP: ip, Port: port, token: token, } }
[ "func", "newPeer", "(", "ip", "net", ".", "IP", ",", "port", "int", ",", "token", "string", ")", "*", "Peer", "{", "return", "&", "Peer", "{", "IP", ":", "ip", ",", "Port", ":", "port", ",", "token", ":", "token", ",", "}", "\n", "}" ]
// newPeer returns a new peer pointer.
[ "newPeer", "returns", "a", "new", "peer", "pointer", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L73-L79
train
shiyanhui/dht
routingtable.go
Insert
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
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...
[ "func", "(", "pm", "*", "peersManager", ")", "Insert", "(", "infoHash", "string", ",", "peer", "*", "Peer", ")", "{", "pm", ".", "Lock", "(", ")", "\n", "if", "_", ",", "ok", ":=", "pm", ".", "table", ".", "Get", "(", "infoHash", ")", ";", "!",...
// Insert adds a peer into peersManager.
[ "Insert", "adds", "a", "peer", "into", "peersManager", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L114-L128
train
shiyanhui/dht
routingtable.go
GetPeers
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
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...
[ "func", "(", "pm", "*", "peersManager", ")", "GetPeers", "(", "infoHash", "string", ",", "size", "int", ")", "[", "]", "*", "Peer", "{", "peers", ":=", "make", "(", "[", "]", "*", "Peer", ",", "0", ",", "size", ")", "\n\n", "v", ",", "ok", ":="...
// GetPeers returns size-length peers who announces having infoHash.
[ "GetPeers", "returns", "size", "-", "length", "peers", "who", "announces", "having", "infoHash", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L131-L147
train
shiyanhui/dht
routingtable.go
newKBucket
func newKBucket(prefix *bitmap) *kbucket { bucket := &kbucket{ nodes: newKeyedDeque(), candidates: newKeyedDeque(), lastChanged: time.Now(), prefix: prefix, } return bucket }
go
func newKBucket(prefix *bitmap) *kbucket { bucket := &kbucket{ nodes: newKeyedDeque(), candidates: newKeyedDeque(), lastChanged: time.Now(), prefix: prefix, } return bucket }
[ "func", "newKBucket", "(", "prefix", "*", "bitmap", ")", "*", "kbucket", "{", "bucket", ":=", "&", "kbucket", "{", "nodes", ":", "newKeyedDeque", "(", ")", ",", "candidates", ":", "newKeyedDeque", "(", ")", ",", "lastChanged", ":", "time", ".", "Now", ...
// newKBucket returns a new kbucket pointer.
[ "newKBucket", "returns", "a", "new", "kbucket", "pointer", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L158-L166
train
shiyanhui/dht
routingtable.go
LastChanged
func (bucket *kbucket) LastChanged() time.Time { bucket.RLock() defer bucket.RUnlock() return bucket.lastChanged }
go
func (bucket *kbucket) LastChanged() time.Time { bucket.RLock() defer bucket.RUnlock() return bucket.lastChanged }
[ "func", "(", "bucket", "*", "kbucket", ")", "LastChanged", "(", ")", "time", ".", "Time", "{", "bucket", ".", "RLock", "(", ")", "\n", "defer", "bucket", ".", "RUnlock", "(", ")", "\n\n", "return", "bucket", ".", "lastChanged", "\n", "}" ]
// LastChanged return the last time when it changes.
[ "LastChanged", "return", "the", "last", "time", "when", "it", "changes", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L169-L174
train
shiyanhui/dht
routingtable.go
RandomChildID
func (bucket *kbucket) RandomChildID() string { prefixLen := bucket.prefix.Size / 8 return strings.Join([]string{ bucket.prefix.RawString()[:prefixLen], randomString(20 - prefixLen), }, "") }
go
func (bucket *kbucket) RandomChildID() string { prefixLen := bucket.prefix.Size / 8 return strings.Join([]string{ bucket.prefix.RawString()[:prefixLen], randomString(20 - prefixLen), }, "") }
[ "func", "(", "bucket", "*", "kbucket", ")", "RandomChildID", "(", ")", "string", "{", "prefixLen", ":=", "bucket", ".", "prefix", ".", "Size", "/", "8", "\n\n", "return", "strings", ".", "Join", "(", "[", "]", "string", "{", "bucket", ".", "prefix", ...
// RandomChildID returns a random id that has the same prefix with bucket.
[ "RandomChildID", "returns", "a", "random", "id", "that", "has", "the", "same", "prefix", "with", "bucket", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L177-L184
train
shiyanhui/dht
routingtable.go
UpdateTimestamp
func (bucket *kbucket) UpdateTimestamp() { bucket.Lock() defer bucket.Unlock() bucket.lastChanged = time.Now() }
go
func (bucket *kbucket) UpdateTimestamp() { bucket.Lock() defer bucket.Unlock() bucket.lastChanged = time.Now() }
[ "func", "(", "bucket", "*", "kbucket", ")", "UpdateTimestamp", "(", ")", "{", "bucket", ".", "Lock", "(", ")", "\n", "defer", "bucket", ".", "Unlock", "(", ")", "\n\n", "bucket", ".", "lastChanged", "=", "time", ".", "Now", "(", ")", "\n", "}" ]
// UpdateTimestamp update bucket's last changed time..
[ "UpdateTimestamp", "update", "bucket", "s", "last", "changed", "time", ".." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L187-L192
train
shiyanhui/dht
routingtable.go
Insert
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
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 }
[ "func", "(", "bucket", "*", "kbucket", ")", "Insert", "(", "no", "*", "node", ")", "bool", "{", "isNew", ":=", "!", "bucket", ".", "nodes", ".", "HasKey", "(", "no", ".", "id", ".", "RawString", "(", ")", ")", "\n\n", "bucket", ".", "nodes", ".",...
// Insert inserts node to the bucket. It returns whether the node is new in // the bucket.
[ "Insert", "inserts", "node", "to", "the", "bucket", ".", "It", "returns", "whether", "the", "node", "is", "new", "in", "the", "bucket", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L196-L203
train
shiyanhui/dht
routingtable.go
Fresh
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
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) } } }
[ "func", "(", "bucket", "*", "kbucket", ")", "Fresh", "(", "dht", "*", "DHT", ")", "{", "for", "e", ":=", "range", "bucket", ".", "nodes", ".", "Iter", "(", ")", "{", "no", ":=", "e", ".", "Value", ".", "(", "*", "node", ")", "\n", "if", "time...
// Fresh pings the expired nodes in the bucket.
[ "Fresh", "pings", "the", "expired", "nodes", "in", "the", "bucket", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L233-L240
train
shiyanhui/dht
routingtable.go
newRoutingTableNode
func newRoutingTableNode(prefix *bitmap) *routingTableNode { return &routingTableNode{ children: make([]*routingTableNode, 2), bucket: newKBucket(prefix), } }
go
func newRoutingTableNode(prefix *bitmap) *routingTableNode { return &routingTableNode{ children: make([]*routingTableNode, 2), bucket: newKBucket(prefix), } }
[ "func", "newRoutingTableNode", "(", "prefix", "*", "bitmap", ")", "*", "routingTableNode", "{", "return", "&", "routingTableNode", "{", "children", ":", "make", "(", "[", "]", "*", "routingTableNode", ",", "2", ")", ",", "bucket", ":", "newKBucket", "(", "...
// newRoutingTableNode returns a new routingTableNode pointer.
[ "newRoutingTableNode", "returns", "a", "new", "routingTableNode", "pointer", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L250-L255
train
shiyanhui/dht
routingtable.go
Child
func (tableNode *routingTableNode) Child(index int) *routingTableNode { if index >= 2 { return nil } tableNode.RLock() defer tableNode.RUnlock() return tableNode.children[index] }
go
func (tableNode *routingTableNode) Child(index int) *routingTableNode { if index >= 2 { return nil } tableNode.RLock() defer tableNode.RUnlock() return tableNode.children[index] }
[ "func", "(", "tableNode", "*", "routingTableNode", ")", "Child", "(", "index", "int", ")", "*", "routingTableNode", "{", "if", "index", ">=", "2", "{", "return", "nil", "\n", "}", "\n\n", "tableNode", ".", "RLock", "(", ")", "\n", "defer", "tableNode", ...
// Child returns routingTableNode's left or right child.
[ "Child", "returns", "routingTableNode", "s", "left", "or", "right", "child", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L258-L267
train
shiyanhui/dht
routingtable.go
SetChild
func (tableNode *routingTableNode) SetChild(index int, c *routingTableNode) { tableNode.Lock() defer tableNode.Unlock() tableNode.children[index] = c }
go
func (tableNode *routingTableNode) SetChild(index int, c *routingTableNode) { tableNode.Lock() defer tableNode.Unlock() tableNode.children[index] = c }
[ "func", "(", "tableNode", "*", "routingTableNode", ")", "SetChild", "(", "index", "int", ",", "c", "*", "routingTableNode", ")", "{", "tableNode", ".", "Lock", "(", ")", "\n", "defer", "tableNode", ".", "Unlock", "(", ")", "\n\n", "tableNode", ".", "chil...
// SetChild sets routingTableNode's left or right child. When index is 0, it's // the left child, if 1, it's the right child.
[ "SetChild", "sets", "routingTableNode", "s", "left", "or", "right", "child", ".", "When", "index", "is", "0", "it", "s", "the", "left", "child", "if", "1", "it", "s", "the", "right", "child", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L271-L276
train
shiyanhui/dht
routingtable.go
KBucket
func (tableNode *routingTableNode) KBucket() *kbucket { tableNode.RLock() defer tableNode.RUnlock() return tableNode.bucket }
go
func (tableNode *routingTableNode) KBucket() *kbucket { tableNode.RLock() defer tableNode.RUnlock() return tableNode.bucket }
[ "func", "(", "tableNode", "*", "routingTableNode", ")", "KBucket", "(", ")", "*", "kbucket", "{", "tableNode", ".", "RLock", "(", ")", "\n", "defer", "tableNode", ".", "RUnlock", "(", ")", "\n\n", "return", "tableNode", ".", "bucket", "\n", "}" ]
// KBucket returns the bucket routingTableNode holds.
[ "KBucket", "returns", "the", "bucket", "routingTableNode", "holds", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L279-L284
train
shiyanhui/dht
routingtable.go
SetKBucket
func (tableNode *routingTableNode) SetKBucket(bucket *kbucket) { tableNode.Lock() defer tableNode.Unlock() tableNode.bucket = bucket }
go
func (tableNode *routingTableNode) SetKBucket(bucket *kbucket) { tableNode.Lock() defer tableNode.Unlock() tableNode.bucket = bucket }
[ "func", "(", "tableNode", "*", "routingTableNode", ")", "SetKBucket", "(", "bucket", "*", "kbucket", ")", "{", "tableNode", ".", "Lock", "(", ")", "\n", "defer", "tableNode", ".", "Unlock", "(", ")", "\n\n", "tableNode", ".", "bucket", "=", "bucket", "\n...
// SetKBucket sets the bucket.
[ "SetKBucket", "sets", "the", "bucket", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L287-L292
train
shiyanhui/dht
routingtable.go
Split
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
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...
[ "func", "(", "tableNode", "*", "routingTableNode", ")", "Split", "(", ")", "{", "prefixLen", ":=", "tableNode", ".", "KBucket", "(", ")", ".", "prefix", ".", "Size", "\n\n", "if", "prefixLen", "==", "maxPrefixLength", "{", "return", "\n", "}", "\n\n", "f...
// Split splits current routingTableNode and sets it's two children.
[ "Split", "splits", "current", "routingTableNode", "and", "sets", "it", "s", "two", "children", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L295-L324
train
shiyanhui/dht
routingtable.go
newRoutingTable
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
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...
[ "func", "newRoutingTable", "(", "k", "int", ",", "dht", "*", "DHT", ")", "*", "routingTable", "{", "root", ":=", "newRoutingTableNode", "(", "newBitmap", "(", "0", ")", ")", "\n\n", "rt", ":=", "&", "routingTable", "{", "RWMutex", ":", "&", "sync", "."...
// newRoutingTable returns a new routingTable pointer.
[ "newRoutingTable", "returns", "a", "new", "routingTable", "pointer", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L338-L353
train
shiyanhui/dht
routingtable.go
Insert
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
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...
[ "func", "(", "rt", "*", "routingTable", ")", "Insert", "(", "nd", "*", "node", ")", "bool", "{", "rt", ".", "Lock", "(", ")", "\n", "defer", "rt", ".", "Unlock", "(", ")", "\n\n", "if", "rt", ".", "dht", ".", "blackList", ".", "in", "(", "nd", ...
// Insert adds a node to routing table. It returns whether the node is new // in the routingtable.
[ "Insert", "adds", "a", "node", "to", "routing", "table", ".", "It", "returns", "whether", "the", "node", "is", "new", "in", "the", "routingtable", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L357-L415
train
shiyanhui/dht
routingtable.go
GetNeighbors
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
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)) ...
[ "func", "(", "rt", "*", "routingTable", ")", "GetNeighbors", "(", "id", "*", "bitmap", ",", "size", "int", ")", "[", "]", "*", "node", "{", "rt", ".", "RLock", "(", ")", "\n", "nodes", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "0...
// GetNeighbors returns the size-length nodes closest to id.
[ "GetNeighbors", "returns", "the", "size", "-", "length", "nodes", "closest", "to", "id", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L418-L433
train
shiyanhui/dht
routingtable.go
GetNeighborCompactInfos
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
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 }
[ "func", "(", "rt", "*", "routingTable", ")", "GetNeighborCompactInfos", "(", "id", "*", "bitmap", ",", "size", "int", ")", "[", "]", "string", "{", "neighbors", ":=", "rt", ".", "GetNeighbors", "(", "id", ",", "size", ")", "\n", "infos", ":=", "make", ...
// GetNeighborIds return the size-length compact node info closest to id.
[ "GetNeighborIds", "return", "the", "size", "-", "length", "compact", "node", "info", "closest", "to", "id", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L436-L445
train
shiyanhui/dht
routingtable.go
GetNodeKBucktByID
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
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()....
[ "func", "(", "rt", "*", "routingTable", ")", "GetNodeKBucktByID", "(", "id", "*", "bitmap", ")", "(", "nd", "*", "node", ",", "bucket", "*", "kbucket", ")", "{", "rt", ".", "RLock", "(", ")", "\n", "defer", "rt", ".", "RUnlock", "(", ")", "\n\n", ...
// GetNodeKBucktById returns node whose id is `id` and the bucket it // belongs to.
[ "GetNodeKBucktById", "returns", "node", "whose", "id", "is", "id", "and", "the", "bucket", "it", "belongs", "to", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L449-L471
train
shiyanhui/dht
routingtable.go
GetNodeByAddress
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
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 }
[ "func", "(", "rt", "*", "routingTable", ")", "GetNodeByAddress", "(", "address", "string", ")", "(", "no", "*", "node", ",", "ok", "bool", ")", "{", "rt", ".", "RLock", "(", ")", "\n", "defer", "rt", ".", "RUnlock", "(", ")", "\n\n", "v", ",", "o...
// GetNodeByAddress finds node by address.
[ "GetNodeByAddress", "finds", "node", "by", "address", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L474-L483
train
shiyanhui/dht
routingtable.go
Remove
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
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) } }
[ "func", "(", "rt", "*", "routingTable", ")", "Remove", "(", "id", "*", "bitmap", ")", "{", "if", "nd", ",", "bucket", ":=", "rt", ".", "GetNodeKBucktByID", "(", "id", ")", ";", "nd", "!=", "nil", "{", "bucket", ".", "Replace", "(", "nd", ")", "\n...
// Remove deletes the node whose id is `id`.
[ "Remove", "deletes", "the", "node", "whose", "id", "is", "id", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L486-L492
train
shiyanhui/dht
routingtable.go
Fresh
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
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...
[ "func", "(", "rt", "*", "routingTable", ")", "Fresh", "(", ")", "{", "now", ":=", "time", ".", "Now", "(", ")", "\n\n", "for", "e", ":=", "range", "rt", ".", "cachedKBuckets", ".", "Iter", "(", ")", "{", "bucket", ":=", "e", ".", "Value", ".", ...
// Fresh sends findNode to all nodes in the expired nodes.
[ "Fresh", "sends", "findNode", "to", "all", "nodes", "in", "the", "expired", "nodes", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L503-L531
train
shiyanhui/dht
routingtable.go
Len
func (rt *routingTable) Len() int { rt.RLock() defer rt.RUnlock() return rt.cachedNodes.Len() }
go
func (rt *routingTable) Len() int { rt.RLock() defer rt.RUnlock() return rt.cachedNodes.Len() }
[ "func", "(", "rt", "*", "routingTable", ")", "Len", "(", ")", "int", "{", "rt", ".", "RLock", "(", ")", "\n", "defer", "rt", ".", "RUnlock", "(", ")", "\n\n", "return", "rt", ".", "cachedNodes", ".", "Len", "(", ")", "\n", "}" ]
// Len returns the number of nodes in table.
[ "Len", "returns", "the", "number", "of", "nodes", "in", "table", "." ]
1b3b78ecf279a28409577382c3ae95df5703cf50
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L534-L539
train