_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/integration/cluster.go#L213-L215
func NewClusterByConfig(t testing.TB, cfg *ClusterConfig) *cluster { return newCluster(t, cfg) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pps/pretty/pretty.go#L414-L436
func ShorthandInput(input *ppsclient.Input) string { switch { case input == nil: return "none" case input.Pfs != nil: return fmt.Sprintf("%s:%s", input.Pfs.Repo, input.Pfs.Glob) case input.Cross != nil: var subInput []string for _, input := range input.Cross { subInput = append(subInput, ShorthandInput(input)) } return "(" + strings.Join(subInput, " ⨯ ") + ")" case input.Union != nil: var subInput []string for _, input := range input.Union { subInput = append(subInput, ShorthandInput(input)) } return "(" + strings.Join(subInput, " ∪ ") + ")" case input.Cron != nil: return fmt.Sprintf("%s:%s", input.Cron.Name, input.Cron.Spec) } return "" }
https://github.com/mastahyeti/fakeca/blob/c1d84b1b473e99212130da7b311dd0605de5ed0a/identity.go#L42-L44
func (id *Identity) PFX(password string) []byte { return toPFX(id.Certificate, id.PrivateKey, password) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L1854-L1862
func (u OperationBody) MustPaymentOp() PaymentOp { val, ok := u.GetPaymentOp() if !ok { panic("arm PaymentOp is not set") } return val }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/outbound.go#L178-L188
func (call *OutboundCall) createStatsTags(connectionTags map[string]string, callOptions *CallOptions, method string) { call.commonStatsTags = map[string]string{ "target-service": call.callReq.Service, } for k, v := range connectionTags { call.commonStatsTags[k] = v } if callOptions.Format != HTTP { call.commonStatsTags["target-endpoint"] = string(method) } }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/tackle/main.go#L176-L194
func currentClusters(proj string) (map[string]cluster, error) { clusters, err := output("gcloud", "container", "clusters", "list", "--project="+proj, "--format=value(name,zone)") if err != nil { return nil, fmt.Errorf("list clusters: %v", err) } options := map[string]cluster{} for _, line := range strings.Split(clusters, "\n") { if len(line) == 0 { continue } parts := strings.Split(line, "\t") if len(parts) != 2 { return nil, fmt.Errorf("bad line: %q", line) } c := cluster{name: parts[0], zone: parts[1], project: proj} options[c.name] = c } return options, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/robots/issue-creator/creator/creator.go#L296-L312
func setIntersect(a, b []string) (filtered, removed []string) { for _, elemA := range a { found := false for _, elemB := range b { if elemA == elemB { found = true break } } if found { filtered = append(filtered, elemA) } else { removed = append(removed, elemA) } } return }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L697-L708
func rewriteImport(f *ast.File, oldPath, newPath string) (rewrote bool) { for _, imp := range f.Imports { if importPath(imp) == oldPath { rewrote = true // record old End, because the default is to compute // it using the length of imp.Path.Value. imp.EndPos = imp.End() imp.Path.Value = strconv.Quote(newPath) } } return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L1692-L1696
func (v SetRuleSelectorReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss15(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/reiver/go-telnet/blob/9ff0b2ab096ebe42bf8e2ffd1366e7ed2223b04c/tls.go#L49-L113
func (server *Server) ListenAndServeTLS(certFile string, keyFile string) error { addr := server.Addr if "" == addr { addr = ":telnets" } listener, err := net.Listen("tcp", addr) if nil != err { return err } // Apparently have to make a copy of the TLS config this way, rather than by // simple assignment, to prevent some unexported fields from being copied over. // // It would be nice if tls.Config had a method that would do this "safely". // (I.e., what happens if in the future more exported fields are added to // tls.Config?) var tlsConfig *tls.Config = nil if nil == server.TLSConfig { tlsConfig = &tls.Config{} } else { tlsConfig = &tls.Config{ Rand: server.TLSConfig.Rand, Time: server.TLSConfig.Time, Certificates: server.TLSConfig.Certificates, NameToCertificate: server.TLSConfig.NameToCertificate, GetCertificate: server.TLSConfig.GetCertificate, RootCAs: server.TLSConfig.RootCAs, NextProtos: server.TLSConfig.NextProtos, ServerName: server.TLSConfig.ServerName, ClientAuth: server.TLSConfig.ClientAuth, ClientCAs: server.TLSConfig.ClientCAs, InsecureSkipVerify: server.TLSConfig.InsecureSkipVerify, CipherSuites: server.TLSConfig.CipherSuites, PreferServerCipherSuites: server.TLSConfig.PreferServerCipherSuites, SessionTicketsDisabled: server.TLSConfig.SessionTicketsDisabled, SessionTicketKey: server.TLSConfig.SessionTicketKey, ClientSessionCache: server.TLSConfig.ClientSessionCache, MinVersion: server.TLSConfig.MinVersion, MaxVersion: server.TLSConfig.MaxVersion, CurvePreferences: server.TLSConfig.CurvePreferences, } } tlsConfigHasCertificate := len(tlsConfig.Certificates) > 0 || nil != tlsConfig.GetCertificate if "" == certFile || "" == keyFile || !tlsConfigHasCertificate { tlsConfig.Certificates = make([]tls.Certificate, 1) var err error tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile) if nil != err { return err } } tlsListener := tls.NewListener(listener, tlsConfig) return server.Serve(tlsListener) }
https://github.com/codegangsta/martini-contrib/blob/8ce6181c2609699e4c7cd30994b76a850a9cdadc/cors/cors.go#L85-L125
func (o *Options) PreflightHeader(origin, rMethod, rHeaders string) (headers map[string]string) { headers = make(map[string]string) if !o.AllowAllOrigins && !o.IsOriginAllowed(origin) { return } // verify if requested method is allowed // TODO: Too many for loops for _, method := range o.AllowMethods { if method == rMethod { headers[headerAllowMethods] = strings.Join(o.AllowMethods, ",") break } } // verify if requested headers are allowed var allowed []string for _, rHeader := range strings.Split(rHeaders, ",") { lookupLoop: for _, allowedHeader := range o.AllowHeaders { if rHeader == allowedHeader { allowed = append(allowed, rHeader) break lookupLoop } } } // add allowed headers if len(allowed) > 0 { headers[headerAllowHeaders] = strings.Join(allowed, ",") } // add exposed headers if len(o.ExposeHeaders) > 0 { headers[headerExposeHeaders] = strings.Join(o.ExposeHeaders, ",") } // add a max age header if o.MaxAge > time.Duration(0) { headers[headerMaxAge] = strconv.FormatInt(int64(o.MaxAge/time.Second), 10) } return }
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/pbuf.go#L60-L62
func (b *PointerRingBuf) ReadWithoutAdvance(p []interface{}) (n int, err error) { return b.readAndMaybeAdvance(p, false) }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/highgui.go#L145-L148
func (win *Window) GetHandle() unsafe.Pointer { p := C.cvGetWindowHandle(win.name_c) return unsafe.Pointer(p) }
https://github.com/getantibody/folder/blob/e65aa38ebeb03e6d6e91b90a637f3b7c17e1b6d6/main.go#L12-L18
func FromURL(url string) string { result := url for _, replace := range replaces { result = strings.Replace(result, replace.a, replace.b, -1) } return result }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/log/log.go#L76-L82
func (t *Target) Error(v error) { t.mut.RLock() defer t.mut.RUnlock() if t.logger != nil { t.logger.Errorf("%+v", v) } }
https://github.com/ccding/go-config-reader/blob/8b6c2b50197f20da3b1c5944c274c173634dc056/config/config.go#L148-L161
func (c *Config) WriteTo(filename string) error { content := "" for k, v := range c.config { format := "%v = %v\n" if k != "" { content += fmt.Sprintf("[%v]\n", k) format = "\t" + format } for key, value := range v { content += fmt.Sprintf(format, key, value) } } return ioutil.WriteFile(filename, []byte(content), 0644) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/token-counter/influx.go#L68-L91
func (i *InfluxDB) Push(measurement string, tags map[string]string, fields map[string]interface{}, date time.Time) error { batch, err := influxdb.NewBatchPoints(influxdb.BatchPointsConfig{ Database: i.database, Precision: "s", }) if err != nil { return err } pt, err := influxdb.NewPoint(measurement, tags, fields, date) if err != nil { return err } batch.AddPoint(pt) err = i.client.Write(batch) if err != nil { return err } glog.Infof("Sent to influx: %s %+v %+v %s", measurement, tags, fields, date) return nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/raft.go#L644-L678
func getIDs(lg *zap.Logger, snap *raftpb.Snapshot, ents []raftpb.Entry) []uint64 { ids := make(map[uint64]bool) if snap != nil { for _, id := range snap.Metadata.ConfState.Nodes { ids[id] = true } } for _, e := range ents { if e.Type != raftpb.EntryConfChange { continue } var cc raftpb.ConfChange pbutil.MustUnmarshal(&cc, e.Data) switch cc.Type { case raftpb.ConfChangeAddNode: ids[cc.NodeID] = true case raftpb.ConfChangeRemoveNode: delete(ids, cc.NodeID) case raftpb.ConfChangeUpdateNode: // do nothing default: if lg != nil { lg.Panic("unknown ConfChange Type", zap.String("type", cc.Type.String())) } else { plog.Panicf("ConfChange Type should be either ConfChangeAddNode or ConfChangeRemoveNode!") } } } sids := make(types.Uint64Slice, 0, len(ids)) for id := range ids { sids = append(sids, id) } sort.Sort(sids) return []uint64(sids) }
https://github.com/urandom/handler/blob/61508044a5569d1609521d81e81f6737567fd104/method/verb.go#L19-L32
func HTTP(h http.Handler, verb Verb, verbs ...Verb) http.Handler { verbSet := map[Verb]struct{}{verb: struct{}{}} for _, v := range verbs { verbSet[v] = struct{}{} } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if _, ok := verbSet[Verb(r.Method)]; ok { h.ServeHTTP(w, r) } else { w.WriteHeader(http.StatusBadRequest) } }) }
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/memory.go#L207-L211
func (b *ChannelMemoryBackend) Flush() { b.flushWg.Add(1) b.events <- eventFlush b.flushWg.Wait() }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L259-L273
func (pr *prInsecureAcceptAnything) UnmarshalJSON(data []byte) error { *pr = prInsecureAcceptAnything{} var tmp prInsecureAcceptAnything if err := paranoidUnmarshalJSONObjectExactFields(data, map[string]interface{}{ "type": &tmp.Type, }); err != nil { return err } if tmp.Type != prTypeInsecureAcceptAnything { return InvalidPolicyFormatError(fmt.Sprintf("Unexpected policy requirement type \"%s\"", tmp.Type)) } *pr = *newPRInsecureAcceptAnything() return nil }
https://github.com/knq/sdhook/blob/41b9ccbff0b5fa5a56fbdccf2eb8653e7afe8d4b/opts.go#L61-L66
func ErrorService(errorService *errorReporting.Service) Option { return func(sh *StackdriverHook) error { sh.errorService = errorService return nil } }
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/bool.go#L50-L69
func (b *Bool) UnmarshalJSON(data []byte) error { var err error var v interface{} if err = json.Unmarshal(data, &v); err != nil { return err } switch x := v.(type) { case bool: b.Bool = x case map[string]interface{}: err = json.Unmarshal(data, &b.NullBool) case nil: b.Valid = false return nil default: err = fmt.Errorf("json: cannot unmarshal %v into Go value of type null.Bool", reflect.TypeOf(v).Name()) } b.Valid = err == nil return err }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/iterator.go#L194-L199
func (s *MergeIterator) Key() []byte { if len(s.h) == 0 { return nil } return s.h[0].itr.Key() }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/approve/approvers/owners.go#L59-L61
func NewOwners(log *logrus.Entry, filenames []string, r Repo, s int64) Owners { return Owners{filenames: filenames, repo: r, seed: s, log: log} }
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/tree.go#L157-L166
func GetAttribute(n Elem, local, space string) (xml.Attr, bool) { attrs := n.GetAttrs() for _, i := range attrs { attr := i.GetToken().(xml.Attr) if local == attr.Name.Local && space == attr.Name.Space { return attr, true } } return xml.Attr{}, false }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/migration/migration.go#L65-L67
func Register(name string, fn MigrateFunc) error { return register(name, false, fn) }
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/report_slices.go#L20-L57
func (opts formatOptions) CanFormatDiffSlice(v *valueNode) bool { switch { case opts.DiffMode != diffUnknown: return false // Must be formatting in diff mode case v.NumDiff == 0: return false // No differences detected case v.NumIgnored+v.NumCompared+v.NumTransformed > 0: // TODO: Handle the case where someone uses bytes.Equal on a large slice. return false // Some custom option was used to determined equality case !v.ValueX.IsValid() || !v.ValueY.IsValid(): return false // Both values must be valid } switch t := v.Type; t.Kind() { case reflect.String: case reflect.Array, reflect.Slice: // Only slices of primitive types have specialized handling. switch t.Elem().Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Bool, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: default: return false } // If a sufficient number of elements already differ, // use specialized formatting even if length requirement is not met. if v.NumDiff > v.NumSame { return true } default: return false } // Use specialized string diffing for longer slices or strings. const minLength = 64 return v.ValueX.Len() >= minLength && v.ValueY.Len() >= minLength }
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/english/stem.go#L11-L44
func Stem(word string, stemStopwWords bool) string { word = strings.ToLower(strings.TrimSpace(word)) // Return small words and stop words if len(word) <= 2 || (stemStopwWords == false && isStopWord(word)) { return word } // Return special words immediately if specialVersion := stemSpecialWord(word); specialVersion != "" { word = specialVersion return word } w := snowballword.New(word) // Stem the word. Note, each of these // steps will alter `w` in place. // preprocess(w) step0(w) step1a(w) step1b(w) step1c(w) step2(w) step3(w) step4(w) step5(w) postprocess(w) return w.String() }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/mex.go#L106-L112
func (mex *messageExchange) checkError() error { if err := mex.ctx.Err(); err != nil { return GetContextError(err) } return mex.errCh.checkErr() }
https://github.com/libp2p/go-libp2p-crypto/blob/9d2fed53443f745e6dc4d02bdcc94d9742a0ca84/ecdsa.go#L79-L86
func UnmarshalECDSAPrivateKey(data []byte) (PrivKey, error) { priv, err := x509.ParseECPrivateKey(data) if err != nil { return nil, err } return &ECDSAPrivateKey{priv}, nil }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/error_registry.go#L102-L111
func (r *MapErrorRegistry) AddHandler(code int, handler func(body []byte) error) error { if _, ok := r.errors[code]; ok { return ErrErrorAlreadyRegistered } if _, ok := r.handlers[code]; ok { return ErrErrorAlreadyRegistered } r.handlers[code] = handler return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L5978-L5982
func (v *EventStyleSheetAdded) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss53(&r, v) return r.Error() }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/log/log.go#L304-L319
func (r *Result) run() error { res := &pb.LogReadResponse{} if err := internal.Call(r.context, "logservice", "Read", r.request, res); err != nil { return err } r.logs = make([]*Record, len(res.Log)) r.request.Offset = res.Offset r.resultsSeen = true for i, log := range res.Log { r.logs[i] = protoToRecord(log) } return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node/open.go#L14-L22
func Open(dir string) (*sql.DB, error) { path := filepath.Join(dir, "local.db") db, err := sqliteOpen(path) if err != nil { return nil, fmt.Errorf("cannot open node database: %v", err) } return db, nil }
https://github.com/nightlyone/lockfile/blob/0ad87eef1443f64d3d8c50da647e2b1552851124/lockfile.go#L44-L49
func New(path string) (Lockfile, error) { if !filepath.IsAbs(path) { return Lockfile(""), ErrNeedAbsPath } return Lockfile(path), nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L341-L345
func (v WebSocketRequest) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork1(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L487-L491
func (v SetNodeNameReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom4(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_zfs_utils.go#L42-L62
func zfsModuleVersionGet() (string, error) { var zfsVersion string if shared.PathExists("/sys/module/zfs/version") { out, err := ioutil.ReadFile("/sys/module/zfs/version") if err != nil { return "", fmt.Errorf("Could not determine ZFS module version") } zfsVersion = string(out) } else { out, err := shared.RunCommand("modinfo", "-F", "version", "zfs") if err != nil { return "", fmt.Errorf("Could not determine ZFS module version") } zfsVersion = out } return strings.TrimSpace(zfsVersion), nil }
https://github.com/texttheater/golang-levenshtein/blob/d188e65d659ef53fcdb0691c12f1bba64928b649/levenshtein/levenshtein.go#L62-L99
func DistanceForStrings(source []rune, target []rune, op Options) int { // Note: This algorithm is a specialization of MatrixForStrings. // MatrixForStrings returns the full edit matrix. However, we only need a // single value (see DistanceForMatrix) and the main loop of the algorithm // only uses the current and previous row. As such we create a 2D matrix, // but with height 2 (enough to store current and previous row). height := len(source) + 1 width := len(target) + 1 matrix := make([][]int, 2) // Initialize trivial distances (from/to empty string). That is, fill // the left column and the top row with row/column indices. for i := 0; i < 2; i++ { matrix[i] = make([]int, width) matrix[i][0] = i } for j := 1; j < width; j++ { matrix[0][j] = j } // Fill in the remaining cells: for each prefix pair, choose the // (edit history, operation) pair with the lowest cost. for i := 1; i < height; i++ { cur := matrix[i%2] prev := matrix[(i-1)%2] cur[0] = i for j := 1; j < width; j++ { delCost := prev[j] + op.DelCost matchSubCost := prev[j-1] if !op.Matches(source[i-1], target[j-1]) { matchSubCost += op.SubCost } insCost := cur[j-1] + op.InsCost cur[j] = min(delCost, min(matchSubCost, insCost)) } } return matrix[(height-1)%2][width-1] }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L465-L474
func (p *GetHeapUsageParams) Do(ctx context.Context) (usedSize float64, totalSize float64, err error) { // execute var res GetHeapUsageReturns err = cdp.Execute(ctx, CommandGetHeapUsage, nil, &res) if err != nil { return 0, 0, err } return res.UsedSize, res.TotalSize, nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/log/log.go#L254-L282
func Pretty(entry *logrus.Entry) ([]byte, error) { serialized := []byte( fmt.Sprintf( "%v %v ", entry.Time.Format(logrus.DefaultTimestampFormat), strings.ToUpper(entry.Level.String()), ), ) if entry.Data["service"] != nil { serialized = append(serialized, []byte(fmt.Sprintf("%v.%v ", entry.Data["service"], entry.Data["method"]))...) } if len(entry.Data) > 2 { delete(entry.Data, "service") delete(entry.Data, "method") if entry.Data["duration"] != nil { entry.Data["duration"] = entry.Data["duration"].(time.Duration).Seconds() } data, err := json.Marshal(entry.Data) if err != nil { return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) } serialized = append(serialized, []byte(string(data))...) serialized = append(serialized, ' ') } serialized = append(serialized, []byte(entry.Message)...) serialized = append(serialized, '\n') return serialized, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L3931-L3935
func (v EventBindingCalled) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoRuntime36(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/obj/amazon_client.go#L147-L151
func (v *vaultCredentialsProvider) IsExpired() bool { v.leaseMu.Lock() defer v.leaseMu.Unlock() return time.Now().After(v.leaseLastRenew.Add(v.leaseDuration)) }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/namespaced/namespaced.go#L52-L68
func (n *Namespaced) WithField(k string, v interface{}) log.Interface { if k == NamespaceKey { if str, ok := v.(string); ok { return &Namespaced{ Interface: n.Interface, namespaces: n.namespaces, namespace: str, } } } return &Namespaced{ Interface: n.Interface.WithField(k, v), namespaces: n.namespaces, namespace: n.namespace, } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/browser.go#L34-L39
func GrantPermissions(origin string, permissions []PermissionType) *GrantPermissionsParams { return &GrantPermissionsParams{ Origin: origin, Permissions: permissions, } }
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/rbuf.go#L306-L326
func (b *FixedSizeRingBuf) ReadFrom(r io.Reader) (n int64, err error) { for { writeCapacity := b.N - b.Readable if writeCapacity <= 0 { // we are all full return n, nil } writeStart := (b.Beg + b.Readable) % b.N upperLim := intMin(writeStart+writeCapacity, b.N) m, e := r.Read(b.A[b.Use][writeStart:upperLim]) n += int64(m) b.Readable += m if e == io.EOF { return n, nil } if e != nil { return n, e } } }
https://github.com/pantheon-systems/go-certauth/blob/8764720d23a5034dd9fab090815b7859463c68f6/certutils/certutils_pre_go18.go#L104-L117
func LoadCACertFile(cert string) (*x509.CertPool, error) { // validate caCert, and setup certpool ca, err := ioutil.ReadFile(cert) if err != nil { return nil, fmt.Errorf("could not load CA Certificate: %s ", err.Error()) } certPool := x509.NewCertPool() if err := certPool.AppendCertsFromPEM(ca); !err { return nil, errors.New("could not append CA Certificate to CertPool") } return certPool, nil }
https://github.com/blacklabeldata/namedtuple/blob/c341f1db44f30b8164294aa8605ede42be604aba/types.go#L47-L50
func (t *TupleType) Contains(field string) bool { _, exists := t.fields[field] return exists }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L317-L319
func Set(c context.Context, item *Item) error { return singleError(set(c, []*Item{item}, nil, pb.MemcacheSetRequest_SET)) }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/cmd/viewcore/main.go#L749-L765
func typeName(c *gocore.Process, x gocore.Object) string { size := c.Size(x) typ, repeat := c.Type(x) if typ == nil { return fmt.Sprintf("unk%d", size) } name := typ.String() n := size / typ.Size if n > 1 { if repeat < n { name = fmt.Sprintf("[%d+%d?]%s", repeat, n-repeat, name) } else { name = fmt.Sprintf("[%d]%s", repeat, name) } } return name }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3223-L3226
func (e SetOptionsResultCode) String() string { name, _ := setOptionsResultCodeMap[int32(e)] return name }
https://github.com/sourcegraph/go-vcsurl/blob/2305ecca26ab74e3f819cb3875cd631f467e0c2b/vcsurl.go#L58-L160
func Parse(spec string) (info *RepoInfo, err error) { if parts := gitPreprocessRE.FindStringSubmatch(spec); len(parts) == 3 { spec = fmt.Sprintf("git://%s/%s", parts[1], parts[2]) } var parsedURL *url.URL if parsedURL, err = url.Parse(spec); err == nil { if parsedURL.Scheme == "" { spec = "https://" + spec if parsedURL, err = url.Parse(spec); err != nil { return nil, err } } info = new(RepoInfo) info.CloneURL = parsedURL.String() info.RepoHost = RepoHost(parsedURL.Host) info.Rev = parsedURL.Fragment if info.RepoHost == GitHub || parsedURL.Scheme == "git" { info.VCS = Git } else if info.RepoHost == GoogleCode && parsedURL.Scheme == "https" { info.VCS = Mercurial } else if info.RepoHost == Bitbucket && (parsedURL.Scheme == "https" || parsedURL.Scheme == "http") { if !strings.HasSuffix(parsedURL.Path, ".git") { info.VCS = Mercurial } } else if info.RepoHost == Launchpad { info.VCS = Bazaar } path := parsedURL.Path switch info.RepoHost { case GitHub: parts := strings.Split(path, "/") if len(parts) >= 3 { info.Username = parts[1] parts[2] = removeDotGit.ReplaceAllLiteralString(parts[2], "") info.Name = parts[2] info.FullName = parts[1] + "/" + parts[2] info.CloneURL = "git://github.com/" + info.FullName + ".git" } case GoogleCode: parts := strings.Split(path, "/") if len(parts) >= 3 { if parts[1] == "p" { info.Name = parts[2] info.FullName = info.Name info.CloneURL = "https://code.google.com/p/" + info.FullName } } case PythonOrg: parts := strings.Split(path, "/") if len(parts) >= 2 { info.CloneURL = "http://hg.python.org" + path info.VCS = Mercurial info.Name = parts[len(parts)-1] info.FullName = strings.Join(parts[1:], "/") } case Bitbucket: parts := strings.Split(path, "/") if len(parts) >= 3 { info.Username = parts[1] if strings.HasSuffix(parts[2], ".git") { info.VCS = Git parts[2] = strings.TrimSuffix(parts[2], ".git") } info.Name = parts[2] info.FullName = parts[1] + "/" + parts[2] info.CloneURL = "https://bitbucket.org/" + info.FullName if info.VCS == Git { info.CloneURL += ".git" } } default: if len(path) == 0 { return nil, fmt.Errorf("empty path in repo spec: %q", spec) } path = path[1:] // remove leading slash path = removeDotGit.ReplaceAllLiteralString(path, "") info.FullName = path info.Name = filepath.Base(path) if strings.Contains(spec, "git") { info.VCS = Git } else if strings.Contains(spec, "hg") || strings.Contains(spec, "mercurial") { info.VCS = Mercurial } } if info.RepoHost == Launchpad { parsedURL.Scheme = "bzr" info.CloneURL = parsedURL.String() } if info.Name == "" || info.FullName == "" { return nil, fmt.Errorf("unable to determine name or full name for repo spec %q", spec) } return info, nil } return nil, err }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dbase/curve.go#L113-L143
func TraceQuad(t Liner, quad []float64, flatteningThreshold float64) error { if len(quad) < 6 { return errors.New("quad length must be >= 6") } // Allocates curves stack var curves [CurveRecursionLimit * 6]float64 copy(curves[0:6], quad[0:6]) i := 0 // current curve var c []float64 var dx, dy, d float64 for i >= 0 { c = curves[i:] dx = c[4] - c[0] dy = c[5] - c[1] d = math.Abs(((c[2]-c[4])*dy - (c[3]-c[5])*dx)) // if it's flat then trace a line if (d*d) <= flatteningThreshold*(dx*dx+dy*dy) || i == len(curves)-6 { t.LineTo(c[4], c[5]) i -= 6 } else { // second half of bezier go lower onto the stack SubdivideQuad(c, curves[i+6:], curves[i:]) i += 6 } } return nil }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L120-L122
func (img *IplImage) SetCOI(coi int) { C.cvSetImageCOI((*C.IplImage)(img), C.int(coi)) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3862-L3888
func (u OperationResultTr) ArmForSwitch(sw int32) (string, bool) { switch OperationType(sw) { case OperationTypeCreateAccount: return "CreateAccountResult", true case OperationTypePayment: return "PaymentResult", true case OperationTypePathPayment: return "PathPaymentResult", true case OperationTypeManageOffer: return "ManageOfferResult", true case OperationTypeCreatePassiveOffer: return "CreatePassiveOfferResult", true case OperationTypeSetOptions: return "SetOptionsResult", true case OperationTypeChangeTrust: return "ChangeTrustResult", true case OperationTypeAllowTrust: return "AllowTrustResult", true case OperationTypeAccountMerge: return "AccountMergeResult", true case OperationTypeInflation: return "InflationResult", true case OperationTypeManageData: return "ManageDataResult", true } return "-", false }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/kube/client.go#L334-L345
func UnmarshalClusterMap(data []byte) (map[string]Cluster, error) { var raw map[string]Cluster if err := yaml.Unmarshal(data, &raw); err != nil { // If we failed to unmarshal the multicluster format try the single Cluster format. var singleConfig Cluster if err := yaml.Unmarshal(data, &singleConfig); err != nil { return nil, err } raw = map[string]Cluster{DefaultClusterAlias: singleConfig} } return raw, nil }
https://github.com/gravitational/roundtrip/blob/e1e0cd6b05a6bb1791b262e63160038828fd7b3a/creds.go#L44-L94
func ParseAuthHeaders(r *http.Request) (*AuthCreds, error) { // according to the doc below oauth 2.0 bearer access token can // come with query parameter // http://self-issued.info/docs/draft-ietf-oauth-v2-bearer.html#query-param // we are going to support this if r.URL.Query().Get(AccessTokenQueryParam) != "" { return &AuthCreds{ Type: AuthBearer, Password: r.URL.Query().Get(AccessTokenQueryParam), }, nil } authHeader := r.Header.Get("Authorization") if authHeader == "" { return nil, trace.Wrap(&AccessDeniedError{Message: "unauthorized"}) } auth := strings.SplitN(authHeader, " ", 2) if len(auth) != 2 { return nil, trace.Wrap( &ParameterError{ Name: "Authorization", Message: "invalid auth header"}) } switch auth[0] { case AuthBasic: payload, err := base64.StdEncoding.DecodeString(auth[1]) if err != nil { return nil, trace.Wrap( &ParameterError{ Name: "Authorization", Message: err.Error()}) } pair := strings.SplitN(string(payload), ":", 2) if len(pair) != 2 { return nil, trace.Wrap( &ParameterError{ Name: "Authorization", Message: "bad header"}) } return &AuthCreds{Type: AuthBasic, Username: pair[0], Password: pair[1]}, nil case AuthBearer: return &AuthCreds{Type: AuthBearer, Password: auth[1]}, nil } return nil, trace.Wrap( &ParameterError{ Name: "Authorization", Message: "unsupported auth scheme"}) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/types.go#L127-L142
func (t Modifier) String() string { switch t { case ModifierNone: return "None" case ModifierAlt: return "Alt" case ModifierCtrl: return "Ctrl" case ModifierMeta: return "Meta" case ModifierShift: return "Shift" } return fmt.Sprintf("Modifier(%d)", t) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/deck/pr_history.go#L133-L161
func getPRBuildData(bucket storageBucket, jobs []jobBuilds) []buildData { buildch := make(chan buildData) defer close(buildch) expected := 0 for _, job := range jobs { for j, buildPrefix := range job.buildPrefixes { go func(j int, jobName, buildPrefix string) { build, err := getBuildData(bucket, buildPrefix) if err != nil { logrus.WithError(err).Warningf("build %s information incomplete", buildPrefix) } split := strings.Split(strings.TrimSuffix(buildPrefix, "/"), "/") build.SpyglassLink = path.Join(spyglassPrefix, bucket.getName(), buildPrefix) build.ID = split[len(split)-1] build.jobName = jobName build.prefix = buildPrefix build.index = j buildch <- build }(j, job.name, buildPrefix) expected++ } } builds := []buildData{} for k := 0; k < expected; k++ { build := <-buildch builds = append(builds, build) } return builds }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L772-L775
func (p PrintToPDFParams) WithFooterTemplate(footerTemplate string) *PrintToPDFParams { p.FooterTemplate = footerTemplate return &p }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/plugins/state.go#L36-L39
func (s *StatePlugin) AddFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&s.desc, "state", "", "Description of the state (eg: `opened,!merged,labeled:cool`)") cmd.Flags().IntSliceVar(&s.percentiles, "percentiles", []int{}, "Age percentiles for state") }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/easyjson.go#L1609-L1613
func (v ClearGeolocationOverrideParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoEmulation18(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/brankas/sentinel/blob/0ff081867c31a45cb71f5976ea6144fd06a557b5/opts.go#L33-L46
func Server(serverFuncs ...interface{}) Option { return func(s *Sentinel) error { s.Lock() defer s.Unlock() if s.started { return ErrAlreadyStarted } var err error s.serverFuncs, err = convertAndAppendContextFuncs(s.serverFuncs, serverFuncs...) return err } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L1148-L1152
func (v *SourceRange) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss9(&r, v) return r.Error() }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/etcdserverpb/rpc.pb.go#L877-L884
func (*ResponseOp) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _ResponseOp_OneofMarshaler, _ResponseOp_OneofUnmarshaler, _ResponseOp_OneofSizer, []interface{}{ (*ResponseOp_ResponseRange)(nil), (*ResponseOp_ResponsePut)(nil), (*ResponseOp_ResponseDeleteRange)(nil), (*ResponseOp_ResponseTxn)(nil), } }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/routes/patch_apps_app_routes_route_responses.go#L25-L59
func (o *PatchAppsAppRoutesRouteReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 200: result := NewPatchAppsAppRoutesRouteOK() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil case 400: result := NewPatchAppsAppRoutesRouteBadRequest() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 404: result := NewPatchAppsAppRoutesRouteNotFound() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result default: result := NewPatchAppsAppRoutesRouteDefault(response.Code()) if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } if response.Code()/100 == 2 { return result, nil } return nil, result } }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/page.go#L261-L280
func (p *Page) RunScript(body string, arguments map[string]interface{}, result interface{}) error { var ( keys []string values []interface{} ) for key, value := range arguments { keys = append(keys, key) values = append(values, value) } argumentList := strings.Join(keys, ", ") cleanBody := fmt.Sprintf("return (function(%s) { %s; }).apply(this, arguments);", argumentList, body) if err := p.session.Execute(cleanBody, values, result); err != nil { return fmt.Errorf("failed to run script: %s", err) } return nil }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/guest.go#L459-L508
func (g *Guest) Ls(dir string) ([]*GuestFile, error) { var jobHandle C.VixHandle = C.VIX_INVALID_HANDLE var err C.VixError = C.VIX_OK var files []*GuestFile guestdir := C.CString(dir) defer C.free(unsafe.Pointer(guestdir)) jobHandle = C.VixVM_ListDirectoryInGuest(g.handle, guestdir, 0, nil, nil) defer C.Vix_ReleaseHandle(jobHandle) err = C.vix_job_wait(jobHandle) if C.VIX_OK != err { return nil, &Error{ Operation: "guest.Ls.ListDirectoryInGuest", Code: int(err & 0xFFFF), Text: C.GoString(C.Vix_GetErrorText(err, nil)), } } num := C.VixJob_GetNumProperties(jobHandle, C.VIX_PROPERTY_JOB_RESULT_ITEM_NAME) for i := 0; i < int(num); i++ { var name *C.char var size *C.int64 var modtime *C.int64 var attrs *C.int gfile := &GuestFile{} err = C.get_guest_file(jobHandle, C.int(i), name, size, modtime, attrs) if C.VIX_OK != err { return nil, &Error{ Operation: "guest.Ls.get_guest_file", Code: int(err & 0xFFFF), Text: C.GoString(C.Vix_GetErrorText(err, nil)), } } gfile.Path = C.GoString(name) C.Vix_FreeBuffer(unsafe.Pointer(name)) gfile.Size = int64(*size) gfile.Modtime = int64(*modtime) gfile.Attrs = FileAttr(*attrs) files = append(files, gfile) } return files, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/layertree/layertree.go#L237-L239
func (p *ReleaseSnapshotParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandReleaseSnapshot, p, nil) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L148-L151
func (p DescribeNodeParams) WithObjectID(objectID runtime.RemoteObjectID) *DescribeNodeParams { p.ObjectID = objectID return &p }
https://github.com/go-openapi/loads/blob/74628589c3b94e3526a842d24f46589980f5ab22/spec.go#L78-L85
func JSONSpec(path string) (*Document, error) { data, err := JSONDoc(path) if err != nil { return nil, err } // convert to json return Analyzed(data, "") }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/meshconn/peer.go#L135-L137
func (p *Peer) LocalAddr() net.Addr { return MeshAddr{PeerName: p.name, PeerUID: p.uid} }
https://github.com/michaelbironneau/garbler/blob/2018e2dc9c1173564cc1352ccb90bdc0ac29c12f/lib/garbler.go#L149-L199
func (g Garbler) garbledSequence(length int, numGarbled int) string { if numGarbled > length { panic("should not require more garbled chars than string length") } var ret string numCanGarble := 0 sequence := []string{"c", "v", "c", "c", "v"} sequencePosition := 0 for i := 0; i < length; i++ { if i%2 == 0 && numCanGarble < numGarbled { //make things garblable if required: //make every other character garblable until we reach numGarblable if sequence[sequencePosition] == "c" { ret += string(ConsonantGarblers[randInt(len(ConsonantGarblers))]) } else { ret += string(VowelGarblers[randInt(len(VowelGarblers))]) } numCanGarble++ sequencePosition = (sequencePosition + 1) % len(sequence) continue } //no need to garble this character, just generate a random vowel/consonant if sequence[sequencePosition] == "c" { ret += string(Consonants[randInt(len(Consonants))]) } else { ret += string(Vowels[randInt(len(Vowels))]) } sequencePosition = (sequencePosition + 1) % len(sequence) } if numCanGarble >= numGarbled { return ret } //we've made even-numbered chars garbled, now start with the odd-numbered ones for i := 0; i < length; i++ { if i%2 == 1 && numCanGarble < numGarbled { //make things garblable if required: //make every other character garblable until we reach numGarblable if sequence[sequencePosition] == "c" { ret += string(ConsonantGarblers[randInt(len(ConsonantGarblers))]) } else { ret += string(VowelGarblers[randInt(len(VowelGarblers))]) } numCanGarble++ sequencePosition = (sequencePosition + 1) % len(sequence) } else if numCanGarble >= numGarbled { return ret } } //if we reach this point, something went horribly wrong panic("ouch") }
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/lexer/lexer.go#L80-L87
func Lex(xpath string) chan XItem { l := &Lexer{ input: xpath, items: make(chan XItem), } go l.run() return l.items }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/netutil/isolate_linux.go#L45-L67
func SetLatency(ms, rv int) error { ifces, err := GetDefaultInterfaces() if err != nil { return err } if rv > ms { rv = 1 } for ifce := range ifces { cmdStr := fmt.Sprintf("sudo tc qdisc add dev %s root netem delay %dms %dms distribution normal", ifce, ms, rv) _, err = exec.Command("/bin/sh", "-c", cmdStr).Output() if err != nil { // the rule has already been added. Overwrite it. cmdStr = fmt.Sprintf("sudo tc qdisc change dev %s root netem delay %dms %dms distribution normal", ifce, ms, rv) _, err = exec.Command("/bin/sh", "-c", cmdStr).Output() if err != nil { return err } } } return nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/auth/store.go#L1068-L1122
func NewAuthStore(lg *zap.Logger, be backend.Backend, tp TokenProvider, bcryptCost int) *authStore { if bcryptCost < bcrypt.MinCost || bcryptCost > bcrypt.MaxCost { if lg != nil { lg.Warn( "use default bcrypt cost instead of the invalid given cost", zap.Int("min-cost", bcrypt.MinCost), zap.Int("max-cost", bcrypt.MaxCost), zap.Int("default-cost", bcrypt.DefaultCost), zap.Int("given-cost", bcryptCost)) } else { plog.Warningf("Use default bcrypt-cost %d instead of the invalid value %d", bcrypt.DefaultCost, bcryptCost) } bcryptCost = bcrypt.DefaultCost } tx := be.BatchTx() tx.Lock() tx.UnsafeCreateBucket(authBucketName) tx.UnsafeCreateBucket(authUsersBucketName) tx.UnsafeCreateBucket(authRolesBucketName) enabled := false _, vs := tx.UnsafeRange(authBucketName, enableFlagKey, nil, 0) if len(vs) == 1 { if bytes.Equal(vs[0], authEnabled) { enabled = true } } as := &authStore{ revision: getRevision(tx), lg: lg, be: be, enabled: enabled, rangePermCache: make(map[string]*unifiedRangePermissions), tokenProvider: tp, bcryptCost: bcryptCost, } if enabled { as.tokenProvider.enable() } if as.Revision() == 0 { as.commitRevision(tx) } tx.Unlock() be.ForceCommit() return as }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/inmem_store.go#L107-L115
func (i *InmemStore) Get(key []byte) ([]byte, error) { i.l.RLock() defer i.l.RUnlock() val := i.kv[string(key)] if val == nil { return nil, errors.New("not found") } return val, nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/rawnode.go#L167-L183
func (rn *RawNode) ApplyConfChange(cc pb.ConfChange) *pb.ConfState { if cc.NodeID == None { return &pb.ConfState{Nodes: rn.raft.nodes(), Learners: rn.raft.learnerNodes()} } switch cc.Type { case pb.ConfChangeAddNode: rn.raft.addNode(cc.NodeID) case pb.ConfChangeAddLearnerNode: rn.raft.addLearner(cc.NodeID) case pb.ConfChangeRemoveNode: rn.raft.removeNode(cc.NodeID) case pb.ConfChangeUpdateNode: default: panic("unexpected conf type") } return &pb.ConfState{Nodes: rn.raft.nodes(), Learners: rn.raft.learnerNodes()} }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/region.go#L89-L94
func (r region) Uint16() uint16 { if r.typ.Kind != KindUint || r.typ.Size != 2 { panic("bad uint16 type " + r.typ.Name) } return r.p.proc.ReadUint16(r.a) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L563-L567
func (v SetScriptSourceReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDebugger5(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/alecthomas/mph/blob/cf7b0cd2d9579868ec2a49493fd62b2e28bcb336/chd.go#L61-L67
func Read(r io.Reader) (*CHD, error) { b, err := ioutil.ReadAll(r) if err != nil { return nil, err } return Mmap(b) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cron/cron.go#L176-L185
func (c *Cron) removeJob(name string) error { job, ok := c.jobs[name] if !ok { return fmt.Errorf("job %s has not been added to cronAgent yet", name) } c.cronAgent.Remove(job.entryID) delete(c.jobs, name) c.logger.Infof("Removed previous cron job %s.", name) return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/easyjson.go#L838-L842
func (v GetWindowBoundsParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoBrowser8(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L87-L89
func (api *API) AccountLocator(href string) *AccountLocator { return &AccountLocator{Href(href), api} }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/transaction.go#L241-L244
func (m MemoReturn) MutateTransaction(o *TransactionBuilder) (err error) { o.TX.Memo, err = xdr.NewMemo(xdr.MemoTypeMemoReturn, m.Value) return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L4042-L4046
func (v *EvaluateReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime37(&r, v) return r.Error() }
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L225-L238
func (s *MockSpan) logFieldsWithTimestamp(ts time.Time, fields ...log.Field) { lr := MockLogRecord{ Timestamp: ts, Fields: make([]MockKeyValue, len(fields)), } for i, f := range fields { outField := &(lr.Fields[i]) f.Marshal(outField) } s.Lock() defer s.Unlock() s.logs = append(s.logs, lr) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L4978-L4982
func (v *GetAllCookiesReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork38(&r, v) return r.Error() }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/tarfile/dest.go#L97-L158
func (d *Destination) PutBlob(ctx context.Context, stream io.Reader, inputInfo types.BlobInfo, cache types.BlobInfoCache, isConfig bool) (types.BlobInfo, error) { // Ouch, we need to stream the blob into a temporary file just to determine the size. // When the layer is decompressed, we also have to generate the digest on uncompressed datas. if inputInfo.Size == -1 || inputInfo.Digest.String() == "" { logrus.Debugf("docker tarfile: input with unknown size, streaming to disk first ...") streamCopy, err := ioutil.TempFile(tmpdir.TemporaryDirectoryForBigFiles(), "docker-tarfile-blob") if err != nil { return types.BlobInfo{}, err } defer os.Remove(streamCopy.Name()) defer streamCopy.Close() digester := digest.Canonical.Digester() tee := io.TeeReader(stream, digester.Hash()) // TODO: This can take quite some time, and should ideally be cancellable using ctx.Done(). size, err := io.Copy(streamCopy, tee) if err != nil { return types.BlobInfo{}, err } _, err = streamCopy.Seek(0, os.SEEK_SET) if err != nil { return types.BlobInfo{}, err } inputInfo.Size = size // inputInfo is a struct, so we are only modifying our copy. if inputInfo.Digest == "" { inputInfo.Digest = digester.Digest() } stream = streamCopy logrus.Debugf("... streaming done") } // Maybe the blob has been already sent ok, reusedInfo, err := d.TryReusingBlob(ctx, inputInfo, cache, false) if err != nil { return types.BlobInfo{}, err } if ok { return reusedInfo, nil } if isConfig { buf, err := ioutil.ReadAll(stream) if err != nil { return types.BlobInfo{}, errors.Wrap(err, "Error reading Config file stream") } d.config = buf if err := d.sendFile(inputInfo.Digest.Hex()+".json", inputInfo.Size, bytes.NewReader(buf)); err != nil { return types.BlobInfo{}, errors.Wrap(err, "Error writing Config file") } } else { // Note that this can't be e.g. filepath.Join(l.Digest.Hex(), legacyLayerFileName); due to the way // writeLegacyLayerMetadata constructs layer IDs differently from inputinfo.Digest values (as described // inside it), most of the layers would end up in subdirectories alone without any metadata; (docker load) // tries to load every subdirectory as an image and fails if the config is missing. So, keep the layers // in the root of the tarball. if err := d.sendFile(inputInfo.Digest.Hex()+".tar", inputInfo.Size, stream); err != nil { return types.BlobInfo{}, err } } d.blobs[inputInfo.Digest] = types.BlobInfo{Digest: inputInfo.Digest, Size: inputInfo.Size} return types.BlobInfo{Digest: inputInfo.Digest, Size: inputInfo.Size}, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L756-L759
func (p RunScriptParams) WithGeneratePreview(generatePreview bool) *RunScriptParams { p.GeneratePreview = generatePreview return &p }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/types.go#L333-L335
func (t *Type) UnmarshalJSON(buf []byte) error { return easyjson.Unmarshal(buf, t) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/easyjson.go#L1949-L1953
func (v *DatabaseWithObjectStores) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoIndexeddb17(&r, v) return r.Error() }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pod-utils/gcs/target.go#L40-L52
func PathForSpec(spec *downwardapi.JobSpec, pathSegment RepoPathBuilder) string { switch spec.Type { case prowapi.PeriodicJob, prowapi.PostsubmitJob: return path.Join(NonPRLogs, spec.Job, spec.BuildID) case prowapi.PresubmitJob: return path.Join(PRLogs, "pull", pathSegment(spec.Refs.Org, spec.Refs.Repo), strconv.Itoa(spec.Refs.Pulls[0].Number), spec.Job, spec.BuildID) case prowapi.BatchJob: return path.Join(PRLogs, "pull", "batch", spec.Job, spec.BuildID) default: logrus.Fatalf("unknown job spec type: %v", spec.Type) } return "" }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L471-L476
func GetResourceContent(frameID cdp.FrameID, url string) *GetResourceContentParams { return &GetResourceContentParams{ FrameID: frameID, URL: url, } }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/auth/auth.go#L36-L41
func WithTokenFunc(k string, tokenFunc func(v string) string) *TokenCredentials { return &TokenCredentials{ tokenFunc: tokenFunc, tokenFuncKey: k, } }
https://github.com/libp2p/go-libp2p-crypto/blob/9d2fed53443f745e6dc4d02bdcc94d9742a0ca84/secp256k1.go#L61-L63
func (k *Secp256k1PrivateKey) Raw() ([]byte, error) { return (*btcec.PrivateKey)(k).Serialize(), nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L5221-L5225
func (v CallFrame) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoRuntime48(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L296-L301
func (s *FileSequence) FrameRange() string { if s.frameSet == nil { return "" } return s.frameSet.FrameRange() }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/ledger_key.go#L78-L87
func (key *LedgerKey) SetTrustline(account AccountId, line Asset) error { data := LedgerKeyTrustLine{account, line} nkey, err := NewLedgerKey(LedgerEntryTypeTrustline, data) if err != nil { return err } *key = nkey return nil }