_id stringlengths 2 7 | title stringlengths 1 118 | partition stringclasses 3
values | text stringlengths 52 85.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q24500 | createRespMux | train | func (nc *Conn) createRespMux(respSub string) error {
s, err := nc.Subscribe(respSub, nc.respHandler)
if err != nil {
return err
}
nc.mu.Lock()
nc.respMux = s
nc.mu.Unlock()
return nil
} | go | {
"resource": ""
} |
q24501 | Request | train | func (nc *Conn) Request(subj string, data []byte, timeout time.Duration) (*Msg, error) {
if nc == nil {
return nil, ErrInvalidConnection
}
nc.mu.Lock()
// If user wants the old style.
if nc.Opts.UseOldRequestStyle {
nc.mu.Unlock()
return nc.oldRequest(subj, data, timeout)
}
// Do setup for the new style.... | go | {
"resource": ""
} |
q24502 | NewInbox | train | func NewInbox() string {
var b [inboxPrefixLen + nuidSize]byte
pres := b[:inboxPrefixLen]
copy(pres, InboxPrefix)
ns := b[inboxPrefixLen:]
copy(ns, nuid.Next())
return string(b[:])
} | go | {
"resource": ""
} |
q24503 | initNewResp | train | func (nc *Conn) initNewResp() {
// _INBOX wildcard
nc.respSub = fmt.Sprintf("%s.*", NewInbox())
nc.respMap = make(map[string]chan *Msg)
nc.respRand = rand.New(rand.NewSource(time.Now().UnixNano()))
} | go | {
"resource": ""
} |
q24504 | newRespInbox | train | func (nc *Conn) newRespInbox() string {
if nc.respMap == nil {
nc.initNewResp()
}
var b [respInboxPrefixLen + replySuffixLen]byte
pres := b[:respInboxPrefixLen]
copy(pres, nc.respSub)
rn := nc.respRand.Int63()
for i, l := respInboxPrefixLen, rn; i < len(b); i++ {
b[i] = rdigits[l%base]
l /= base
}
return... | go | {
"resource": ""
} |
q24505 | NewRespInbox | train | func (nc *Conn) NewRespInbox() string {
nc.mu.Lock()
s := nc.newRespInbox()
nc.mu.Unlock()
return s
} | go | {
"resource": ""
} |
q24506 | QueueSubscribe | train | func (nc *Conn) QueueSubscribe(subj, queue string, cb MsgHandler) (*Subscription, error) {
return nc.subscribe(subj, queue, cb, nil, false)
} | go | {
"resource": ""
} |
q24507 | subscribe | train | func (nc *Conn) subscribe(subj, queue string, cb MsgHandler, ch chan *Msg, isSync bool) (*Subscription, error) {
if nc == nil {
return nil, ErrInvalidConnection
}
nc.mu.Lock()
// ok here, but defer is generally expensive
defer nc.mu.Unlock()
// Check for some error conditions.
if nc.isClosed() {
return nil,... | go | {
"resource": ""
} |
q24508 | NumSubscriptions | train | func (nc *Conn) NumSubscriptions() int {
nc.mu.RLock()
defer nc.mu.RUnlock()
return len(nc.subs)
} | go | {
"resource": ""
} |
q24509 | removeSub | train | func (nc *Conn) removeSub(s *Subscription) {
nc.subsMu.Lock()
delete(nc.subs, s.sid)
nc.subsMu.Unlock()
s.mu.Lock()
defer s.mu.Unlock()
// Release callers on NextMsg for SyncSubscription only
if s.mch != nil && s.typ == SyncSubscription {
close(s.mch)
}
s.mch = nil
// Mark as invalid
s.conn = nil
s.close... | go | {
"resource": ""
} |
q24510 | Type | train | func (s *Subscription) Type() SubscriptionType {
if s == nil {
return NilSubscription
}
s.mu.Lock()
defer s.mu.Unlock()
return s.typ
} | go | {
"resource": ""
} |
q24511 | Drain | train | func (s *Subscription) Drain() error {
if s == nil {
return ErrBadSubscription
}
s.mu.Lock()
conn := s.conn
s.mu.Unlock()
if conn == nil {
return ErrBadSubscription
}
return conn.unsubscribe(s, 0, true)
} | go | {
"resource": ""
} |
q24512 | Unsubscribe | train | func (s *Subscription) Unsubscribe() error {
if s == nil {
return ErrBadSubscription
}
s.mu.Lock()
conn := s.conn
s.mu.Unlock()
if conn == nil {
return ErrBadSubscription
}
if conn.IsDraining() {
return ErrConnectionDraining
}
return conn.unsubscribe(s, 0, false)
} | go | {
"resource": ""
} |
q24513 | checkDrained | train | func (nc *Conn) checkDrained(sub *Subscription) {
if nc == nil || sub == nil {
return
}
// This allows us to know that whatever we have in the client pending
// is correct and the server will not send additional information.
nc.Flush()
// Once we are here we just wait for Pending to reach 0 or
// any other s... | go | {
"resource": ""
} |
q24514 | AutoUnsubscribe | train | func (s *Subscription) AutoUnsubscribe(max int) error {
if s == nil {
return ErrBadSubscription
}
s.mu.Lock()
conn := s.conn
s.mu.Unlock()
if conn == nil {
return ErrBadSubscription
}
return conn.unsubscribe(s, max, false)
} | go | {
"resource": ""
} |
q24515 | NextMsg | train | func (s *Subscription) NextMsg(timeout time.Duration) (*Msg, error) {
if s == nil {
return nil, ErrBadSubscription
}
s.mu.Lock()
err := s.validateNextMsgState()
if err != nil {
s.mu.Unlock()
return nil, err
}
// snapshot
mch := s.mch
s.mu.Unlock()
var ok bool
var msg *Msg
// If something is availa... | go | {
"resource": ""
} |
q24516 | validateNextMsgState | train | func (s *Subscription) validateNextMsgState() error {
if s.connClosed {
return ErrConnectionClosed
}
if s.mch == nil {
if s.max > 0 && s.delivered >= s.max {
return ErrMaxMessages
} else if s.closed {
return ErrBadSubscription
}
}
if s.mcb != nil {
return ErrSyncSubRequired
}
if s.sc {
s.sc = f... | go | {
"resource": ""
} |
q24517 | processNextMsgDelivered | train | func (s *Subscription) processNextMsgDelivered(msg *Msg) error {
s.mu.Lock()
nc := s.conn
max := s.max
// Update some stats.
s.delivered++
delivered := s.delivered
if s.typ == SyncSubscription {
s.pMsgs--
s.pBytes -= len(msg.Data)
}
s.mu.Unlock()
if max > 0 {
if delivered > max {
return ErrMaxMessa... | go | {
"resource": ""
} |
q24518 | Pending | train | func (s *Subscription) Pending() (int, int, error) {
if s == nil {
return -1, -1, ErrBadSubscription
}
s.mu.Lock()
defer s.mu.Unlock()
if s.conn == nil {
return -1, -1, ErrBadSubscription
}
if s.typ == ChanSubscription {
return -1, -1, ErrTypeSubscription
}
return s.pMsgs, s.pBytes, nil
} | go | {
"resource": ""
} |
q24519 | PendingLimits | train | func (s *Subscription) PendingLimits() (int, int, error) {
if s == nil {
return -1, -1, ErrBadSubscription
}
s.mu.Lock()
defer s.mu.Unlock()
if s.conn == nil {
return -1, -1, ErrBadSubscription
}
if s.typ == ChanSubscription {
return -1, -1, ErrTypeSubscription
}
return s.pMsgsLimit, s.pBytesLimit, nil
} | go | {
"resource": ""
} |
q24520 | sendPing | train | func (nc *Conn) sendPing(ch chan struct{}) {
nc.pongs = append(nc.pongs, ch)
nc.bw.WriteString(pingProto)
// Flush in place.
nc.bw.Flush()
} | go | {
"resource": ""
} |
q24521 | processPingTimer | train | func (nc *Conn) processPingTimer() {
nc.mu.Lock()
if nc.status != CONNECTED {
nc.mu.Unlock()
return
}
// Check for violation
nc.pout++
if nc.pout > nc.Opts.MaxPingsOut {
nc.mu.Unlock()
nc.processOpErr(ErrStaleConnection)
return
}
nc.sendPing(nil)
nc.ptmr.Reset(nc.Opts.PingInterval)
nc.mu.Unlock()... | go | {
"resource": ""
} |
q24522 | resendSubscriptions | train | func (nc *Conn) resendSubscriptions() {
// Since we are going to send protocols to the server, we don't want to
// be holding the subsMu lock (which is used in processMsg). So copy
// the subscriptions in a temporary array.
nc.subsMu.RLock()
subs := make([]*Subscription, 0, len(nc.subs))
for _, s := range nc.subs... | go | {
"resource": ""
} |
q24523 | clearPendingFlushCalls | train | func (nc *Conn) clearPendingFlushCalls() {
// Clear any queued pongs, e.g. pending flush calls.
for _, ch := range nc.pongs {
if ch != nil {
close(ch)
}
}
nc.pongs = nil
} | go | {
"resource": ""
} |
q24524 | clearPendingRequestCalls | train | func (nc *Conn) clearPendingRequestCalls() {
if nc.respMap == nil {
return
}
for key, ch := range nc.respMap {
if ch != nil {
close(ch)
delete(nc.respMap, key)
}
}
} | go | {
"resource": ""
} |
q24525 | close | train | func (nc *Conn) close(status Status, doCBs bool) {
nc.mu.Lock()
if nc.isClosed() {
nc.status = status
nc.mu.Unlock()
return
}
nc.status = CLOSED
// Kick the Go routines so they fall out.
nc.kickFlusher()
nc.mu.Unlock()
nc.mu.Lock()
// Clear any queued pongs, e.g. pending flush calls.
nc.clearPendingF... | go | {
"resource": ""
} |
q24526 | IsClosed | train | func (nc *Conn) IsClosed() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.isClosed()
} | go | {
"resource": ""
} |
q24527 | IsReconnecting | train | func (nc *Conn) IsReconnecting() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.isReconnecting()
} | go | {
"resource": ""
} |
q24528 | IsConnected | train | func (nc *Conn) IsConnected() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.isConnected()
} | go | {
"resource": ""
} |
q24529 | drainConnection | train | func (nc *Conn) drainConnection() {
// Snapshot subs list.
nc.mu.Lock()
subs := make([]*Subscription, 0, len(nc.subs))
for _, s := range nc.subs {
subs = append(subs, s)
}
errCB := nc.Opts.AsyncErrorCB
drainWait := nc.Opts.DrainTimeout
nc.mu.Unlock()
// for pushing errors with context.
pushErr := func(err ... | go | {
"resource": ""
} |
q24530 | IsDraining | train | func (nc *Conn) IsDraining() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.isDraining()
} | go | {
"resource": ""
} |
q24531 | getServers | train | func (nc *Conn) getServers(implicitOnly bool) []string {
poolSize := len(nc.srvPool)
var servers = make([]string, 0)
for i := 0; i < poolSize; i++ {
if implicitOnly && !nc.srvPool[i].isImplicit {
continue
}
url := nc.srvPool[i].url
servers = append(servers, fmt.Sprintf("%s://%s", url.Scheme, url.Host))
}... | go | {
"resource": ""
} |
q24532 | Servers | train | func (nc *Conn) Servers() []string {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.getServers(false)
} | go | {
"resource": ""
} |
q24533 | DiscoveredServers | train | func (nc *Conn) DiscoveredServers() []string {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.getServers(true)
} | go | {
"resource": ""
} |
q24534 | Status | train | func (nc *Conn) Status() Status {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.status
} | go | {
"resource": ""
} |
q24535 | isDraining | train | func (nc *Conn) isDraining() bool {
return nc.status == DRAINING_SUBS || nc.status == DRAINING_PUBS
} | go | {
"resource": ""
} |
q24536 | Stats | train | func (nc *Conn) Stats() Statistics {
// Stats are updated either under connection's mu or subsMu mutexes.
// Lock both to safely get them.
nc.mu.Lock()
nc.subsMu.RLock()
stats := Statistics{
InMsgs: nc.InMsgs,
InBytes: nc.InBytes,
OutMsgs: nc.OutMsgs,
OutBytes: nc.OutBytes,
Reconnects: nc.Rec... | go | {
"resource": ""
} |
q24537 | MaxPayload | train | func (nc *Conn) MaxPayload() int64 {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.info.MaxPayload
} | go | {
"resource": ""
} |
q24538 | AuthRequired | train | func (nc *Conn) AuthRequired() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.info.AuthRequired
} | go | {
"resource": ""
} |
q24539 | TLSRequired | train | func (nc *Conn) TLSRequired() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.info.TLSRequired
} | go | {
"resource": ""
} |
q24540 | GetClientID | train | func (nc *Conn) GetClientID() (uint64, error) {
nc.mu.RLock()
defer nc.mu.RUnlock()
if nc.isClosed() {
return 0, ErrConnectionClosed
}
if nc.info.CID == 0 {
return 0, ErrClientIDNotSupported
}
return nc.info.CID, nil
} | go | {
"resource": ""
} |
q24541 | NkeyOptionFromSeed | train | func NkeyOptionFromSeed(seedFile string) (Option, error) {
kp, err := nkeyPairFromSeedFile(seedFile)
if err != nil {
return nil, err
}
// Wipe our key on exit.
defer kp.Wipe()
pub, err := kp.PublicKey()
if err != nil {
return nil, err
}
if !nkeys.IsValidPublicUserKey(pub) {
return nil, fmt.Errorf("nats:... | go | {
"resource": ""
} |
q24542 | sigHandler | train | func sigHandler(nonce []byte, seedFile string) ([]byte, error) {
kp, err := nkeyPairFromSeedFile(seedFile)
if err != nil {
return nil, err
}
// Wipe our key on exit.
defer kp.Wipe()
sig, _ := kp.Sign(nonce)
return sig, nil
} | go | {
"resource": ""
} |
q24543 | CloneTLSConfig | train | func CloneTLSConfig(c *tls.Config) *tls.Config {
if c == nil {
return &tls.Config{}
}
return c.Clone()
} | go | {
"resource": ""
} |
q24544 | RequestWithContext | train | func (nc *Conn) RequestWithContext(ctx context.Context, subj string, data []byte) (*Msg, error) {
if ctx == nil {
return nil, ErrInvalidContext
}
if nc == nil {
return nil, ErrInvalidConnection
}
// Check whether the context is done already before making
// the request.
if ctx.Err() != nil {
return nil, ct... | go | {
"resource": ""
} |
q24545 | oldRequestWithContext | train | func (nc *Conn) oldRequestWithContext(ctx context.Context, subj string, data []byte) (*Msg, error) {
inbox := NewInbox()
ch := make(chan *Msg, RequestChanLen)
s, err := nc.subscribe(inbox, _EMPTY_, nil, ch, true)
if err != nil {
return nil, err
}
s.AutoUnsubscribe(1)
defer s.Unsubscribe()
err = nc.PublishRe... | go | {
"resource": ""
} |
q24546 | NextMsgWithContext | train | func (s *Subscription) NextMsgWithContext(ctx context.Context) (*Msg, error) {
if ctx == nil {
return nil, ErrInvalidContext
}
if s == nil {
return nil, ErrBadSubscription
}
if ctx.Err() != nil {
return nil, ctx.Err()
}
s.mu.Lock()
err := s.validateNextMsgState()
if err != nil {
s.mu.Unlock()
return... | go | {
"resource": ""
} |
q24547 | RequestWithContext | train | func (c *EncodedConn) RequestWithContext(ctx context.Context, subject string, v interface{}, vPtr interface{}) error {
if ctx == nil {
return ErrInvalidContext
}
b, err := c.Enc.Encode(subject, v)
if err != nil {
return err
}
m, err := c.Conn.RequestWithContext(ctx, subject, b)
if err != nil {
return err
... | go | {
"resource": ""
} |
q24548 | BindSendChan | train | func (c *EncodedConn) BindSendChan(subject string, channel interface{}) error {
chVal := reflect.ValueOf(channel)
if chVal.Kind() != reflect.Chan {
return ErrChanArg
}
go chPublish(c, chVal, subject)
return nil
} | go | {
"resource": ""
} |
q24549 | chPublish | train | func chPublish(c *EncodedConn, chVal reflect.Value, subject string) {
for {
val, ok := chVal.Recv()
if !ok {
// Channel has most likely been closed.
return
}
if e := c.Publish(subject, val.Interface()); e != nil {
// Do this under lock.
c.Conn.mu.Lock()
defer c.Conn.mu.Unlock()
if c.Conn.Opt... | go | {
"resource": ""
} |
q24550 | BindRecvChan | train | func (c *EncodedConn) BindRecvChan(subject string, channel interface{}) (*Subscription, error) {
return c.bindRecvChan(subject, _EMPTY_, channel)
} | go | {
"resource": ""
} |
q24551 | BindRecvQueueChan | train | func (c *EncodedConn) BindRecvQueueChan(subject, queue string, channel interface{}) (*Subscription, error) {
return c.bindRecvChan(subject, queue, channel)
} | go | {
"resource": ""
} |
q24552 | bindRecvChan | train | func (c *EncodedConn) bindRecvChan(subject, queue string, channel interface{}) (*Subscription, error) {
chVal := reflect.ValueOf(channel)
if chVal.Kind() != reflect.Chan {
return nil, ErrChanArg
}
argType := chVal.Type().Elem()
cb := func(m *Msg) {
var oPtr reflect.Value
if argType.Kind() != reflect.Ptr {
... | go | {
"resource": ""
} |
q24553 | lookupGeo | train | func lookupGeo() string {
c := &http.Client{Timeout: 2 * time.Second}
resp, err := c.Get("https://ipinfo.io")
if err != nil || resp == nil {
log.Fatalf("Could not retrive geo location data: %v", err)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
g := geo{}
if err := json.Unmarshal(body, &g); ... | go | {
"resource": ""
} |
q24554 | CSV | train | func (bm *Benchmark) CSV() string {
var buffer bytes.Buffer
writer := csv.NewWriter(&buffer)
headers := []string{"#RunID", "ClientID", "MsgCount", "MsgBytes", "MsgsPerSec", "BytesPerSec", "DurationSecs"}
if err := writer.Write(headers); err != nil {
log.Fatalf("Error while serializing headers %q: %v", headers, er... | go | {
"resource": ""
} |
q24555 | NewSample | train | func NewSample(jobCount int, msgSize int, start, end time.Time, nc *nats.Conn) *Sample {
s := Sample{JobMsgCnt: jobCount, Start: start, End: end}
s.MsgBytes = uint64(msgSize * jobCount)
s.MsgCnt = nc.OutMsgs + nc.InMsgs
s.IOBytes = nc.OutBytes + nc.InBytes
return &s
} | go | {
"resource": ""
} |
q24556 | Throughput | train | func (s *Sample) Throughput() float64 {
return float64(s.MsgBytes) / s.Duration().Seconds()
} | go | {
"resource": ""
} |
q24557 | Rate | train | func (s *Sample) Rate() int64 {
return int64(float64(s.JobMsgCnt) / s.Duration().Seconds())
} | go | {
"resource": ""
} |
q24558 | Duration | train | func (s *Sample) Duration() time.Duration {
return s.End.Sub(s.Start)
} | go | {
"resource": ""
} |
q24559 | MinRate | train | func (sg *SampleGroup) MinRate() int64 {
m := int64(0)
for i, s := range sg.Samples {
if i == 0 {
m = s.Rate()
}
m = min(m, s.Rate())
}
return m
} | go | {
"resource": ""
} |
q24560 | MaxRate | train | func (sg *SampleGroup) MaxRate() int64 {
m := int64(0)
for i, s := range sg.Samples {
if i == 0 {
m = s.Rate()
}
m = max(m, s.Rate())
}
return m
} | go | {
"resource": ""
} |
q24561 | AvgRate | train | func (sg *SampleGroup) AvgRate() int64 {
sum := uint64(0)
for _, s := range sg.Samples {
sum += uint64(s.Rate())
}
return int64(sum / uint64(len(sg.Samples)))
} | go | {
"resource": ""
} |
q24562 | StdDev | train | func (sg *SampleGroup) StdDev() float64 {
avg := float64(sg.AvgRate())
sum := float64(0)
for _, c := range sg.Samples {
sum += math.Pow(float64(c.Rate())-avg, 2)
}
variance := sum / float64(len(sg.Samples))
return math.Sqrt(variance)
} | go | {
"resource": ""
} |
q24563 | AddSample | train | func (sg *SampleGroup) AddSample(e *Sample) {
sg.Samples = append(sg.Samples, e)
if len(sg.Samples) == 1 {
sg.Start = e.Start
sg.End = e.End
}
sg.IOBytes += e.IOBytes
sg.JobMsgCnt += e.JobMsgCnt
sg.MsgCnt += e.MsgCnt
sg.MsgBytes += e.MsgBytes
if e.Start.Before(sg.Start) {
sg.Start = e.Start
}
if e.En... | go | {
"resource": ""
} |
q24564 | Report | train | func (bm *Benchmark) Report() string {
var buffer bytes.Buffer
indent := ""
if !bm.Pubs.HasSamples() && !bm.Subs.HasSamples() {
return "No publisher or subscribers. Nothing to report."
}
if bm.Pubs.HasSamples() && bm.Subs.HasSamples() {
buffer.WriteString(fmt.Sprintf("%s Pub/Sub stats: %s\n", bm.Name, bm))
... | go | {
"resource": ""
} |
q24565 | HumanBytes | train | func HumanBytes(bytes float64, si bool) string {
var base = 1024
pre := []string{"K", "M", "G", "T", "P", "E"}
var post = "B"
if si {
base = 1000
pre = []string{"k", "M", "G", "T", "P", "E"}
post = "iB"
}
if bytes < float64(base) {
return fmt.Sprintf("%.2f B", bytes)
}
exp := int(math.Log(bytes) / math.... | go | {
"resource": ""
} |
q24566 | MsgsPerClient | train | func MsgsPerClient(numMsgs, numClients int) []int {
var counts []int
if numClients == 0 || numMsgs == 0 {
return counts
}
counts = make([]int, numClients)
mc := numMsgs / numClients
for i := 0; i < numClients; i++ {
counts[i] = mc
}
extra := numMsgs % numClients
for i := 0; i < extra; i++ {
counts[i]++
... | go | {
"resource": ""
} |
q24567 | Get | train | func (tp *timerPool) Get(d time.Duration) *time.Timer {
if t, _ := tp.p.Get().(*time.Timer); t != nil {
t.Reset(d)
return t
}
return time.NewTimer(d)
} | go | {
"resource": ""
} |
q24568 | NewBlacklistedImports | train | func NewBlacklistedImports(id string, conf gosec.Config, blacklist map[string]string) (gosec.Rule, []ast.Node) {
return &blacklistedImport{
MetaData: gosec.MetaData{
ID: id,
Severity: gosec.Medium,
Confidence: gosec.High,
},
Blacklisted: blacklist,
}, []ast.Node{(*ast.ImportSpec)(nil)}
} | go | {
"resource": ""
} |
q24569 | NewBlacklistedImportRC4 | train | func NewBlacklistedImportRC4(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
return NewBlacklistedImports(id, conf, map[string]string{
"crypto/rc4": "Blacklisted import crypto/rc4: weak cryptographic primitive",
})
} | go | {
"resource": ""
} |
q24570 | NewHardcodedCredentials | train | func NewHardcodedCredentials(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
pattern := `(?i)passwd|pass|password|pwd|secret|token`
entropyThreshold := 80.0
perCharThreshold := 3.0
ignoreEntropy := false
var truncateString = 16
if val, ok := conf["G101"]; ok {
conf := val.(map[string]string)
if confi... | go | {
"resource": ""
} |
q24571 | NewBindsToAllNetworkInterfaces | train | func NewBindsToAllNetworkInterfaces(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
calls := gosec.NewCallList()
calls.Add("net", "Listen")
calls.Add("crypto/tls", "Listen")
return &bindsToAllNetworkInterfaces{
calls: calls,
pattern: regexp.MustCompile(`^(0.0.0.0|:).*$`),
MetaData: gosec.MetaData{
... | go | {
"resource": ""
} |
q24572 | NewFilePerms | train | func NewFilePerms(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
mode := getConfiguredMode(conf, "G302", 0600)
return &filePermissions{
mode: mode,
pkg: "os",
calls: []string{"OpenFile", "Chmod"},
MetaData: gosec.MetaData{
ID: id,
Severity: gosec.Medium,
Confidence: gosec.High,... | go | {
"resource": ""
} |
q24573 | NewWeakKeyStrength | train | func NewWeakKeyStrength(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
calls := gosec.NewCallList()
calls.Add("crypto/rsa", "GenerateKey")
bits := 2048
return &weakKeyStrength{
calls: calls,
bits: bits,
MetaData: gosec.MetaData{
ID: id,
Severity: gosec.Medium,
Confidence: gosec.H... | go | {
"resource": ""
} |
q24574 | NewSubproc | train | func NewSubproc(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
rule := &subprocess{gosec.MetaData{ID: id}, gosec.NewCallList()}
rule.Add("os/exec", "Command")
rule.Add("os/exec", "CommandContext")
rule.Add("syscall", "Exec")
return rule, []ast.Node{(*ast.CallExpr)(nil)}
} | go | {
"resource": ""
} |
q24575 | Match | train | func (a *archive) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) {
if node := a.calls.ContainsCallExpr(n, c, false); node != nil {
for _, arg := range node.Args {
var argType types.Type
if selector, ok := arg.(*ast.SelectorExpr); ok {
argType = c.Info.TypeOf(selector.X)
} else if ident, ok :=... | go | {
"resource": ""
} |
q24576 | NewArchive | train | func NewArchive(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
calls := gosec.NewCallList()
calls.Add("path/filepath", "Join")
return &archive{
calls: calls,
argType: "*archive/zip.File",
MetaData: gosec.MetaData{
ID: id,
Severity: gosec.Medium,
Confidence: gosec.High,
What: ... | go | {
"resource": ""
} |
q24577 | AddAll | train | func (c CallList) AddAll(selector string, idents ...string) {
for _, ident := range idents {
c.Add(selector, ident)
}
} | go | {
"resource": ""
} |
q24578 | Add | train | func (c CallList) Add(selector, ident string) {
if _, ok := c[selector]; !ok {
c[selector] = make(set)
}
c[selector][ident] = true
} | go | {
"resource": ""
} |
q24579 | MatchCompLit | train | func MatchCompLit(n ast.Node, ctx *Context, required string) *ast.CompositeLit {
if complit, ok := n.(*ast.CompositeLit); ok {
typeOf := ctx.Info.TypeOf(complit)
if typeOf.String() == required {
return complit
}
}
return nil
} | go | {
"resource": ""
} |
q24580 | GetInt | train | func GetInt(n ast.Node) (int64, error) {
if node, ok := n.(*ast.BasicLit); ok && node.Kind == token.INT {
return strconv.ParseInt(node.Value, 0, 64)
}
return 0, fmt.Errorf("Unexpected AST node type: %T", n)
} | go | {
"resource": ""
} |
q24581 | GetFloat | train | func GetFloat(n ast.Node) (float64, error) {
if node, ok := n.(*ast.BasicLit); ok && node.Kind == token.FLOAT {
return strconv.ParseFloat(node.Value, 64)
}
return 0.0, fmt.Errorf("Unexpected AST node type: %T", n)
} | go | {
"resource": ""
} |
q24582 | GetChar | train | func GetChar(n ast.Node) (byte, error) {
if node, ok := n.(*ast.BasicLit); ok && node.Kind == token.CHAR {
return node.Value[0], nil
}
return 0, fmt.Errorf("Unexpected AST node type: %T", n)
} | go | {
"resource": ""
} |
q24583 | GetString | train | func GetString(n ast.Node) (string, error) {
if node, ok := n.(*ast.BasicLit); ok && node.Kind == token.STRING {
return strconv.Unquote(node.Value)
}
return "", fmt.Errorf("Unexpected AST node type: %T", n)
} | go | {
"resource": ""
} |
q24584 | GetCallObject | train | func GetCallObject(n ast.Node, ctx *Context) (*ast.CallExpr, types.Object) {
switch node := n.(type) {
case *ast.CallExpr:
switch fn := node.Fun.(type) {
case *ast.Ident:
return node, ctx.Info.Uses[fn]
case *ast.SelectorExpr:
return node, ctx.Info.Uses[fn.Sel]
}
}
return nil, nil
} | go | {
"resource": ""
} |
q24585 | GetCallInfo | train | func GetCallInfo(n ast.Node, ctx *Context) (string, string, error) {
switch node := n.(type) {
case *ast.CallExpr:
switch fn := node.Fun.(type) {
case *ast.SelectorExpr:
switch expr := fn.X.(type) {
case *ast.Ident:
if expr.Obj != nil && expr.Obj.Kind == ast.Var {
t := ctx.Info.TypeOf(expr)
if... | go | {
"resource": ""
} |
q24586 | GetCallStringArgsValues | train | func GetCallStringArgsValues(n ast.Node, ctx *Context) []string {
values := []string{}
switch node := n.(type) {
case *ast.CallExpr:
for _, arg := range node.Args {
switch param := arg.(type) {
case *ast.BasicLit:
value, err := GetString(param)
if err == nil {
values = append(values, value)
... | go | {
"resource": ""
} |
q24587 | GetIdentStringValues | train | func GetIdentStringValues(ident *ast.Ident) []string {
values := []string{}
obj := ident.Obj
if obj != nil {
switch decl := obj.Decl.(type) {
case *ast.ValueSpec:
for _, v := range decl.Values {
value, err := GetString(v)
if err == nil {
values = append(values, value)
}
}
case *ast.Assig... | go | {
"resource": ""
} |
q24588 | GetImportedName | train | func GetImportedName(path string, ctx *Context) (string, bool) {
importName, imported := ctx.Imports.Imported[path]
if !imported {
return "", false
}
if _, initonly := ctx.Imports.InitOnly[path]; initonly {
return "", false
}
if alias, ok := ctx.Imports.Aliased[path]; ok {
importName = alias
}
return im... | go | {
"resource": ""
} |
q24589 | GetImportPath | train | func GetImportPath(name string, ctx *Context) (string, bool) {
for path := range ctx.Imports.Imported {
if imported, ok := GetImportedName(path, ctx); ok && imported == name {
return path, true
}
}
return "", false
} | go | {
"resource": ""
} |
q24590 | GetLocation | train | func GetLocation(n ast.Node, ctx *Context) (string, int) {
fobj := ctx.FileSet.File(n.Pos())
return fobj.Name(), fobj.Line(n.Pos())
} | go | {
"resource": ""
} |
q24591 | Gopath | train | func Gopath() []string {
defaultGoPath := runtime.GOROOT()
if u, err := user.Current(); err == nil {
defaultGoPath = filepath.Join(u.HomeDir, "go")
}
path := Getenv("GOPATH", defaultGoPath)
paths := strings.Split(path, string(os.PathListSeparator))
for idx, path := range paths {
if abs, err := filepath.Abs(pa... | go | {
"resource": ""
} |
q24592 | Getenv | train | func Getenv(key, userDefault string) string {
if val := os.Getenv(key); val != "" {
return val
}
return userDefault
} | go | {
"resource": ""
} |
q24593 | GetPkgRelativePath | train | func GetPkgRelativePath(path string) (string, error) {
abspath, err := filepath.Abs(path)
if err != nil {
abspath = path
}
if strings.HasSuffix(abspath, ".go") {
abspath = filepath.Dir(abspath)
}
for _, base := range Gopath() {
projectRoot := filepath.FromSlash(fmt.Sprintf("%s/src/", base))
if strings.Has... | go | {
"resource": ""
} |
q24594 | GetPkgAbsPath | train | func GetPkgAbsPath(pkgPath string) (string, error) {
absPath, err := filepath.Abs(pkgPath)
if err != nil {
return "", err
}
if _, err := os.Stat(absPath); os.IsNotExist(err) {
return "", errors.New("no project absolute path found")
}
return absPath, nil
} | go | {
"resource": ""
} |
q24595 | ConcatString | train | func ConcatString(n *ast.BinaryExpr) (string, bool) {
var s string
// sub expressions are found in X object, Y object is always last BasicLit
if rightOperand, ok := n.Y.(*ast.BasicLit); ok {
if str, err := GetString(rightOperand); err == nil {
s = str + s
}
} else {
return "", false
}
if leftOperand, ok ... | go | {
"resource": ""
} |
q24596 | FindVarIdentities | train | func FindVarIdentities(n *ast.BinaryExpr, c *Context) ([]*ast.Ident, bool) {
identities := []*ast.Ident{}
// sub expressions are found in X object, Y object is always the last term
if rightOperand, ok := n.Y.(*ast.Ident); ok {
obj := c.Info.ObjectOf(rightOperand)
if _, ok := obj.(*types.Var); ok && !TryResolve(r... | go | {
"resource": ""
} |
q24597 | PackagePaths | train | func PackagePaths(root string, exclude *regexp.Regexp) ([]string, error) {
if strings.HasSuffix(root, "...") {
root = root[0 : len(root)-3]
} else {
return []string{root}, nil
}
paths := map[string]bool{}
err := filepath.Walk(root, func(path string, f os.FileInfo, err error) error {
if filepath.Ext(path) == ... | go | {
"resource": ""
} |
q24598 | NewModernTLSCheck | train | func NewModernTLSCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
return &insecureConfigTLS{
MetaData: gosec.MetaData{ID: id},
requiredType: "crypto/tls.Config",
MinVersion: 0x0303,
MaxVersion: 0x0303,
goodCiphers: []string{
"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
"TLS_ECDHE_RS... | go | {
"resource": ""
} |
q24599 | Register | train | func (r RuleSet) Register(rule Rule, nodes ...ast.Node) {
for _, n := range nodes {
t := reflect.TypeOf(n)
if rules, ok := r[t]; ok {
r[t] = append(rules, rule)
} else {
r[t] = []Rule{rule}
}
}
} | go | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.