_id stringlengths 2 7 | title stringlengths 1 118 | partition stringclasses 3
values | text stringlengths 52 85.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q5500 | SetLogger | train | func SetLogger(logDir string, quiet, debug, logJSON bool) {
stderrHundler := logger.StderrHandler
logFormat := logger.LogfmtFormat()
if logJSON {
logFormat = logger.JsonFormatEx(false, true)
stderrHundler = logger.StreamHandler(os.Stderr, logFormat)
}
lvlHundler := logger.LvlFilterHandler(logger.LvlInfo, stde... | go | {
"resource": ""
} |
q5501 | Fatalf | train | func Fatalf(format string, args ...interface{}) {
logger.Crit(fmt.Sprintf(format, args...))
} | go | {
"resource": ""
} |
q5502 | Start | train | func Start(logDir string, driver db.DB) error {
e := echo.New()
e.Debug = config.Conf.Debug
// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
// setup access logger
logPath := filepath.Join(logDir, "access.log")
if _, err := os.Stat(logPath); os.IsNotExist(err) {
if _, err := os.Create(lo... | go | {
"resource": ""
} |
q5503 | NewRedis | train | func NewRedis(dbType, dbpath string, debugSQL bool) (driver *RedisDriver, locked bool, err error) {
driver = &RedisDriver{
name: dbType,
}
log.Debugf("Opening DB (%s).", driver.Name())
if err = driver.OpenDB(dbType, dbpath, debugSQL); err != nil {
return
}
return
} | go | {
"resource": ""
} |
q5504 | InsertJvn | train | func (r *RedisDriver) InsertJvn(cves []models.CveDetail) error {
log.Infof("Inserting fetched CVEs...")
var err error
var refreshedJvns []string
bar := pb.New(len(cves))
if c.Conf.Quiet {
bar.SetWriter(ioutil.Discard)
} else {
bar.SetWriter(os.Stderr)
}
bar.Start()
for chunked := range chunkSlice(cves, 10... | go | {
"resource": ""
} |
q5505 | GetFetchedFeedMeta | train | func (r *RedisDriver) GetFetchedFeedMeta(url string) (*models.FeedMeta, error) {
var result *redis.StringStringMapCmd
if result = r.conn.HGetAll(hashKeyPrefix + "Meta"); result.Err() != nil {
return nil, result.Err()
}
meta := &models.FeedMeta{}
if s, ok := result.Val()[url]; ok {
if err := json.Unmarshal([]by... | go | {
"resource": ""
} |
q5506 | UpsertFeedHash | train | func (r *RedisDriver) UpsertFeedHash(m models.FeedMeta) error {
jn, err := json.Marshal(m)
if err != nil {
return fmt.Errorf("Failed to marshal json. err: %s", err)
}
var pipe redis.Pipeliner
pipe = r.conn.Pipeline()
if result := pipe.HSet(hashKeyPrefix+"Meta", m.URL, jn); result.Err() != nil {
return fmt.Er... | go | {
"resource": ""
} |
q5507 | UpToDate | train | func (f FeedMeta) UpToDate() bool {
return !f.Newly() && f.Hash == f.LatestHash
} | go | {
"resource": ""
} |
q5508 | OutDated | train | func (f FeedMeta) OutDated() bool {
return !f.Newly() && f.Hash != f.LatestHash
} | go | {
"resource": ""
} |
q5509 | StatusForStdout | train | func (f FeedMeta) StatusForStdout() string {
if f.Newly() {
return "Newly"
} else if f.OutDated() {
red := color.New(color.FgRed, color.Bold).SprintFunc()
return red("Out-Dated")
} else if f.UpToDate() {
return color.GreenString("Up-to-Date")
}
return "Unknown"
} | go | {
"resource": ""
} |
q5510 | Year | train | func (f FeedMeta) Year() (year string, xml bool, err error) {
switch f.source() {
case nvdxml:
return strings.TrimSuffix(
strings.Split(f.URL, "nvdcve-2.0-")[1], ".xml.gz"), true, nil
case nvdjson:
return strings.TrimSuffix(
strings.Split(f.URL, "nvdcve-1.0-")[1], ".json.gz"), false, nil
case jvn:
if st... | go | {
"resource": ""
} |
q5511 | ToTableWriterRow | train | func (f FeedMeta) ToTableWriterRow() []string {
y, _, _ := f.Year()
fetched, latest := f.modifiedTimesToStrs()
return []string{
f.color(f.source()),
f.color(y),
f.StatusForStdout(),
f.color(fetched),
f.color(latest),
}
} | go | {
"resource": ""
} |
q5512 | FetchConvert | train | func FetchConvert(metas []models.FeedMeta) (cves []models.CveDetail, err error) {
reqs := []fetcher.FetchRequest{}
for _, meta := range metas {
reqs = append(reqs, fetcher.FetchRequest{
URL: meta.URL,
GZIP: true,
})
}
results, err := fetcher.FetchFeedFiles(reqs)
if err != nil {
return nil,
fmt.Err... | go | {
"resource": ""
} |
q5513 | Register | train | func (c *Collection) Register(fns ...func(DB) error) error {
return c.register(false, fns...)
} | go | {
"resource": ""
} |
q5514 | RegisterTx | train | func (c *Collection) RegisterTx(fns ...func(DB) error) error {
return c.register(true, fns...)
} | go | {
"resource": ""
} |
q5515 | DiscoverSQLMigrations | train | func (c *Collection) DiscoverSQLMigrations(dir string) error {
dir, err := filepath.Abs(dir)
if err != nil {
return err
}
if c.isVisitedDir(dir) {
return nil
}
if _, err := os.Stat(dir); os.IsNotExist(err) {
return nil
}
var ms []*Migration
newMigration := func(version int64) *Migration {
for i := r... | go | {
"resource": ""
} |
q5516 | Format | train | func (r Result) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
if s.Flag('+') {
var buf bytes.Buffer
fmt.Fprintf(&buf, "DNS lookup: %4d ms\n",
int(r.DNSLookup/time.Millisecond))
fmt.Fprintf(&buf, "TCP connection: %4d ms\n",
int(r.TCPConnection/time.Millisecond))
fmt.Fprintf(&... | go | {
"resource": ""
} |
q5517 | WithHTTPStat | train | func WithHTTPStat(ctx context.Context, r *Result) context.Context {
return withClientTrace(ctx, r)
} | go | {
"resource": ""
} |
q5518 | run | train | func (w *worker) run() {
defer func() {
w.logFunc(LogInfo, "worker done.")
w.wg.Done()
}()
// Enter loop to process URLs until stop signal is received
for {
var idleChan <-chan time.Time
w.logFunc(LogInfo, "waiting for pop...")
// Initialize the idle timeout channel, if required
if w.opts.WorkerIdleT... | go | {
"resource": ""
} |
q5519 | isAllowedPerRobotsPolicies | train | func (w *worker) isAllowedPerRobotsPolicies(u *url.URL) bool {
if w.robotsGroup != nil {
// Is this URL allowed per robots.txt policy?
ok := w.robotsGroup.Test(u.Path)
if !ok {
w.logFunc(LogIgnored, "ignored on robots.txt policy: %s", u.String())
}
return ok
}
// No robots.txt = everything is allowed
... | go | {
"resource": ""
} |
q5520 | requestURL | train | func (w *worker) requestURL(ctx *URLContext, headRequest bool) {
if res, ok := w.fetchURL(ctx, w.opts.UserAgent, headRequest); ok {
var harvested interface{}
var visited bool
// Close the body on function end
defer res.Body.Close()
// Any 2xx status code is good to go
if res.StatusCode >= 200 && res.Stat... | go | {
"resource": ""
} |
q5521 | requestRobotsTxt | train | func (w *worker) requestRobotsTxt(ctx *URLContext) {
// Ask if it should be fetched
if robData, reqRob := w.opts.Extender.RequestRobots(ctx, w.opts.RobotUserAgent); !reqRob {
w.logFunc(LogInfo, "using robots.txt from cache")
w.robotsGroup = w.getRobotsTxtGroup(ctx, robData, nil)
} else if res, ok := w.fetchURL(... | go | {
"resource": ""
} |
q5522 | getRobotsTxtGroup | train | func (w *worker) getRobotsTxtGroup(ctx *URLContext, b []byte, res *http.Response) (g *robotstxt.Group) {
var data *robotstxt.RobotsData
var e error
if res != nil {
var buf bytes.Buffer
io.Copy(&buf, res.Body)
res.Body = ioutil.NopCloser(bytes.NewReader(buf.Bytes()))
data, e = robotstxt.FromResponse(res)
/... | go | {
"resource": ""
} |
q5523 | setCrawlDelay | train | func (w *worker) setCrawlDelay() {
var robDelay time.Duration
if w.robotsGroup != nil {
robDelay = w.robotsGroup.CrawlDelay
}
w.lastCrawlDelay = w.opts.Extender.ComputeDelay(w.host,
&DelayInfo{
w.opts.CrawlDelay,
robDelay,
w.lastCrawlDelay,
},
w.lastFetch)
w.logFunc(LogInfo, "using crawl-delay: %... | go | {
"resource": ""
} |
q5524 | fetchURL | train | func (w *worker) fetchURL(ctx *URLContext, agent string, headRequest bool) (res *http.Response, ok bool) {
var e error
var silent bool
for {
// Wait for crawl delay, if one is pending.
w.logFunc(LogTrace, "waiting for crawl delay")
if w.wait != nil {
<-w.wait
w.wait = nil
}
// Compute the next dela... | go | {
"resource": ""
} |
q5525 | sendResponse | train | func (w *worker) sendResponse(ctx *URLContext, visited bool, harvested interface{}, idleDeath bool) {
// Push harvested urls back to crawler, even if empty (uses the channel communication
// to decrement reference count of pending URLs)
if ctx == nil || !isRobotsURL(ctx.url) {
// If a stop signal has been received... | go | {
"resource": ""
} |
q5526 | visitURL | train | func (w *worker) visitURL(ctx *URLContext, res *http.Response) interface{} {
var doc *goquery.Document
var harvested interface{}
var doLinks bool
// Load a goquery document and call the visitor function
if bd, e := ioutil.ReadAll(res.Body); e != nil {
w.opts.Extender.Error(newCrawlError(ctx, e, CekReadBody))
... | go | {
"resource": ""
} |
q5527 | processLinks | train | func (w *worker) processLinks(doc *goquery.Document) (result []*url.URL) {
baseURL, _ := doc.Find("base[href]").Attr("href")
urls := doc.Find("a[href]").Map(func(_ int, s *goquery.Selection) string {
val, _ := s.Attr("href")
if baseURL != "" {
val = handleBaseTag(doc.Url, baseURL, val)
}
return val
})
fo... | go | {
"resource": ""
} |
q5528 | Log | train | func (de *DefaultExtender) Log(logFlags LogFlags, msgLevel LogFlags, msg string) {
if logFlags&msgLevel == msgLevel {
log.Println(msg)
}
} | go | {
"resource": ""
} |
q5529 | ComputeDelay | train | func (de *DefaultExtender) ComputeDelay(host string, di *DelayInfo, lastFetch *FetchInfo) time.Duration {
if di.RobotsDelay > 0 {
return di.RobotsDelay
}
return di.OptsDelay
} | go | {
"resource": ""
} |
q5530 | Visit | train | func (de *DefaultExtender) Visit(ctx *URLContext, res *http.Response, doc *goquery.Document) (harvested interface{}, findLinks bool) {
return nil, true
} | go | {
"resource": ""
} |
q5531 | NewCrawlerWithOptions | train | func NewCrawlerWithOptions(opts *Options) *Crawler {
ret := new(Crawler)
ret.Options = opts
return ret
} | go | {
"resource": ""
} |
q5532 | init | train | func (c *Crawler) init(ctxs []*URLContext) {
// Initialize the internal hosts map
c.hosts = make(map[string]struct{}, len(ctxs))
for _, ctx := range ctxs {
// Add this normalized URL's host if it is not already there.
if _, ok := c.hosts[ctx.normalizedURL.Host]; !ok {
c.hosts[ctx.normalizedURL.Host] = struct{... | go | {
"resource": ""
} |
q5533 | setExtenderEnqueueChan | train | func (c *Crawler) setExtenderEnqueueChan() {
defer func() {
if err := recover(); err != nil {
// Panic can happen if the field exists on a pointer struct, but that
// pointer is nil.
c.logFunc(LogError, "cannot set the enqueue channel: %s", err)
}
}()
// Using reflection, check if the extender has a `E... | go | {
"resource": ""
} |
q5534 | launchWorker | train | func (c *Crawler) launchWorker(ctx *URLContext) *worker {
// Initialize index and channels
i := len(c.workers) + 1
pop := newPopChannel()
// Create the worker
w := &worker{
host: ctx.normalizedURL.Host,
index: i,
push: c.push,
pop: pop,
stop: c.stop,
enqueue: c.enqueue,
wg: c.wg,... | go | {
"resource": ""
} |
q5535 | isSameHost | train | func (c *Crawler) isSameHost(ctx *URLContext) bool {
// If there is a source URL, then just check if the new URL is from the same host
if ctx.normalizedSourceURL != nil {
return ctx.normalizedURL.Host == ctx.normalizedSourceURL.Host
}
// Otherwise, check if the URL is from one of the seed hosts
_, ok := c.hosts... | go | {
"resource": ""
} |
q5536 | enqueueUrls | train | func (c *Crawler) enqueueUrls(ctxs []*URLContext) (cnt int) {
for _, ctx := range ctxs {
var isVisited, enqueue bool
// Cannot directly enqueue a robots.txt URL, since it is managed as a special case
// in the worker (doesn't return a response to crawler).
if ctx.IsRobotsURL() {
continue
}
// Check if ... | go | {
"resource": ""
} |
q5537 | collectUrls | train | func (c *Crawler) collectUrls() error {
defer func() {
c.logFunc(LogInfo, "waiting for goroutines to complete...")
c.wg.Wait()
c.logFunc(LogInfo, "crawler done.")
}()
for {
// By checking this after each channel reception, there is a bug if the worker
// wants to reenqueue following an error or a redirect... | go | {
"resource": ""
} |
q5538 | Stop | train | func (c *Crawler) Stop() {
defer func() {
if err := recover(); err != nil {
c.logFunc(LogError, "error when manually stopping crawler: %s", err)
}
}()
// this channel may be closed already
close(c.stop)
} | go | {
"resource": ""
} |
q5539 | Error | train | func (ce CrawlError) Error() string {
if ce.Err != nil {
return ce.Err.Error()
}
return ce.msg
} | go | {
"resource": ""
} |
q5540 | newCrawlError | train | func newCrawlError(ctx *URLContext, e error, kind CrawlErrorKind) *CrawlError {
return &CrawlError{ctx, e, kind, ""}
} | go | {
"resource": ""
} |
q5541 | newCrawlErrorMessage | train | func newCrawlErrorMessage(ctx *URLContext, msg string, kind CrawlErrorKind) *CrawlError {
return &CrawlError{ctx, nil, kind, msg}
} | go | {
"resource": ""
} |
q5542 | cloneForRedirect | train | func (uc *URLContext) cloneForRedirect(dst *url.URL, normFlags purell.NormalizationFlags) *URLContext {
var src, normalizedSrc *url.URL
if uc.sourceURL != nil {
src = &url.URL{}
*src = *uc.sourceURL
}
if src == nil && uc.url != nil {
// if the current context doesn't have a source URL, use its URL as
// sou... | go | {
"resource": ""
} |
q5543 | NewOptions | train | func NewOptions(ext Extender) *Options {
// Use defaults except for Extender
return &Options{
DefaultUserAgent,
DefaultRobotUserAgent,
0,
DefaultEnqueueChanBuffer,
DefaultHostBufferFactor,
DefaultCrawlDelay,
DefaultIdleTTL,
true,
false,
DefaultNormalizationFlags,
LogError,
ext,
}
} | go | {
"resource": ""
} |
q5544 | toCamelInitCase | train | func toCamelInitCase(s string, initCase bool) string {
s = addWordBoundariesToNumbers(s)
s = strings.Trim(s, " ")
n := ""
capNext := initCase
for _, v := range s {
if v >= 'A' && v <= 'Z' {
n += string(v)
}
if v >= '0' && v <= '9' {
n += string(v)
}
if v >= 'a' && v <= 'z' {
if capNext {
n +... | go | {
"resource": ""
} |
q5545 | ToLowerCamel | train | func ToLowerCamel(s string) string {
if s == "" {
return s
}
if r := rune(s[0]); r >= 'A' && r <= 'Z' {
s = strings.ToLower(string(r)) + s[1:]
}
return toCamelInitCase(s, false)
} | go | {
"resource": ""
} |
q5546 | Call | train | func (s *Session) Call(name string, a ...interface{}) error {
return s.Command(name, a...).Run()
} | go | {
"resource": ""
} |
q5547 | UnmarshalJSON | train | func (s *Session) UnmarshalJSON(data interface{}) (err error) {
bufrw := bytes.NewBuffer(nil)
s.Stdout = bufrw
if err = s.Run(); err != nil {
return
}
return json.NewDecoder(bufrw).Decode(data)
} | go | {
"resource": ""
} |
q5548 | UnmarshalXML | train | func (s *Session) UnmarshalXML(data interface{}) (err error) {
bufrw := bytes.NewBuffer(nil)
s.Stdout = bufrw
if err = s.Run(); err != nil {
return
}
return xml.NewDecoder(bufrw).Decode(data)
} | go | {
"resource": ""
} |
q5549 | NewEncoder | train | func NewEncoder(w io.WriteSeeker, sampleRate, bitDepth, numChans, audioFormat int) *Encoder {
return &Encoder{
w: w,
SampleRate: sampleRate,
BitDepth: bitDepth,
NumChans: numChans,
WavAudioFormat: audioFormat,
}
} | go | {
"resource": ""
} |
q5550 | AddLE | train | func (e *Encoder) AddLE(src interface{}) error {
e.WrittenBytes += binary.Size(src)
return binary.Write(e.w, binary.LittleEndian, src)
} | go | {
"resource": ""
} |
q5551 | AddBE | train | func (e *Encoder) AddBE(src interface{}) error {
e.WrittenBytes += binary.Size(src)
return binary.Write(e.w, binary.BigEndian, src)
} | go | {
"resource": ""
} |
q5552 | WriteFrame | train | func (e *Encoder) WriteFrame(value interface{}) error {
if !e.wroteHeader {
e.writeHeader()
}
if !e.pcmChunkStarted {
// sound header
if err := e.AddLE(riff.DataFormatID); err != nil {
return fmt.Errorf("error encoding sound header %v", err)
}
e.pcmChunkStarted = true
// write a temporary chunksize
... | go | {
"resource": ""
} |
q5553 | DecodeCueChunk | train | func DecodeCueChunk(d *Decoder, ch *riff.Chunk) error {
if ch == nil {
return fmt.Errorf("can't decode a nil chunk")
}
if d == nil {
return fmt.Errorf("nil decoder")
}
if ch.ID == CIDCue {
// read the entire chunk in memory
buf := make([]byte, ch.Size)
var err error
if _, err = ch.Read(buf); err != nil... | go | {
"resource": ""
} |
q5554 | NewDecoder | train | func NewDecoder(r io.ReadSeeker) *Decoder {
return &Decoder{
r: r,
parser: riff.New(r),
}
} | go | {
"resource": ""
} |
q5555 | Seek | train | func (d *Decoder) Seek(offset int64, whence int) (int64, error) {
return d.r.Seek(offset, whence)
} | go | {
"resource": ""
} |
q5556 | Err | train | func (d *Decoder) Err() error {
if d.err == io.EOF {
return nil
}
return d.err
} | go | {
"resource": ""
} |
q5557 | EOF | train | func (d *Decoder) EOF() bool {
if d == nil || d.err == io.EOF {
return true
}
return false
} | go | {
"resource": ""
} |
q5558 | ReadMetadata | train | func (d *Decoder) ReadMetadata() {
if d.Metadata != nil {
return
}
d.ReadInfo()
if d.Err() != nil || d.Metadata != nil {
return
}
var (
chunk *riff.Chunk
err error
)
for err == nil {
chunk, err = d.parser.NextChunk()
if err != nil {
break
}
switch chunk.ID {
case CIDList:
if err = Dec... | go | {
"resource": ""
} |
q5559 | Duration | train | func (d *Decoder) Duration() (time.Duration, error) {
if d == nil || d.parser == nil {
return 0, errors.New("can't calculate the duration of a nil pointer")
}
return d.parser.Duration()
} | go | {
"resource": ""
} |
q5560 | readHeaders | train | func (d *Decoder) readHeaders() error {
if d == nil || d.NumChans > 0 {
return nil
}
id, size, err := d.parser.IDnSize()
if err != nil {
return err
}
d.parser.ID = id
if d.parser.ID != riff.RiffID {
return fmt.Errorf("%s - %s", d.parser.ID, riff.ErrFmtNotSupported)
}
d.parser.Size = size
if err := bina... | go | {
"resource": ""
} |
q5561 | sampleFloat64DecodeFunc | train | func sampleFloat64DecodeFunc(bitsPerSample int) (func([]byte) float64, error) {
bytesPerSample := bitsPerSample / 8
switch bytesPerSample {
case 1:
// 8bit values are unsigned
return func(s []byte) float64 {
return float64(uint8(s[0]))
}, nil
case 2:
return func(s []byte) float64 {
return float64(int(... | go | {
"resource": ""
} |
q5562 | Diff | train | func Diff(a, b interface{}) (desc []string) {
Pdiff((*sbuf)(&desc), a, b)
return desc
} | go | {
"resource": ""
} |
q5563 | Fdiff | train | func Fdiff(w io.Writer, a, b interface{}) {
Pdiff(&wprintfer{w}, a, b)
} | go | {
"resource": ""
} |
q5564 | Pdiff | train | func Pdiff(p Printfer, a, b interface{}) {
diffPrinter{w: p}.diff(reflect.ValueOf(a), reflect.ValueOf(b))
} | go | {
"resource": ""
} |
q5565 | Ldiff | train | func Ldiff(l Logfer, a, b interface{}) {
Pdiff(&logprintfer{l}, a, b)
} | go | {
"resource": ""
} |
q5566 | keyEqual | train | func keyEqual(av, bv reflect.Value) bool {
if !av.IsValid() && !bv.IsValid() {
return true
}
if !av.IsValid() || !bv.IsValid() || av.Type() != bv.Type() {
return false
}
switch kind := av.Kind(); kind {
case reflect.Bool:
a, b := av.Bool(), bv.Bool()
return a == b
case reflect.Int, reflect.Int8, reflect.... | go | {
"resource": ""
} |
q5567 | TokenErrorf | train | func TokenErrorf(token *scanner.Token, format string, args ...interface{}) error {
return Errorf(token.Pos, format, args...)
} | go | {
"resource": ""
} |
q5568 | ParseWithPosition | train | func ParseWithPosition(v string, pos ast.Pos) (ast.Node, error) {
ch := scanner.Scan(v, pos)
return parser.Parse(ch)
} | go | {
"resource": ""
} |
q5569 | Peek | train | func (p *Peeker) Peek() *Token {
if p.peeked == nil {
p.peeked = <-p.ch
}
return p.peeked
} | go | {
"resource": ""
} |
q5570 | Read | train | func (p *Peeker) Read() *Token {
token := p.Peek()
// As a special case, we will produce the EOF token forever once
// it is reached.
if token.Type != EOF {
p.peeked = nil
}
return token
} | go | {
"resource": ""
} |
q5571 | Close | train | func (p *Peeker) Close() {
for _ = range p.ch {
// discard
}
// Install a synthetic EOF token in 'peeked' in case someone
// erroneously calls Peek() or Read() after we've closed.
p.peeked = &Token{
Type: EOF,
Content: "",
}
} | go | {
"resource": ""
} |
q5572 | parseInterpolationSeq | train | func (p *parser) parseInterpolationSeq(quoted bool) (ast.Node, error) {
literalType := scanner.LITERAL
endType := scanner.EOF
if quoted {
// exceptions for quoted sequences
literalType = scanner.STRING
endType = scanner.CQUOTE
}
startPos := p.peeker.Peek().Pos
if quoted {
tok := p.peeker.Read()
if tok... | go | {
"resource": ""
} |
q5573 | parseStringToken | train | func (p *parser) parseStringToken(tok *scanner.Token) (string, error) {
var backslashes bool
switch tok.Type {
case scanner.LITERAL:
backslashes = false
case scanner.STRING:
backslashes = true
default:
panic("unsupported string token type")
}
raw := []byte(tok.Content)
buf := make([]byte, 0, len(raw))
... | go | {
"resource": ""
} |
q5574 | parseBinaryOps | train | func (p *parser) parseBinaryOps(ops []map[scanner.TokenType]ast.ArithmeticOp) (ast.Node, error) {
if len(ops) == 0 {
// We've run out of operators, so now we'll just try to parse a term.
return p.ParseExpressionTerm()
}
thisLevel := ops[0]
remaining := ops[1:]
startPos := p.peeker.Peek().Pos
var lhs, rhs a... | go | {
"resource": ""
} |
q5575 | internalEval | train | func internalEval(root ast.Node, config *EvalConfig) (interface{}, ast.Type, error) {
// Copy the scope so we can add our builtins
if config == nil {
config = new(EvalConfig)
}
scope := registerBuiltins(config.GlobalScope)
implicitMap := map[ast.Type]map[ast.Type]string{
ast.TypeFloat: {
ast.TypeInt: "__... | go | {
"resource": ""
} |
q5576 | evalNode | train | func evalNode(raw ast.Node) (EvalNode, error) {
switch n := raw.(type) {
case *ast.Index:
return &evalIndex{n}, nil
case *ast.Call:
return &evalCall{n}, nil
case *ast.Conditional:
return &evalConditional{n}, nil
case *ast.Output:
return &evalOutput{n}, nil
case *ast.LiteralNode:
return &evalLiteralNode{... | go | {
"resource": ""
} |
q5577 | NewLiteralNode | train | func NewLiteralNode(value interface{}, pos Pos) (*LiteralNode, error) {
goType := reflect.TypeOf(value)
var hilType Type
switch goType.Kind() {
case reflect.Bool:
hilType = TypeBool
case reflect.Int:
hilType = TypeInt
case reflect.Float64:
hilType = TypeFloat
case reflect.String:
hilType = TypeString
d... | go | {
"resource": ""
} |
q5578 | MustNewLiteralNode | train | func MustNewLiteralNode(value interface{}, pos Pos) *LiteralNode {
node, err := NewLiteralNode(value, pos)
if err != nil {
panic(err)
}
return node
} | go | {
"resource": ""
} |
q5579 | IsUnknown | train | func (n *LiteralNode) IsUnknown() bool {
return IsUnknown(Variable{
Type: n.Typex,
Value: n.Value,
})
} | go | {
"resource": ""
} |
q5580 | IsUnknown | train | func IsUnknown(v Variable) bool {
// If it is unknown itself, return true
if v.Type == TypeUnknown {
return true
}
// If it is a container type, check the values
switch v.Type {
case TypeList:
for _, el := range v.Value.([]Variable) {
if IsUnknown(el) {
return true
}
}
case TypeMap:
for _, el ... | go | {
"resource": ""
} |
q5581 | Walk | train | func Walk(v interface{}, cb WalkFn) error {
walker := &interpolationWalker{F: cb}
return reflectwalk.Walk(v, walker)
} | go | {
"resource": ""
} |
q5582 | Scan | train | func Scan(s string, startPos ast.Pos) <-chan *Token {
ch := make(chan *Token)
go scan(s, ch, startPos)
return ch
} | go | {
"resource": ""
} |
q5583 | scanIdentifier | train | func scanIdentifier(s string) (string, int) {
byteLen := 0
runeLen := 0
for {
if byteLen >= len(s) {
break
}
nextRune, size := utf8.DecodeRuneInString(s[byteLen:])
if !(nextRune == '_' ||
nextRune == '-' ||
nextRune == '.' ||
nextRune == '*' ||
unicode.IsNumber(nextRune) ||
unicode.IsLette... | go | {
"resource": ""
} |
q5584 | NewVariable | train | func NewVariable(v interface{}) (result Variable, err error) {
switch v := reflect.ValueOf(v); v.Kind() {
case reflect.String:
result.Type = TypeString
default:
err = fmt.Errorf("Unknown type: %s", v.Kind())
}
result.Value = v
return
} | go | {
"resource": ""
} |
q5585 | String | train | func (v Variable) String() string {
return fmt.Sprintf("{Variable (%s): %+v}", v.Type, v.Value)
} | go | {
"resource": ""
} |
q5586 | NewAvx512 | train | func NewAvx512(a512srv *Avx512Server) hash.Hash {
uid := atomic.AddUint64(&uidCounter, 1)
return &Avx512Digest{uid: uid, a512srv: a512srv}
} | go | {
"resource": ""
} |
q5587 | Reset | train | func (d *Avx512Digest) Reset() {
d.a512srv.blocksCh <- blockInput{uid: d.uid, reset: true}
d.nx = 0
d.len = 0
d.final = false
} | go | {
"resource": ""
} |
q5588 | Write | train | func (d *Avx512Digest) Write(p []byte) (nn int, err error) {
if d.final {
return 0, errors.New("Avx512Digest already finalized. Reset first before writing again")
}
nn = len(p)
d.len += uint64(nn)
if d.nx > 0 {
n := copy(d.x[d.nx:], p)
d.nx += n
if d.nx == chunk {
d.a512srv.blocksCh <- blockInput{uid:... | go | {
"resource": ""
} |
q5589 | Sum | train | func (d *Avx512Digest) Sum(in []byte) (result []byte) {
if d.final {
return append(in, d.result[:]...)
}
trail := make([]byte, 0, 128)
len := d.len
// Padding. Add a 1 bit and 0 bits until 56 bytes mod 64.
var tmp [64]byte
tmp[0] = 0x80
if len%64 < 56 {
trail = append(d.x[:d.nx], tmp[0:56-len%64]...)
}... | go | {
"resource": ""
} |
q5590 | blockAvx512 | train | func blockAvx512(digests *[512]byte, input [16][]byte, mask []uint64) [16][Size]byte {
scratch := [512]byte{}
sha256X16Avx512(digests, &scratch, &table, mask, input)
output := [16][Size]byte{}
for i := 0; i < 16; i++ {
output[i] = getDigest(i, digests[:])
}
return output
} | go | {
"resource": ""
} |
q5591 | NewAvx512Server | train | func NewAvx512Server() *Avx512Server {
a512srv := &Avx512Server{}
a512srv.digests = make(map[uint64][Size]byte)
a512srv.blocksCh = make(chan blockInput)
// Start a single thread for reading from the input channel
go a512srv.Process()
return a512srv
} | go | {
"resource": ""
} |
q5592 | Process | train | func (a512srv *Avx512Server) Process() {
for {
select {
case block := <-a512srv.blocksCh:
if block.reset {
a512srv.reset(block.uid)
continue
}
index := block.uid & 0xf
// fmt.Println("Adding message:", block.uid, index)
if a512srv.lanes[index].block != nil { // If slot is already filled, pr... | go | {
"resource": ""
} |
q5593 | reset | train | func (a512srv *Avx512Server) reset(uid uint64) {
// Check if there is a message still waiting to be processed (and remove if so)
for i, lane := range a512srv.lanes {
if lane.uid == uid {
if lane.block != nil {
a512srv.lanes[i] = Avx512LaneInfo{} // clear message
a512srv.totalIn--
}
}
}
// Delete... | go | {
"resource": ""
} |
q5594 | blocks | train | func (a512srv *Avx512Server) blocks() (err error) {
inputs := [16][]byte{}
for i := range inputs {
inputs[i] = a512srv.lanes[i].block
}
mask := expandMask(genMask(inputs))
outputs := blockAvx512(a512srv.getDigests(), inputs, mask)
a512srv.totalIn = 0
for i := 0; i < len(outputs); i++ {
uid, outputCh := a5... | go | {
"resource": ""
} |
q5595 | Sum | train | func (a512srv *Avx512Server) Sum(uid uint64, p []byte) [32]byte {
sumCh := make(chan [32]byte)
a512srv.blocksCh <- blockInput{uid: uid, msg: p, final: true, sumCh: sumCh}
return <-sumCh
} | go | {
"resource": ""
} |
q5596 | Reset | train | func (d *digest) Reset() {
d.h[0] = init0
d.h[1] = init1
d.h[2] = init2
d.h[3] = init3
d.h[4] = init4
d.h[5] = init5
d.h[6] = init6
d.h[7] = init7
d.nx = 0
d.len = 0
} | go | {
"resource": ""
} |
q5597 | New | train | func New() hash.Hash {
if blockfunc != blockfuncGeneric {
d := new(digest)
d.Reset()
return d
}
// Fallback to the standard golang implementation
// if no features were found.
return sha256.New()
} | go | {
"resource": ""
} |
q5598 | Sum256 | train | func Sum256(data []byte) (result [Size]byte) {
var d digest
d.Reset()
d.Write(data)
result = d.checkSum()
return
} | go | {
"resource": ""
} |
q5599 | Sum | train | func (d *digest) Sum(in []byte) []byte {
// Make a copy of d0 so that caller can keep writing and summing.
d0 := *d
hash := d0.checkSum()
return append(in, hash[:]...)
} | go | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.