_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L363-L375
func GetByName(name string) (*App, error) { var app App conn, err := db.Conn() if err != nil { return nil, err } defer conn.Close() err = conn.Apps().Find(bson.M{"name": name}).One(&app) if err == mgo.ErrNotFound { return nil, appTypes.ErrAppNotFound } return &app, err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/easyjson.go#L1531-L1535
func (v *HideHighlightParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoOverlay14(&r, v) return r.Error() }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/catalog.go#L49-L59
func (c *Catalog) All() []Model { // prepare models models := make([]Model, 0, len(c.models)) // add models for _, model := range c.models { models = append(models, model) } return models }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/emulation.go#L481-L483
func (p *SetTouchEmulationEnabledParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetTouchEmulationEnabled, p, nil) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/praxisgen/action_analysis.go#L225-L238
func rawPayload(typ gen.DataType, p interface{}) *gen.ActionParam { var required bool if req, ok := p.(map[string]interface{})["required"]; ok { required = req.(bool) } return &gen.ActionParam{ Name: "payload", QueryName: "payload", VarName: "payload", Type: typ, Location: gen.PayloadParam, Mandatory: required, } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L335-L339
func (v Viewport) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage2(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/cmd/target.go#L246-L268
func WriteOnTargetList(label, target string) error { label = strings.TrimSpace(label) target = strings.TrimSpace(target) targetExist, err := CheckIfTargetLabelExists(label) if err != nil { return err } if targetExist { return errors.New("Target label provided already exists") } targetsPath := JoinWithUserDir(".tsuru", "targets") targetsFile, err := filesystem().OpenFile(targetsPath, syscall.O_RDWR|syscall.O_CREAT|syscall.O_APPEND, 0600) if err != nil { return err } defer targetsFile.Close() content := label + "\t" + target + "\n" n, err := targetsFile.WriteString(content) if n != len(content) || err != nil { return errors.New("Failed to write the target file") } return nil }
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nitro.go#L540-L546
func (s *Snapshot) Decode(buf []byte, r io.Reader) error { if _, err := io.ReadFull(r, buf[0:4]); err != nil { return err } s.sn = binary.BigEndian.Uint32(buf[0:4]) return nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L839-L845
func (c APIClient) NewPutFileClient() (PutFileClient, error) { pfc, err := c.PfsAPIClient.PutFile(c.Ctx()) if err != nil { return nil, grpcutil.ScrubGRPC(err) } return &putFileClient{c: pfc}, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/backgroundservice/backgroundservice.go#L82-L84
func (p *SetRecordingParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetRecording, p, nil) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L8470-L8474
func (v *CachedResource) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork66(&r, v) return r.Error() }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/tarfile/src.go#L190-L201
func (s *Source) readTarComponent(path string) ([]byte, error) { file, err := s.openTarComponent(path) if err != nil { return nil, errors.Wrapf(err, "Error loading tar component %s", path) } defer file.Close() bytes, err := ioutil.ReadAll(file) if err != nil { return nil, err } return bytes, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/idmap/shift_linux.go#L171-L183
func GetCaps(path string) ([]byte, error) { xattrs, err := shared.GetAllXattr(path) if err != nil { return nil, err } valueStr, ok := xattrs["security.capability"] if !ok { return nil, nil } return []byte(valueStr), nil }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_image_dest.go#L512-L527
func (c *dockerClient) deleteOneSignature(url *url.URL) (missing bool, err error) { switch url.Scheme { case "file": logrus.Debugf("Deleting %s", url.Path) err := os.Remove(url.Path) if err != nil && os.IsNotExist(err) { return true, nil } return false, err case "http", "https": return false, errors.Errorf("Writing directly to a %s sigstore %s is not supported. Configure a sigstore-staging: location", url.Scheme, url.String()) default: return false, errors.Errorf("Unsupported scheme when deleting signature from %s", url.String()) } }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/deck/main.go#L972-L1002
func handleLog(lc logClient) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { setHeadersNoCaching(w) w.Header().Set("Access-Control-Allow-Origin", "*") job := r.URL.Query().Get("job") id := r.URL.Query().Get("id") logger := logrus.WithFields(logrus.Fields{"job": job, "id": id}) if err := validateLogRequest(r); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } log, err := lc.GetJobLog(job, id) if err != nil { http.Error(w, fmt.Sprintf("Log not found: %v", err), http.StatusNotFound) logger := logger.WithError(err) msg := "Log not found." if strings.Contains(err.Error(), "PodInitializing") { // PodInitializing is really common and not something // that has any actionable items for administrators // monitoring logs, so we should log it as information logger.Info(msg) } else { logger.Warning(msg) } return } if _, err = w.Write(log); err != nil { logger.WithError(err).Warning("Error writing log.") } } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L58-L62
func (v StepOverParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDebugger(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L2384-L2388
func (v *ResumeParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger24(&r, v) return r.Error() }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/models.go#L74-L86
func (t *Token) Validate() error { // check id if !t.ID().Valid() { return fire.E("invalid id") } // check expires at if t.ExpiresAt.IsZero() { return fire.E("expires at not set") } return nil }
https://github.com/fgrid/uuid/blob/6f72a2d331c927473b9b19f590d43ccb5018c844/v3.go#L10-L14
func NewV3(namespace *UUID, name []byte) *UUID { uuid := newByHash(md5.New(), namespace, name) uuid[6] = (uuid[6] & 0x0f) | 0x30 return uuid }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/apps/patch_apps_app_responses.go#L25-L59
func (o *PatchAppsAppReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 200: result := NewPatchAppsAppOK() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil case 400: result := NewPatchAppsAppBadRequest() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 404: result := NewPatchAppsAppNotFound() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result default: result := NewPatchAppsAppDefault(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/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/indexeddb.go#L56-L61
func DeleteDatabase(securityOrigin string, databaseName string) *DeleteDatabaseParams { return &DeleteDatabaseParams{ SecurityOrigin: securityOrigin, DatabaseName: databaseName, } }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/manage_data.go#L10-L16
func ClearData(name string, muts ...interface{}) (result ManageDataBuilder) { result.MD.DataName = xdr.String64(name) result.MD.DataValue = nil result.validateName() result.Mutate(muts...) return }
https://github.com/r3labs/sse/blob/2f90368216802092e9ed520c43e974e11d50438d/client.go#L171-L173
func (c *Client) SubscribeRaw(handler func(msg *Event)) error { return c.Subscribe("", handler) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/blobinfocache/memory/memory.go#L49-L53
func (mem *cache) UncompressedDigest(anyDigest digest.Digest) digest.Digest { mem.mutex.Lock() defer mem.mutex.Unlock() return mem.uncompressedDigestLocked(anyDigest) }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxtype.go#L598-L600
func NewCvPoint2D32f(x, y float32) CvPoint2D32f { return CvPoint2D32f{C.float(x), C.float(y)} }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/contention/contention.go#L36-L41
func NewTimeoutDetector(maxDuration time.Duration) *TimeoutDetector { return &TimeoutDetector{ maxDuration: maxDuration, records: make(map[uint64]time.Time), } }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/reqres.go#L205-L207
func (r *reqResReader) arg3Reader() (ArgReader, error) { return r.argReader(true /* last */, reqResReaderPreArg3, reqResReaderComplete) }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/file_snapshot.go#L110-L115
func NewFileSnapshotStore(base string, retain int, logOutput io.Writer) (*FileSnapshotStore, error) { if logOutput == nil { logOutput = os.Stderr } return NewFileSnapshotStoreWithLogger(base, retain, log.New(logOutput, "", log.LstdFlags)) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L417-L426
func (p *GetContentQuadsParams) Do(ctx context.Context) (quads []Quad, err error) { // execute var res GetContentQuadsReturns err = cdp.Execute(ctx, CommandGetContentQuads, p, &res) if err != nil { return nil, err } return res.Quads, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/genfiles/genfiles.go#L109-L148
func (g *Group) load(r io.Reader) ([]string, error) { var repoPaths []string s := bufio.NewScanner(r) for s.Scan() { l := strings.TrimSpace(s.Text()) if l == "" || l[0] == '#' { // Ignore comments and empty lines. continue } fs := strings.Fields(l) if len(fs) != 2 { return repoPaths, &ParseError{line: l} } switch fs[0] { case "prefix", "path-prefix": g.PathPrefixes[fs[1]] = true case "file-prefix": g.FilePrefixes[fs[1]] = true case "file-name": g.FileNames[fs[1]] = true case "path": g.FileNames[fs[1]] = true case "paths-from-repo": // Despite the name, this command actually requires a file // of paths from the _same_ repo in which the .generated_files // config lives. repoPaths = append(repoPaths, fs[1]) default: return repoPaths, &ParseError{line: l} } } if err := s.Err(); err != nil { return repoPaths, err } return repoPaths, nil }
https://github.com/geoffgarside/ber/blob/27a1aff36ce64dbe5d93c08cc5f161983134ddc5/common.go#L109-L141
func getUniversalType(t reflect.Type) (tagNumber int, isCompound, ok bool) { switch t { case objectIdentifierType: return tagOID, false, true case bitStringType: return tagBitString, false, true case timeType: return tagUTCTime, false, true case enumeratedType: return tagEnum, false, true case bigIntType: return tagInteger, false, true } switch t.Kind() { case reflect.Bool: return tagBoolean, false, true case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return tagInteger, false, true case reflect.Struct: return tagSequence, true, true case reflect.Slice: if t.Elem().Kind() == reflect.Uint8 { return tagOctetString, false, true } if strings.HasSuffix(t.Name(), "SET") { return tagSet, true, true } return tagSequence, true, true case reflect.String: return tagPrintableString, false, true } return 0, false, false }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L106-L109
func (p CallFunctionOnParams) WithObjectID(objectID RemoteObjectID) *CallFunctionOnParams { p.ObjectID = objectID return &p }
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/english/common.go#L247-L277
func endsShortSyllable(w *snowballword.SnowballWord, i int) bool { if i == 2 { // Check for a vowel at the beginning of the word followed by a non-vowel. if isLowerVowel(w.RS[0]) && !isLowerVowel(w.RS[1]) { return true } else { return false } } else if i >= 3 { // The runes 1, 2, & 3 positions to the left of `i`. s1 := w.RS[i-1] s2 := w.RS[i-2] s3 := w.RS[i-3] // Check for a vowel followed by a non-vowel other than w, x or Y // and preceded by a non-vowel. // (Note: w, x, Y rune codepoints = 119, 120, 89) // if !isLowerVowel(s1) && s1 != 119 && s1 != 120 && s1 != 89 && isLowerVowel(s2) && !isLowerVowel(s3) { return true } else { return false } } return false }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tracing/easyjson.go#L592-L596
func (v RecordClockSyncMarkerParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoTracing4(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/offsets.go#L55-L57
func (s *OffsetStash) ResetOffset(msg *sarama.ConsumerMessage, metadata string) { s.ResetPartitionOffset(msg.Topic, msg.Partition, msg.Offset, metadata) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/trigger/generic-comment.go#L168-L182
func determineSkippedPresubmits(toTrigger, toSkipSuperset []config.Presubmit, logger *logrus.Entry) []config.Presubmit { triggeredContexts := sets.NewString() for _, presubmit := range toTrigger { triggeredContexts.Insert(presubmit.Context) } var toSkip []config.Presubmit for _, presubmit := range toSkipSuperset { if triggeredContexts.Has(presubmit.Context) { logger.WithFields(logrus.Fields{"context": presubmit.Context, "job": presubmit.Name}).Debug("Not skipping job as context will be created by a triggered job.") continue } toSkip = append(toSkip, presubmit) } return toSkip }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/spyglass/gcsartifact_fetcher.go#L107-L143
func (af *GCSArtifactFetcher) artifacts(key string) ([]string, error) { src, err := newGCSJobSource(key) if err != nil { return nil, fmt.Errorf("Failed to get GCS job source from %s: %v", key, err) } listStart := time.Now() bucketName, prefix := extractBucketPrefixPair(src.jobPath()) artifacts := []string{} bkt := af.client.Bucket(bucketName) q := storage.Query{ Prefix: prefix, Versions: false, } objIter := bkt.Objects(context.Background(), &q) wait := []time.Duration{16, 32, 64, 128, 256, 256, 512, 512} for i := 0; ; { oAttrs, err := objIter.Next() if err == iterator.Done { break } if err != nil { logrus.WithFields(fieldsForJob(src)).WithError(err).Error("Error accessing GCS artifact.") if i >= len(wait) { return artifacts, fmt.Errorf("timed out: error accessing GCS artifact: %v", err) } time.Sleep((wait[i] + time.Duration(rand.Intn(10))) * time.Millisecond) i++ continue } artifacts = append(artifacts, strings.TrimPrefix(oAttrs.Name, prefix)) i = 0 } listElapsed := time.Since(listStart) logrus.WithField("duration", listElapsed).Infof("Listed %d artifacts.", len(artifacts)) return artifacts, nil }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/render/template.go#L56-L64
func (s templateRenderer) partialFeeder(name string) (string, error) { ct := strings.ToLower(s.contentType) d, f := filepath.Split(name) name = filepath.Join(d, "_"+f) name = fixExtension(name, ct) return s.TemplatesBox.FindString(name) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5889-L5901
func NewTransactionMeta(v int32, value interface{}) (result TransactionMeta, err error) { result.V = v switch int32(v) { case 0: tv, ok := value.([]OperationMeta) if !ok { err = fmt.Errorf("invalid value, must be []OperationMeta") return } result.Operations = &tv } return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/easyjson.go#L740-L744
func (v *ObjectStoreIndex) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoIndexeddb6(&r, v) return r.Error() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/heartbeat.go#L26-L152
func Heartbeat(gateway *Gateway, cluster *db.Cluster) (task.Func, task.Schedule) { heartbeat := func(ctx context.Context) { if gateway.server == nil || gateway.memoryDial != nil { // We're not a raft node or we're not clustered return } raftNodes, err := gateway.currentRaftNodes() if err == raft.ErrNotLeader { return } logger.Debugf("Starting heartbeat round") if err != nil { logger.Warnf("Failed to get current raft nodes: %v", err) return } // Replace the local raft_nodes table immediately because it // might miss a row containing ourselves, since we might have // been elected leader before the former leader had chance to // send us a fresh update through the heartbeat pool. logger.Debugf("Heartbeat updating local raft nodes to %+v", raftNodes) err = gateway.db.Transaction(func(tx *db.NodeTx) error { return tx.RaftNodesReplace(raftNodes) }) if err != nil { logger.Warnf("Failed to replace local raft nodes: %v", err) return } var nodes []db.NodeInfo var nodeAddress string // Address of this node err = cluster.Transaction(func(tx *db.ClusterTx) error { var err error nodes, err = tx.Nodes() if err != nil { return err } nodeAddress, err = tx.NodeAddress() if err != nil { return err } return nil }) if err != nil { logger.Warnf("Failed to get current cluster nodes: %v", err) return } heartbeats := make([]time.Time, len(nodes)) heartbeatsLock := sync.Mutex{} heartbeatsWg := sync.WaitGroup{} for i, node := range nodes { // Special case the local node if node.Address == nodeAddress { heartbeatsLock.Lock() heartbeats[i] = time.Now() heartbeatsLock.Unlock() continue } // Parallelize the rest heartbeatsWg.Add(1) go func(i int, address string) { defer heartbeatsWg.Done() // Spread in time by waiting up to 3s less than the interval time.Sleep(time.Duration(rand.Intn((heartbeatInterval*1000)-3000)) * time.Millisecond) logger.Debugf("Sending heartbeat to %s", address) err := heartbeatNode(ctx, address, gateway.cert, raftNodes) if err == nil { heartbeatsLock.Lock() heartbeats[i] = time.Now() heartbeatsLock.Unlock() logger.Debugf("Successful heartbeat for %s", address) } else { logger.Debugf("Failed heartbeat for %s: %v", address, err) } }(i, node.Address) } heartbeatsWg.Wait() // If the context has been cancelled, return immediately. if ctx.Err() != nil { logger.Debugf("Aborting heartbeat round") return } err = cluster.Transaction(func(tx *db.ClusterTx) error { for i, node := range nodes { if heartbeats[i].Equal(time.Time{}) { continue } err := tx.NodeHeartbeat(node.Address, heartbeats[i]) if err != nil { return err } } return nil }) if err != nil { logger.Warnf("Failed to update heartbeat: %v", err) } logger.Debugf("Completed heartbeat round") } // Since the database APIs are blocking we need to wrap the core logic // and run it in a goroutine, so we can abort as soon as the context expires. heartbeatWrapper := func(ctx context.Context) { ch := make(chan struct{}) go func() { heartbeat(ctx) ch <- struct{}{} }() select { case <-ch: case <-ctx.Done(): } } schedule := task.Every(time.Duration(heartbeatInterval) * time.Second) return heartbeatWrapper, schedule }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/operations.go#L303-L316
func (c *ClusterTx) OperationRemove(uuid string) error { result, err := c.tx.Exec("DELETE FROM operations WHERE uuid=?", uuid) if err != nil { return err } n, err := result.RowsAffected() if err != nil { return err } if n != 1 { return fmt.Errorf("query deleted %d rows instead of 1", n) } return nil }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L82-L88
func NewPolicyFromBytes(data []byte) (*Policy, error) { p := Policy{} if err := json.Unmarshal(data, &p); err != nil { return nil, InvalidPolicyFormatError(err.Error()) } return &p, nil }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/net_transport.go#L649-L668
func sendRPC(conn *netConn, rpcType uint8, args interface{}) error { // Write the request type if err := conn.w.WriteByte(rpcType); err != nil { conn.Release() return err } // Send the request if err := conn.enc.Encode(args); err != nil { conn.Release() return err } // Flush if err := conn.w.Flush(); err != nil { conn.Release() return err } return nil }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/render/sse.go#L64-L77
func NewEventSource(w http.ResponseWriter) (*EventSource, error) { es := &EventSource{w: w} var ok bool es.fl, ok = w.(http.Flusher) if !ok { return es, errors.New("streaming is not supported") } es.w.Header().Set("Content-Type", "text/event-stream") es.w.Header().Set("Cache-Control", "no-cache") es.w.Header().Set("Connection", "keep-alive") es.w.Header().Set("Access-Control-Allow-Origin", "*") return es, nil }
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cmd/deploycontroller.go#L31-L66
func DeployControllerCmd() *cobra.Command { var dco = &cli.DeployControllerOptions{} var deployControllerCmd = &cobra.Command{ Use: "deploycontroller <NAME>", Short: "Deploy a controller for a given cluster", Long: `Use this command to deploy a controller for a given cluster. As long as a controller is defined, this will create the deployment and the namespace.`, Run: func(cmd *cobra.Command, args []string) { switch len(args) { case 0: dco.Name = viper.GetString(keyKubicornName) case 1: dco.Name = args[0] default: logger.Critical("Too many arguments.") os.Exit(1) } if err := runDeployController(dco); err != nil { logger.Critical(err.Error()) os.Exit(1) } }, } fs := deployControllerCmd.Flags() bindCommonStateStoreFlags(&dco.StateStoreOptions, fs) bindCommonAwsFlags(&dco.AwsOptions, fs) fs.StringVar(&dco.GitRemote, keyGitConfig, viper.GetString(keyGitConfig), descGitConfig) return deployControllerCmd }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/data_types.go#L220-L227
func (a *Action) HasOptionalParams() bool { for _, param := range a.Params { if !param.Mandatory { return true } } return false }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/db.go#L49-L96
func OpenNode(dir string, fresh func(*Node) error, legacyPatches map[int]*LegacyPatch) (*Node, *Dump, error) { // When updating the node database schema we'll detect if we're // transitioning to the dqlite-based database and dump all the data // before purging the schema. This data will be then imported by the // daemon into the dqlite database. var dump *Dump db, err := node.Open(dir) if err != nil { return nil, nil, err } legacyHook := legacyPatchHook(db, legacyPatches) hook := func(version int, tx *sql.Tx) error { if version == node.UpdateFromPreClustering { logger.Debug("Loading pre-clustering sqlite data") var err error dump, err = LoadPreClusteringData(tx) if err != nil { return err } } return legacyHook(version, tx) } initial, err := node.EnsureSchema(db, dir, hook) if err != nil { return nil, nil, err } node := &Node{ db: db, dir: dir, } if initial == 0 { if fresh != nil { err := fresh(node) if err != nil { return nil, nil, err } } } db.SetMaxOpenConns(1) db.SetMaxIdleConns(1) return node, dump, nil }
https://github.com/kelseyhightower/envconfig/blob/dd1402a4d99de9ac2f396cd6fcb957bc2c695ec1/envconfig.go#L179-L219
func Process(prefix string, spec interface{}) error { infos, err := gatherInfo(prefix, spec) for _, info := range infos { // `os.Getenv` cannot differentiate between an explicitly set empty value // and an unset value. `os.LookupEnv` is preferred to `syscall.Getenv`, // but it is only available in go1.5 or newer. We're using Go build tags // here to use os.LookupEnv for >=go1.5 value, ok := lookupEnv(info.Key) if !ok && info.Alt != "" { value, ok = lookupEnv(info.Alt) } def := info.Tags.Get("default") if def != "" && !ok { value = def } req := info.Tags.Get("required") if !ok && def == "" { if isTrue(req) { return fmt.Errorf("required key %s missing value", info.Key) } continue } err = processField(value, info.Field) if err != nil { return &ParseError{ KeyName: info.Key, FieldName: info.Name, TypeName: info.Field.Type().String(), Value: value, Err: err, } } } return err }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vm.go#L1628-L1652
func (v *VM) RevertToSnapshot(snapshot *Snapshot, options VMPowerOption) error { var jobHandle C.VixHandle = C.VIX_INVALID_HANDLE var err C.VixError = C.VIX_OK jobHandle = C.VixVM_RevertToSnapshot(v.handle, snapshot.handle, 0, // options C.VIX_INVALID_HANDLE, // propertyListHandle nil, // callbackProc nil) // clientData defer C.Vix_ReleaseHandle(jobHandle) err = C.vix_job_wait(jobHandle) if C.VIX_OK != err { return &Error{ Operation: "vm.RevertToSnapshot", Code: int(err & 0xFFFF), Text: C.GoString(C.Vix_GetErrorText(err, nil)), } } return nil }
https://github.com/go-openapi/loads/blob/74628589c3b94e3526a842d24f46589980f5ab22/spec.go#L115-L152
func Spec(path string) (*Document, error) { specURL, err := url.Parse(path) if err != nil { return nil, err } var lastErr error for l := loaders.Next; l != nil; l = l.Next { if loaders.Match(specURL.Path) { b, err2 := loaders.Fn(path) if err2 != nil { lastErr = err2 continue } doc, err3 := Analyzed(b, "") if err3 != nil { return nil, err3 } if doc != nil { doc.specFilePath = path } return doc, nil } } if lastErr != nil { return nil, lastErr } b, err := defaultLoader.Fn(path) if err != nil { return nil, err } document, err := Analyzed(b, "") if document != nil { document.specFilePath = path } return document, err }
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/service/lease.go#L85-L104
func (s *Lease) Procurement() (skuTask *taskmanager.Task) { if skuConstructor, ok := s.availableSkus[s.Sku]; ok { leaseMap := structs.Map(s) sku := skuConstructor.New(s.taskManager, leaseMap) GLogger.Println("here is my sku: ", sku) skuTask = sku.Procurement() tt := skuTask.Read(func(t *taskmanager.Task) interface{} { tt := *t return tt }) GLogger.Println("here is my task after procurement: ", tt) s.Task = skuTask.GetRedactedVersion() } else { GLogger.Println("No Sku Match: ", s.Sku, s.availableSkus) s.Task.Status = TaskStatusUnavailable } return }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_pools.go#L1013-L1033
func (c *Cluster) StoragePoolVolumeGetTypeID(project string, volumeName string, volumeType int, poolID, nodeID int64) (int64, error) { volumeID := int64(-1) query := `SELECT storage_volumes.id FROM storage_volumes JOIN storage_pools ON storage_volumes.storage_pool_id = storage_pools.id JOIN projects ON storage_volumes.project_id = projects.id WHERE projects.name=? AND storage_volumes.storage_pool_id=? AND storage_volumes.node_id=? AND storage_volumes.name=? AND storage_volumes.type=?` inargs := []interface{}{project, poolID, nodeID, volumeName, volumeType} outargs := []interface{}{&volumeID} err := dbQueryRowScan(c.db, query, inargs, outargs) if err != nil { if err == sql.ErrNoRows { return -1, ErrNoSuchObject } return -1, err } return volumeID, nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/adt/interval_tree.go#L479-L486
func (ivt *IntervalTree) Stab(iv Interval) (ivs []*IntervalValue) { if ivt.count == 0 { return nil } f := func(n *IntervalValue) bool { ivs = append(ivs, n); return true } ivt.Visit(iv, f) return ivs }
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/internal/diff/diff.go#L129-L294
func Difference(nx, ny int, f EqualFunc) (es EditScript) { // This algorithm is based on traversing what is known as an "edit-graph". // See Figure 1 from "An O(ND) Difference Algorithm and Its Variations" // by Eugene W. Myers. Since D can be as large as N itself, this is // effectively O(N^2). Unlike the algorithm from that paper, we are not // interested in the optimal path, but at least some "decent" path. // // For example, let X and Y be lists of symbols: // X = [A B C A B B A] // Y = [C B A B A C] // // The edit-graph can be drawn as the following: // A B C A B B A // ┌─────────────┐ // C │_|_|\|_|_|_|_│ 0 // B │_|\|_|_|\|\|_│ 1 // A │\|_|_|\|_|_|\│ 2 // B │_|\|_|_|\|\|_│ 3 // A │\|_|_|\|_|_|\│ 4 // C │ | |\| | | | │ 5 // └─────────────┘ 6 // 0 1 2 3 4 5 6 7 // // List X is written along the horizontal axis, while list Y is written // along the vertical axis. At any point on this grid, if the symbol in // list X matches the corresponding symbol in list Y, then a '\' is drawn. // The goal of any minimal edit-script algorithm is to find a path from the // top-left corner to the bottom-right corner, while traveling through the // fewest horizontal or vertical edges. // A horizontal edge is equivalent to inserting a symbol from list X. // A vertical edge is equivalent to inserting a symbol from list Y. // A diagonal edge is equivalent to a matching symbol between both X and Y. // Invariants: // • 0 ≤ fwdPath.X ≤ (fwdFrontier.X, revFrontier.X) ≤ revPath.X ≤ nx // • 0 ≤ fwdPath.Y ≤ (fwdFrontier.Y, revFrontier.Y) ≤ revPath.Y ≤ ny // // In general: // • fwdFrontier.X < revFrontier.X // • fwdFrontier.Y < revFrontier.Y // Unless, it is time for the algorithm to terminate. fwdPath := path{+1, point{0, 0}, make(EditScript, 0, (nx+ny)/2)} revPath := path{-1, point{nx, ny}, make(EditScript, 0)} fwdFrontier := fwdPath.point // Forward search frontier revFrontier := revPath.point // Reverse search frontier // Search budget bounds the cost of searching for better paths. // The longest sequence of non-matching symbols that can be tolerated is // approximately the square-root of the search budget. searchBudget := 4 * (nx + ny) // O(n) // The algorithm below is a greedy, meet-in-the-middle algorithm for // computing sub-optimal edit-scripts between two lists. // // The algorithm is approximately as follows: // • Searching for differences switches back-and-forth between // a search that starts at the beginning (the top-left corner), and // a search that starts at the end (the bottom-right corner). The goal of // the search is connect with the search from the opposite corner. // • As we search, we build a path in a greedy manner, where the first // match seen is added to the path (this is sub-optimal, but provides a // decent result in practice). When matches are found, we try the next pair // of symbols in the lists and follow all matches as far as possible. // • When searching for matches, we search along a diagonal going through // through the "frontier" point. If no matches are found, we advance the // frontier towards the opposite corner. // • This algorithm terminates when either the X coordinates or the // Y coordinates of the forward and reverse frontier points ever intersect. // // This algorithm is correct even if searching only in the forward direction // or in the reverse direction. We do both because it is commonly observed // that two lists commonly differ because elements were added to the front // or end of the other list. // // Running the tests with the "cmp_debug" build tag prints a visualization // of the algorithm running in real-time. This is educational for // understanding how the algorithm works. See debug_enable.go. f = debug.Begin(nx, ny, f, &fwdPath.es, &revPath.es) for { // Forward search from the beginning. if fwdFrontier.X >= revFrontier.X || fwdFrontier.Y >= revFrontier.Y || searchBudget == 0 { break } for stop1, stop2, i := false, false, 0; !(stop1 && stop2) && searchBudget > 0; i++ { // Search in a diagonal pattern for a match. z := zigzag(i) p := point{fwdFrontier.X + z, fwdFrontier.Y - z} switch { case p.X >= revPath.X || p.Y < fwdPath.Y: stop1 = true // Hit top-right corner case p.Y >= revPath.Y || p.X < fwdPath.X: stop2 = true // Hit bottom-left corner case f(p.X, p.Y).Equal(): // Match found, so connect the path to this point. fwdPath.connect(p, f) fwdPath.append(Identity) // Follow sequence of matches as far as possible. for fwdPath.X < revPath.X && fwdPath.Y < revPath.Y { if !f(fwdPath.X, fwdPath.Y).Equal() { break } fwdPath.append(Identity) } fwdFrontier = fwdPath.point stop1, stop2 = true, true default: searchBudget-- // Match not found } debug.Update() } // Advance the frontier towards reverse point. if revPath.X-fwdFrontier.X >= revPath.Y-fwdFrontier.Y { fwdFrontier.X++ } else { fwdFrontier.Y++ } // Reverse search from the end. if fwdFrontier.X >= revFrontier.X || fwdFrontier.Y >= revFrontier.Y || searchBudget == 0 { break } for stop1, stop2, i := false, false, 0; !(stop1 && stop2) && searchBudget > 0; i++ { // Search in a diagonal pattern for a match. z := zigzag(i) p := point{revFrontier.X - z, revFrontier.Y + z} switch { case fwdPath.X >= p.X || revPath.Y < p.Y: stop1 = true // Hit bottom-left corner case fwdPath.Y >= p.Y || revPath.X < p.X: stop2 = true // Hit top-right corner case f(p.X-1, p.Y-1).Equal(): // Match found, so connect the path to this point. revPath.connect(p, f) revPath.append(Identity) // Follow sequence of matches as far as possible. for fwdPath.X < revPath.X && fwdPath.Y < revPath.Y { if !f(revPath.X-1, revPath.Y-1).Equal() { break } revPath.append(Identity) } revFrontier = revPath.point stop1, stop2 = true, true default: searchBudget-- // Match not found } debug.Update() } // Advance the frontier towards forward point. if revFrontier.X-fwdPath.X >= revFrontier.Y-fwdPath.Y { revFrontier.X-- } else { revFrontier.Y-- } } // Join the forward and reverse paths and then append the reverse path. fwdPath.connect(revPath.point, f) for i := len(revPath.es) - 1; i >= 0; i-- { t := revPath.es[i] revPath.es = revPath.es[:i] fwdPath.append(t) } debug.Finish() return fwdPath.es }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/easyjson.go#L69-L73
func (v *empty) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdproto(&r, v) return r.Error() }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/check.go#L269-L283
func NewCheckDatascaleCommand() *cobra.Command { cmd := &cobra.Command{ Use: "datascale [options]", Short: "Check the memory usage of holding data for different workloads on a given server endpoint.", Long: "If no endpoint is provided, localhost will be used. If multiple endpoints are provided, first endpoint will be used.", Run: newCheckDatascaleCommand, } cmd.Flags().StringVar(&checkDatascaleLoad, "load", "s", "The datascale check's workload model. Accepted workloads: s(small), m(medium), l(large), xl(xLarge)") cmd.Flags().StringVar(&checkDatascalePrefix, "prefix", "/etcdctl-check-datascale/", "The prefix for writing the datascale check's keys.") cmd.Flags().BoolVar(&autoCompact, "auto-compact", false, "Compact storage with last revision after test is finished.") cmd.Flags().BoolVar(&autoDefrag, "auto-defrag", false, "Defragment storage after test is finished.") return cmd }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cachestorage/easyjson.go#L727-L731
func (v *Header) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoCachestorage6(&r, v) return r.Error() }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L461-L466
func (p *Peer) canRemove() bool { p.RLock() count := len(p.inboundConnections) + len(p.outboundConnections) + int(p.scCount) p.RUnlock() return count == 0 }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/gerrit/adapter/trigger.go#L30-L52
func messageFilter(lastUpdate time.Time, change client.ChangeInfo, presubmits []config.Presubmit) (pjutil.Filter, error) { var filters []pjutil.Filter currentRevision := change.Revisions[change.CurrentRevision].Number for _, message := range change.Messages { messageTime := message.Date.Time if message.RevisionNumber != currentRevision || !messageTime.After(lastUpdate) { continue } if !pjutil.TestAllRe.MatchString(message.Message) { for _, presubmit := range presubmits { if presubmit.TriggerMatches(message.Message) { logrus.Infof("Change %d: Comment %s matches triggering regex, for %s.", change.Number, message.Message, presubmit.Name) filters = append(filters, pjutil.CommandFilter(message.Message)) } } } else { filters = append(filters, pjutil.TestAllFilter()) } } return pjutil.AggregateFilter(filters), nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/tide.go#L143-L156
func (t *Tide) MergeMethod(org, repo string) github.PullRequestMergeType { name := org + "/" + repo v, ok := t.MergeType[name] if !ok { if ov, found := t.MergeType[org]; found { return ov } return github.MergeMerge } return v }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/hook/events.go#L357-L368
func genericCommentAction(action string) github.GenericCommentEventAction { switch action { case "created", "opened", "submitted": return github.GenericCommentActionCreated case "edited": return github.GenericCommentActionEdited case "deleted", "dismissed": return github.GenericCommentActionDeleted } // The action is not related to the text body. return "" }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/fileseq.go#L89-L171
func FramesToFrameRange(frames []int, sorted bool, zfill int) string { count := len(frames) if count == 0 { return "" } if count == 1 { return zfillInt(frames[0], zfill) } if sorted { sort.Ints(frames) } var i, frame, step int var start, end string var buf strings.Builder // Keep looping until all frames are consumed for len(frames) > 0 { count = len(frames) // If we get to the last element, just write it // and end if count <= 2 { for _, frame = range frames { if buf.Len() > 0 { buf.WriteString(",") } buf.WriteString(zfillInt(frame, zfill)) } break } // At this point, we have 3 or more frames to check. // Scan the current window of the slice to see how // many frames we can consume into a group step = frames[1] - frames[0] for i = 0; i < len(frames)-1; i++ { // We have scanned as many frames as we can // for this group. Now write them and stop // looping on this window if (frames[i+1] - frames[i]) != step { break } } // Subsequent groups are comma-separated if buf.Len() > 0 { buf.WriteString(",") } // We only have a single frame to write for this group if i == 0 { buf.WriteString(zfillInt(frames[0], zfill)) frames = frames[1:] continue } // First do a check to see if we could have gotten a larger range // out of subsequent values with a different step size if i == 1 && count > 3 { // Check if the next two pairwise frames have the same step. // If so, then it is better than our current grouping. if (frames[2] - frames[1]) == (frames[3] - frames[2]) { // Just consume the first frame, and allow the next // loop to scan the new stepping buf.WriteString(zfillInt(frames[0], zfill)) frames = frames[1:] continue } } // Otherwise write out this step range start = zfillInt(frames[0], zfill) end = zfillInt(frames[i], zfill) buf.WriteString(fmt.Sprintf("%s-%s", start, end)) if step > 1 { buf.WriteString(fmt.Sprintf("x%d", step)) } frames = frames[i+1:] } return buf.String() }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/metadata/action.go#L133-L153
func (p *PathPattern) Substitute(vars []*PathVariable) (string, []string) { values := make([]interface{}, len(p.Variables)) var missing []string var used []string for i, n := range p.Variables { for _, v := range vars { if v.Name == n { values[i] = v.Value used = append(used, n) break } } if values[i] == nil { missing = append(missing, n) } } if len(missing) > 0 { return "", missing } return fmt.Sprintf(p.Pattern, values...), used }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/network.go#L350-L368
func (v *VM) RemoveAllNetworkAdapters() error { vmxPath, err := v.VmxPath() if err != nil { return err } vmx, err := readVmx(vmxPath) if err != nil { return err } for key := range vmx { if strings.HasPrefix(key, "ethernet") { delete(vmx, key) } } return writeVmx(vmxPath, vmx) }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/thrift/context.go#L34-L37
func NewContext(timeout time.Duration) (Context, context.CancelFunc) { ctx, cancel := tchannel.NewContext(timeout) return Wrap(ctx), cancel }
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/figtree.go#L547-L589
func (m *Merger) setSource(v reflect.Value) { if v.Kind() == reflect.Ptr { v = v.Elem() } switch v.Kind() { case reflect.Map: for _, key := range v.MapKeys() { keyval := v.MapIndex(key) if keyval.Kind() == reflect.Struct && keyval.FieldByName("Source").IsValid() { // map values are immutable, so we need to copy the value // update the value, then re-insert the value to the map newval := reflect.New(keyval.Type()) newval.Elem().Set(keyval) m.setSource(newval) v.SetMapIndex(key, newval.Elem()) } } case reflect.Struct: if v.CanAddr() { if option, ok := v.Addr().Interface().(option); ok { if option.IsDefined() { option.SetSource(m.sourceFile) } return } } for i := 0; i < v.NumField(); i++ { structField := v.Type().Field(i) // PkgPath is empty for upper case (exported) field names. if structField.PkgPath != "" { // unexported field, skipping continue } m.setSource(v.Field(i)) } case reflect.Array: fallthrough case reflect.Slice: for i := 0; i < v.Len(); i++ { m.setSource(v.Index(i)) } } }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/sysregistriesv2/system_registries_v2.go#L356-L374
func refMatchesPrefix(ref, prefix string) bool { switch { case len(ref) < len(prefix): return false case len(ref) == len(prefix): return ref == prefix case len(ref) > len(prefix): if !strings.HasPrefix(ref, prefix) { return false } c := ref[len(prefix)] // This allows "example.com:5000" to match "example.com", // which is unintended; that will get fixed eventually, DON'T RELY // ON THE CURRENT BEHAVIOR. return c == ':' || c == '/' || c == '@' default: panic("Internal error: impossible comparison outcome") } }
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/tree.go#L186-L221
func FindNodeByPos(n Node, pos int) Node { if n.Pos() == pos { return n } if elem, ok := n.(Elem); ok { chldrn := elem.GetChildren() for i := 1; i < len(chldrn); i++ { if chldrn[i-1].Pos() <= pos && chldrn[i].Pos() > pos { return FindNodeByPos(chldrn[i-1], pos) } } if len(chldrn) > 0 { if chldrn[len(chldrn)-1].Pos() <= pos { return FindNodeByPos(chldrn[len(chldrn)-1], pos) } } attrs := elem.GetAttrs() for _, i := range attrs { if i.Pos() == pos { return i } } ns := BuildNS(elem) for _, i := range ns { if i.Pos() == pos { return i } } } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L1236-L1240
func (v EventTargetInfoChanged) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoTarget13(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/log/field.go#L41-L47
func String(key, val string) Field { return Field{ key: key, fieldType: stringType, stringVal: val, } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/watcher_hub.go#L48-L53
func newWatchHub(capacity int) *watcherHub { return &watcherHub{ watchers: make(map[string]*list.List), EventHistory: newEventHistory(capacity), } }
https://github.com/gravitational/roundtrip/blob/e1e0cd6b05a6bb1791b262e63160038828fd7b3a/client.go#L231-L253
func (c *Client) PostJSON(ctx context.Context, endpoint string, data interface{}) (*Response, error) { // If the sanitizer is enabled, make sure the requested path is safe. if c.sanitizerEnabled { err := isPathSafe(endpoint) if err != nil { return nil, err } } tracer := c.newTracer() return tracer.Done(c.RoundTrip(func() (*http.Response, error) { data, err := json.Marshal(data) req, err := http.NewRequest(http.MethodPost, endpoint, bytes.NewBuffer(data)) if err != nil { return nil, err } req = req.WithContext(ctx) req.Header.Set("Content-Type", "application/json") c.addAuth(req) tracer.Start(req) return c.client.Do(req) })) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/easyjson.go#L388-L392
func (v *SetTouchEmulationEnabledParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoEmulation3(&r, v) return r.Error() }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L1991-L2000
func (u OperationBody) GetChangeTrustOp() (result ChangeTrustOp, ok bool) { armName, _ := u.ArmForSwitch(int32(u.Type)) if armName == "ChangeTrustOp" { result = *u.ChangeTrustOp ok = true } return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L1881-L1885
func (v *PositionTickInfo) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoProfiler18(&r, v) return r.Error() }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/server/driver.go#L979-L1038
func (d *driver) inspectCommit(pachClient *client.APIClient, commit *pfs.Commit, blockState pfs.CommitState) (*pfs.CommitInfo, error) { ctx := pachClient.Ctx() if commit == nil { return nil, fmt.Errorf("cannot inspect nil commit") } if err := d.checkIsAuthorized(pachClient, commit.Repo, auth.Scope_READER); err != nil { return nil, err } // Check if the commitID is a branch name var commitInfo *pfs.CommitInfo if _, err := col.NewSTM(ctx, d.etcdClient, func(stm col.STM) error { var err error commitInfo, err = d.resolveCommit(stm, commit) return err }); err != nil { return nil, err } commits := d.commits(commit.Repo.Name).ReadOnly(ctx) if blockState == pfs.CommitState_READY { // Wait for each provenant commit to be finished for _, p := range commitInfo.Provenance { d.inspectCommit(pachClient, p.Commit, pfs.CommitState_FINISHED) } } if blockState == pfs.CommitState_FINISHED { // Watch the CommitInfo until the commit has been finished if err := func() error { commitInfoWatcher, err := commits.WatchOne(commit.ID) if err != nil { return err } defer commitInfoWatcher.Close() for { var commitID string _commitInfo := new(pfs.CommitInfo) event := <-commitInfoWatcher.Watch() switch event.Type { case watch.EventError: return event.Err case watch.EventPut: if err := event.Unmarshal(&commitID, _commitInfo); err != nil { return fmt.Errorf("Unmarshal: %v", err) } case watch.EventDelete: return pfsserver.ErrCommitDeleted{commit} } if _commitInfo.Finished != nil { commitInfo = _commitInfo break } } return nil }(); err != nil { return nil, err } } return commitInfo, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L3891-L3895
func (v GetFileInfoReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom44(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L14285-L14292
func (r *Volume) Locator(api *API) *VolumeLocator { for _, l := range r.Links { if l["rel"] == "self" { return api.VolumeLocator(l["href"]) } } return nil }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/mock_client.go#L40-L42
func (p *mockClient) StartServer(args []string, port int) *types.MockServer { return p.MockServer }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/collection/collection.go#L617-L681
func (c *readonlyCollection) WatchByIndex(index *Index, val interface{}) (watch.Watcher, error) { eventCh := make(chan *watch.Event) done := make(chan struct{}) watcher, err := watch.NewWatcher(c.ctx, c.etcdClient, c.prefix, c.indexDir(index, val), c.template) if err != nil { return nil, err } go func() (retErr error) { defer func() { if retErr != nil { eventCh <- &watch.Event{ Type: watch.EventError, Err: retErr, } watcher.Close() } close(eventCh) }() for { var ev *watch.Event var ok bool select { case ev, ok = <-watcher.Watch(): case <-done: watcher.Close() return nil } if !ok { watcher.Close() return nil } var directEv *watch.Event switch ev.Type { case watch.EventError: // pass along the error return ev.Err case watch.EventPut: resp, err := c.get(c.Path(path.Base(string(ev.Key)))) if err != nil { return err } if len(resp.Kvs) == 0 { // this happens only if the item was deleted shortly after // we receive this event. continue } directEv = &watch.Event{ Key: []byte(path.Base(string(ev.Key))), Value: resp.Kvs[0].Value, Type: ev.Type, Template: c.template, } case watch.EventDelete: directEv = &watch.Event{ Key: []byte(path.Base(string(ev.Key))), Type: ev.Type, Template: c.template, } } eventCh <- directEv } }() return watch.MakeWatcher(eventCh, done), nil }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/thrift/thrift-gen/wrap.go#L93-L98
func (s *Service) ExtendsServicePrefix() string { if dotIndex := strings.Index(s.Extends, "."); dotIndex > 0 { return s.ExtendsPrefix } return "" }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/service/service_instance.go#L181-L200
func (si *ServiceInstance) Update(service Service, updateData ServiceInstance, evt *event.Event, requestID string) error { err := validateServiceInstanceTeamOwner(updateData) if err != nil { return err } conn, err := db.Conn() if err != nil { return err } defer conn.Close() tags := processTags(updateData.Tags) if tags == nil { updateData.Tags = si.Tags } else { updateData.Tags = tags } actions := []*action.Action{&updateServiceInstance, &notifyUpdateServiceInstance} pipeline := action.NewPipeline(actions...) return pipeline.Execute(service, *si, updateData, evt, requestID) }
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/template.go#L21-L38
func (tmpl *Template) funcMapMaker(req *http.Request, writer http.ResponseWriter) template.FuncMap { var funcMap = template.FuncMap{} for key, fc := range tmpl.render.funcMaps { funcMap[key] = fc } if tmpl.render.Config.FuncMapMaker != nil { for key, fc := range tmpl.render.Config.FuncMapMaker(tmpl.render, req, writer) { funcMap[key] = fc } } for key, fc := range tmpl.funcMap { funcMap[key] = fc } return funcMap }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L121-L127
func EmptyMacroFile(path, pkg, defName string) (*File, error) { _, err := os.Create(path) if err != nil { return nil, err } return LoadMacroData(path, pkg, defName, nil) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L729-L741
func (c APIClient) GetTag(tag string, writer io.Writer) error { getTagClient, err := c.ObjectAPIClient.GetTag( c.Ctx(), &pfs.Tag{Name: tag}, ) if err != nil { return grpcutil.ScrubGRPC(err) } if err := grpcutil.WriteFromStreamingBytesClient(getTagClient, writer); err != nil { return grpcutil.ScrubGRPC(err) } return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L416-L422
func (f *FakeClient) SetMilestone(org, repo string, issueNum, milestoneNum int) error { if milestoneNum < 0 { return fmt.Errorf("Milestone Numbers Cannot Be Negative") } f.Milestone = milestoneNum return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/cluster/open.go#L26-L47
func Open(name string, store dqlite.ServerStore, options ...dqlite.DriverOption) (*sql.DB, error) { driver, err := dqlite.NewDriver(store, options...) if err != nil { return nil, errors.Wrap(err, "Failed to create dqlite driver") } driverName := dqliteDriverName() sql.Register(driverName, driver) // Create the cluster db. This won't immediately establish any network // connection, that will happen only when a db transaction is started // (see the database/sql connection pooling code for more details). if name == "" { name = "db.bin" } db, err := sql.Open(driverName, name) if err != nil { return nil, fmt.Errorf("cannot open cluster database: %v", err) } return db, nil }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dpdf/gc.go#L47-L58
func NewPdf(orientationStr, unitStr, sizeStr string) *gofpdf.Fpdf { pdf := gofpdf.New(orientationStr, unitStr, sizeStr, draw2d.GetFontFolder()) // to be compatible with draw2d pdf.SetMargins(0, 0, 0) pdf.SetDrawColor(0, 0, 0) pdf.SetFillColor(255, 255, 255) pdf.SetLineCapStyle("round") pdf.SetLineJoinStyle("round") pdf.SetLineWidth(1) pdf.AddPage() return pdf }
https://github.com/ianschenck/envflag/blob/9111d830d133f952887a936367fb0211c3134f0d/envflag.go#L158-L160
func Duration(name string, value time.Duration, usage string) *time.Duration { return EnvironmentFlags.Duration(name, value, usage) }
https://github.com/ip2location/ip2location-go/blob/a417f19539fd2a0eb0adf273b4190241cacc0499/ip2location.go#L519-L678
func query(ipaddress string, mode uint32) IP2Locationrecord { x := loadmessage(not_supported) // default message // read metadata if !metaok { x = loadmessage(missing_file) return x } // check IP type and return IP number & index (if exists) iptype, ipno, ipindex := checkip(ipaddress) if iptype == 0 { x = loadmessage(invalid_address) return x } var colsize uint32 var baseaddr uint32 var low uint32 var high uint32 var mid uint32 var rowoffset uint32 var rowoffset2 uint32 ipfrom := big.NewInt(0) ipto := big.NewInt(0) maxip := big.NewInt(0) if iptype == 4 { baseaddr = meta.ipv4databaseaddr high = meta.ipv4databasecount maxip = max_ipv4_range colsize = meta.ipv4columnsize } else { baseaddr = meta.ipv6databaseaddr high = meta.ipv6databasecount maxip = max_ipv6_range colsize = meta.ipv6columnsize } // reading index if ipindex > 0 { low = readuint32(ipindex) high = readuint32(ipindex + 4) } if ipno.Cmp(maxip)>=0 { ipno = ipno.Sub(ipno, big.NewInt(1)) } for low <= high { mid = ((low + high) >> 1) rowoffset = baseaddr + (mid * colsize) rowoffset2 = rowoffset + colsize if iptype == 4 { ipfrom = big.NewInt(int64(readuint32(rowoffset))) ipto = big.NewInt(int64(readuint32(rowoffset2))) } else { ipfrom = readuint128(rowoffset) ipto = readuint128(rowoffset2) } if ipno.Cmp(ipfrom)>=0 && ipno.Cmp(ipto)<0 { if iptype == 6 { rowoffset = rowoffset + 12 // coz below is assuming all columns are 4 bytes, so got 12 left to go to make 16 bytes total } if mode&countryshort == 1 && country_enabled { x.Country_short = readstr(readuint32(rowoffset + country_position_offset)) } if mode&countrylong != 0 && country_enabled { x.Country_long = readstr(readuint32(rowoffset + country_position_offset) + 3) } if mode&region != 0 && region_enabled { x.Region = readstr(readuint32(rowoffset + region_position_offset)) } if mode&city != 0 && city_enabled { x.City = readstr(readuint32(rowoffset + city_position_offset)) } if mode&isp != 0 && isp_enabled { x.Isp = readstr(readuint32(rowoffset + isp_position_offset)) } if mode&latitude != 0 && latitude_enabled { x.Latitude = readfloat(rowoffset + latitude_position_offset) } if mode&longitude != 0 && longitude_enabled { x.Longitude = readfloat(rowoffset + longitude_position_offset) } if mode&domain != 0 && domain_enabled { x.Domain = readstr(readuint32(rowoffset + domain_position_offset)) } if mode&zipcode != 0 && zipcode_enabled { x.Zipcode = readstr(readuint32(rowoffset + zipcode_position_offset)) } if mode&timezone != 0 && timezone_enabled { x.Timezone = readstr(readuint32(rowoffset + timezone_position_offset)) } if mode&netspeed != 0 && netspeed_enabled { x.Netspeed = readstr(readuint32(rowoffset + netspeed_position_offset)) } if mode&iddcode != 0 && iddcode_enabled { x.Iddcode = readstr(readuint32(rowoffset + iddcode_position_offset)) } if mode&areacode != 0 && areacode_enabled { x.Areacode = readstr(readuint32(rowoffset + areacode_position_offset)) } if mode&weatherstationcode != 0 && weatherstationcode_enabled { x.Weatherstationcode = readstr(readuint32(rowoffset + weatherstationcode_position_offset)) } if mode&weatherstationname != 0 && weatherstationname_enabled { x.Weatherstationname = readstr(readuint32(rowoffset + weatherstationname_position_offset)) } if mode&mcc != 0 && mcc_enabled { x.Mcc = readstr(readuint32(rowoffset + mcc_position_offset)) } if mode&mnc != 0 && mnc_enabled { x.Mnc = readstr(readuint32(rowoffset + mnc_position_offset)) } if mode&mobilebrand != 0 && mobilebrand_enabled { x.Mobilebrand = readstr(readuint32(rowoffset + mobilebrand_position_offset)) } if mode&elevation != 0 && elevation_enabled { f, _ := strconv.ParseFloat(readstr(readuint32(rowoffset + elevation_position_offset)), 32) x.Elevation = float32(f) } if mode&usagetype != 0 && usagetype_enabled { x.Usagetype = readstr(readuint32(rowoffset + usagetype_position_offset)) } return x } else { if ipno.Cmp(ipfrom)<0 { high = mid - 1 } else { low = mid + 1 } } } return x }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/default_context.go#L64-L66
func (d *DefaultContext) Param(key string) string { return d.Params().Get(key) }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/label/label.go#L54-L56
func New(repo, pkg, name string) Label { return Label{Repo: repo, Pkg: pkg, Name: name} }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L468-L471
func (l *Load) Has(sym string) bool { _, ok := l.symbols[sym] return ok }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vm.go#L1466-L1494
func (v *VM) ReadVariable(varType GuestVarType, name string) (string, error) { var jobHandle C.VixHandle = C.VIX_INVALID_HANDLE var err C.VixError = C.VIX_OK var readValue *C.char vname := C.CString(name) defer C.free(unsafe.Pointer(vname)) jobHandle = C.VixVM_ReadVariable(v.handle, C.int(varType), vname, 0, // options nil, // callbackProc nil) // clientData defer C.Vix_ReleaseHandle(jobHandle) err = C.read_variable(jobHandle, &readValue) if C.VIX_OK != err { return "", &Error{ Operation: "vm.ReadVariable", Code: int(err & 0xFFFF), Text: C.GoString(C.Vix_GetErrorText(err, nil)), } } defer C.Vix_FreeBuffer(unsafe.Pointer(readValue)) return C.GoString(readValue), nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/db.go#L90-L102
func safeBase64Scan(src, dest interface{}) error { var val string switch src := src.(type) { case []byte: val = string(src) case string: val = src default: return fmt.Errorf("Invalid value for %T", dest) } return SafeUnmarshalBase64(val, dest) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L156-L165
func (u PublicKey) GetEd25519() (result Uint256, ok bool) { armName, _ := u.ArmForSwitch(int32(u.Type)) if armName == "Ed25519" { result = *u.Ed25519 ok = true } return }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/watcher.go#L44-L75
func (w *watcher) notify(e *Event, originalPath bool, deleted bool) bool { // watcher is interested the path in three cases and under one condition // the condition is that the event happens after the watcher's sinceIndex // 1. the path at which the event happens is the path the watcher is watching at. // For example if the watcher is watching at "/foo" and the event happens at "/foo", // the watcher must be interested in that event. // 2. the watcher is a recursive watcher, it interests in the event happens after // its watching path. For example if watcher A watches at "/foo" and it is a recursive // one, it will interest in the event happens at "/foo/bar". // 3. when we delete a directory, we need to force notify all the watchers who watches // at the file we need to delete. // For example a watcher is watching at "/foo/bar". And we deletes "/foo". The watcher // should get notified even if "/foo" is not the path it is watching. if (w.recursive || originalPath || deleted) && e.Index() >= w.sinceIndex { // We cannot block here if the eventChan capacity is full, otherwise // etcd will hang. eventChan capacity is full when the rate of // notifications are higher than our send rate. // If this happens, we close the channel. select { case w.eventChan <- e: default: // We have missed a notification. Remove the watcher. // Removing the watcher also closes the eventChan. w.remove() } return true } return false }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/client.go#L64-L73
func (c *ClientWriter) WriteType(o *gen.ObjectDataType, w io.Writer) { fields := make([]string, len(o.Fields)) for i, f := range o.Fields { fields[i] = fmt.Sprintf("%s %s `json:\"%s,omitempty\"`", strings.Title(f.VarName), f.Signature(), f.Name) } decl := fmt.Sprintf("type %s struct {\n%s\n}", o.TypeName, strings.Join(fields, "\n\t")) fmt.Fprintf(w, "%s\n\n", decl) }
https://github.com/nicholasjackson/bench/blob/2df9635f0ad020b2e82616b0fd87130aaa1ee12e/results/results.go#L33-L50
func (r ResultSet) Reduce(interval time.Duration) []ResultSet { sort.Sort(r) start := r[0].Timestamp end := r[len(r)-1].Timestamp // create the buckets bucketCount := getBucketCount(start, end, interval) buckets := make([]ResultSet, bucketCount) for _, result := range r { currentBucket := getBucketNumber(result.Timestamp, start, end, interval, bucketCount) buckets[currentBucket] = append(buckets[currentBucket], result) } return buckets }