_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L1503-L1517
func (r *ProtocolLXD) GetContainerTemplateFiles(containerName string) ([]string, error) { if !r.HasExtension("container_edit_metadata") { return nil, fmt.Errorf("The server is missing the required \"container_edit_metadata\" API extension") } templates := []string{} url := fmt.Sprintf("/containers/%s/metadata/templates", url.QueryEscape(containerName)) _, err := r.queryStruct("GET", url, nil, "", &templates) if err != nil { return nil, err } return templates, nil }
https://github.com/armon/go-radix/blob/1a2de0c21c94309923825da3df33a4381872c795/radix.go#L300-L337
func (t *Tree) deletePrefix(parent, n *node, prefix string) int { // Check for key exhaustion if len(prefix) == 0 { // Remove the leaf node subTreeSize := 0 //recursively walk from all edges of the node to be deleted recursiveWalk(n, func(s string, v interface{}) bool { subTreeSize++ return false }) if n.isLeaf() { n.leaf = nil } n.edges = nil // deletes the entire subtree // Check if we should merge the parent's other child if parent != nil && parent != t.root && len(parent.edges) == 1 && !parent.isLeaf() { parent.mergeChild() } t.size -= subTreeSize return subTreeSize } // Look for an edge label := prefix[0] child := n.getEdge(label) if child == nil || (!strings.HasPrefix(child.prefix, prefix) && !strings.HasPrefix(prefix, child.prefix)) { return 0 } // Consume the search prefix if len(child.prefix) > len(prefix) { prefix = prefix[len(prefix):] } else { prefix = prefix[len(child.prefix):] } return t.deletePrefix(n, child, prefix) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage.go#L829-L848
func StorageProgressWriter(op *operation, key string, description string) func(io.WriteCloser) io.WriteCloser { return func(writer io.WriteCloser) io.WriteCloser { if op == nil { return writer } progress := func(progressInt int64, speedInt int64) { progressWrapperRender(op, key, description, progressInt, speedInt) } writePipe := &ioprogress.ProgressWriter{ WriteCloser: writer, Tracker: &ioprogress.ProgressTracker{ Handler: progress, }, } return writePipe } }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/http.go#L103-L213
func (a *API) BuildHTTPRequest(verb, path, version string, params, payload APIParams) (*http.Request, error) { u := url.URL{Host: a.Host, Path: path} if params != nil { var values = u.Query() for n, p := range params { switch t := p.(type) { case string: values.Set(n, t) case int: values.Set(n, strconv.Itoa(t)) case bool: values.Set(n, strconv.FormatBool(t)) case []string: for _, e := range t { values.Add(n, e) } case []int: for _, e := range t { values.Add(n, strconv.Itoa(e)) } case []bool: for _, e := range t { values.Add(n, strconv.FormatBool(e)) } case []interface{}: for _, e := range t { values.Add(n, fmt.Sprintf("%v", e)) } case map[string]string: for pn, e := range t { values.Add(fmt.Sprintf("%s[%s]", n, pn), e) } default: return nil, fmt.Errorf("Invalid param value <%+v> for %s, value must be a string, an integer, a bool, an array of these types of a map of strings", p, n) } } u.RawQuery = values.Encode() } var jsonBytes []byte var body io.Reader var isMultipart bool var isSourceUpload bool var boundary string if payload != nil { var fields io.Reader var multiPartUploads []*FileUpload if a.FileEncoding == FileEncodingMime { multiPartUploads = extractUploads(&payload) isMultipart = len(multiPartUploads) > 0 } sourceUpload := extractSourceUpload(&payload) if len(payload) > 0 { var err error if jsonBytes, err = json.Marshal(payload); err != nil { return nil, fmt.Errorf("failed to serialize request body: %s", err.Error()) } fields = bytes.NewBuffer(jsonBytes) } if isMultipart { var buffer bytes.Buffer w := multipart.NewWriter(&buffer) if len(payload) > 0 { err := writeMultipartParams(w, payload, "") if err != nil { return nil, fmt.Errorf("failed to write multipart params: %s", err.Error()) } } for _, u := range multiPartUploads { p, err := w.CreateFormFile(u.Name, u.Filename) if err != nil { return nil, fmt.Errorf("failed to create multipart file: %s", err.Error()) } _, err = io.Copy(p, u.Reader) if err != nil { return nil, fmt.Errorf("failed to copy multipart file: %s", err.Error()) } } if err := w.Close(); err != nil { return nil, fmt.Errorf("failed to close multipart body: %s", err.Error()) } boundary = w.Boundary() body = &buffer } else if sourceUpload != nil { isSourceUpload = true body = sourceUpload.Reader } else { body = fields } } var req, err = http.NewRequest(verb, u.String(), body) if err != nil { return nil, err } if version != "" { if a.VersionHeader != "" { req.Header.Set(a.VersionHeader, version) } else { req.Header.Set("X-Api-Version", version) } } if isMultipart { req.Header.Set("Content-Type", fmt.Sprintf("multipart/form-data; boundary=%s", boundary)) } else if isSourceUpload { req.Header.Set("Content-Type", "text/plain") } else { req.Header.Set("Content-Type", "application/json") } return req, nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/set_options.go#L50-L58
func (m HomeDomain) MutateSetOptions(o *xdr.SetOptionsOp) (err error) { if len(m) > 32 { return errors.New("HomeDomain is too long") } value := xdr.String32(m) o.HomeDomain = &value return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/emulation.go#L450-L452
func (p *SetScriptExecutionDisabledParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetScriptExecutionDisabled, p, nil) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L1090-L1092
func (p *SetDownloadBehaviorParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetDownloadBehavior, p, nil) }
https://github.com/kelseyhightower/envconfig/blob/dd1402a4d99de9ac2f396cd6fcb957bc2c695ec1/envconfig.go#L60-L145
func gatherInfo(prefix string, spec interface{}) ([]varInfo, error) { s := reflect.ValueOf(spec) if s.Kind() != reflect.Ptr { return nil, ErrInvalidSpecification } s = s.Elem() if s.Kind() != reflect.Struct { return nil, ErrInvalidSpecification } typeOfSpec := s.Type() // over allocate an info array, we will extend if needed later infos := make([]varInfo, 0, s.NumField()) for i := 0; i < s.NumField(); i++ { f := s.Field(i) ftype := typeOfSpec.Field(i) if !f.CanSet() || isTrue(ftype.Tag.Get("ignored")) { continue } for f.Kind() == reflect.Ptr { if f.IsNil() { if f.Type().Elem().Kind() != reflect.Struct { // nil pointer to a non-struct: leave it alone break } // nil pointer to struct: create a zero instance f.Set(reflect.New(f.Type().Elem())) } f = f.Elem() } // Capture information about the config variable info := varInfo{ Name: ftype.Name, Field: f, Tags: ftype.Tag, Alt: strings.ToUpper(ftype.Tag.Get("envconfig")), } // Default to the field name as the env var name (will be upcased) info.Key = info.Name // Best effort to un-pick camel casing as separate words if isTrue(ftype.Tag.Get("split_words")) { words := gatherRegexp.FindAllStringSubmatch(ftype.Name, -1) if len(words) > 0 { var name []string for _, words := range words { name = append(name, words[0]) } info.Key = strings.Join(name, "_") } } if info.Alt != "" { info.Key = info.Alt } if prefix != "" { info.Key = fmt.Sprintf("%s_%s", prefix, info.Key) } info.Key = strings.ToUpper(info.Key) infos = append(infos, info) if f.Kind() == reflect.Struct { // honor Decode if present if decoderFrom(f) == nil && setterFrom(f) == nil && textUnmarshaler(f) == nil && binaryUnmarshaler(f) == nil { innerPrefix := prefix if !ftype.Anonymous { innerPrefix = info.Key } embeddedPtr := f.Addr().Interface() embeddedInfos, err := gatherInfo(innerPrefix, embeddedPtr) if err != nil { return nil, err } infos = append(infos[:len(infos)-1], embeddedInfos...) continue } } } return infos, nil }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/cmd/autogazelle/client_unix.go#L33-L61
func runClient() error { startTime := time.Now() conn, err := net.Dial("unix", *socketPath) if err != nil { if err := startServer(); err != nil { return fmt.Errorf("error starting server: %v", err) } for retry := 0; retry < 3; retry++ { conn, err = net.Dial("unix", *socketPath) if err == nil { break } // Wait for server to start listening. time.Sleep(1 * time.Second) } if err != nil { return fmt.Errorf("failed to connect to server: %v", err) } } defer conn.Close() if _, err := io.Copy(os.Stderr, conn); err != nil { log.Print(err) } elapsedTime := time.Since(startTime) log.Printf("ran gazelle in %.3f s", elapsedTime.Seconds()) return nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/logutil/zap_raft.go#L40-L44
func NewRaftLoggerFromZapCore(cr zapcore.Core, syncer zapcore.WriteSyncer) raft.Logger { // "AddCallerSkip" to annotate caller outside of "logutil" lg := zap.New(cr, zap.AddCaller(), zap.AddCallerSkip(1), zap.ErrorOutput(syncer)) return &zapRaftLogger{lg: lg, sugar: lg.Sugar()} }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selection_actions.go#L239-L249
func (s *Selection) ScrollFinger(xOffset, yOffset int) error { selectedElement, err := s.elements.GetExactlyOne() if err != nil { return fmt.Errorf("failed to select element from %s: %s", s, err) } if err := s.session.TouchScroll(selectedElement.(*api.Element), api.XYOffset{X: xOffset, Y: yOffset}); err != nil { return fmt.Errorf("failed to scroll finger on %s: %s", s, err) } return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/client/client.go#L193-L212
func (c *Client) ReleaseAll(dest string) error { c.lock.Lock() defer c.lock.Unlock() resources, err := c.storage.List() if err != nil { return err } if len(resources) == 0 { return fmt.Errorf("no holding resource") } var allErrors error for _, r := range resources { c.storage.Delete(r.GetName()) err := c.release(r.GetName(), dest) if err != nil { allErrors = multierror.Append(allErrors, err) } } return allErrors }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L195-L204
func (p *EvaluateOnCallFrameParams) Do(ctx context.Context) (result *runtime.RemoteObject, exceptionDetails *runtime.ExceptionDetails, err error) { // execute var res EvaluateOnCallFrameReturns err = cdp.Execute(ctx, CommandEvaluateOnCallFrame, p, &res) if err != nil { return nil, nil, err } return res.Result, res.ExceptionDetails, nil }
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/ast.go#L530-L534
func (node *Update) Format(buf *TrackedBuffer) { buf.Myprintf("update %v%v set %v%v%v%v", node.Comments, node.TableExprs, node.Exprs, node.Where, node.OrderBy, node.Limit) }
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/base.go#L118-L142
func (b *Base) SetFallbackLogger(logger Logger) error { if logger == nil { if b.fallbackLogger != nil && b.fallbackLogger.IsInitialized() { b.fallbackLogger.ShutdownLogger() } b.fallbackLogger = nil return nil } if !logger.IsInitialized() { err := logger.InitLogger() if err != nil { return err } } // Shut down any old logger we might already have a reference to if b.fallbackLogger != nil && b.fallbackLogger.IsInitialized() { b.fallbackLogger.ShutdownLogger() } b.fallbackLogger = logger return nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/rafthttp/transport.go#L353-L377
func (t *Transport) removePeer(id types.ID) { if peer, ok := t.peers[id]; ok { peer.stop() } else { if t.Logger != nil { t.Logger.Panic("unexpected removal of unknown remote peer", zap.String("remote-peer-id", id.String())) } else { plog.Panicf("unexpected removal of unknown peer '%d'", id) } } delete(t.peers, id) delete(t.LeaderStats.Followers, id.String()) t.pipelineProber.Remove(id.String()) t.streamProber.Remove(id.String()) if t.Logger != nil { t.Logger.Info( "removed remote peer", zap.String("local-member-id", t.ID.String()), zap.String("removed-remote-peer-id", id.String()), ) } else { plog.Infof("removed peer %s", id) } }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/praxisgen/helpers.go#L68-L74
func prettify(o interface{}) string { s, err := json.MarshalIndent(o, "", " ") if err != nil { return fmt.Sprintf("%+v", o) } return string(s) }
https://github.com/danott/envflag/blob/14c5f9aaa227ddb49f3206fe06432edfc27735a5/envflag.go#L121-L131
func parse(args []string) { if !FlagSet.Parsed() { FlagSet.Parse(args) } for _, name := range defaultedFlags() { if value, ok := getenv(name); ok { FlagSet.Set(name, value) } } }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/deploy/assets/assets.go#L815-L870
func EtcdVolume(persistentDiskBackend backend, opts *AssetOpts, hostPath string, name string, size int) (*v1.PersistentVolume, error) { spec := &v1.PersistentVolume{ TypeMeta: metav1.TypeMeta{ Kind: "PersistentVolume", APIVersion: "v1", }, ObjectMeta: objectMeta(etcdVolumeName, labels(etcdName), nil, opts.Namespace), Spec: v1.PersistentVolumeSpec{ Capacity: map[v1.ResourceName]resource.Quantity{ "storage": resource.MustParse(fmt.Sprintf("%vGi", size)), }, AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, PersistentVolumeReclaimPolicy: v1.PersistentVolumeReclaimRetain, }, } switch persistentDiskBackend { case amazonBackend: spec.Spec.PersistentVolumeSource = v1.PersistentVolumeSource{ AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{ FSType: "ext4", VolumeID: name, }, } case googleBackend: spec.Spec.PersistentVolumeSource = v1.PersistentVolumeSource{ GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ FSType: "ext4", PDName: name, }, } case microsoftBackend: dataDiskURI := name split := strings.Split(name, "/") diskName := split[len(split)-1] spec.Spec.PersistentVolumeSource = v1.PersistentVolumeSource{ AzureDisk: &v1.AzureDiskVolumeSource{ DiskName: diskName, DataDiskURI: dataDiskURI, }, } case minioBackend: fallthrough case localBackend: spec.Spec.PersistentVolumeSource = v1.PersistentVolumeSource{ HostPath: &v1.HostPathVolumeSource{ Path: filepath.Join(hostPath, "etcd"), }, } default: return nil, fmt.Errorf("cannot generate volume spec for unknown backend \"%v\"", persistentDiskBackend) } return spec, nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/etcdserverpb/rpc.pb.go#L690-L697
func (*RequestOp) 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 _RequestOp_OneofMarshaler, _RequestOp_OneofUnmarshaler, _RequestOp_OneofSizer, []interface{}{ (*RequestOp_RequestRange)(nil), (*RequestOp_RequestPut)(nil), (*RequestOp_RequestDeleteRange)(nil), (*RequestOp_RequestTxn)(nil), } }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/tracer.go#L60-L63
func NewTracerFromRequest(r *http.Request, name string) *Tracer { span, _ := opentracing.StartSpanFromContext(r.Context(), name) return NewTracer(span) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/tackle/main.go#L50-L55
func ensure(binary, install string) error { if _, err := exec.LookPath(binary); err != nil { return fmt.Errorf("%s: %s", binary, install) } return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/query.go#L85-L113
func execFromFile(tx *sql.Tx, path string, hook Hook) error { if !shared.PathExists(path) { return nil } bytes, err := ioutil.ReadFile(path) if err != nil { return errors.Wrap(err, "failed to read file") } if hook != nil { err := hook(-1, tx) if err != nil { return errors.Wrap(err, "failed to execute hook") } } _, err = tx.Exec(string(bytes)) if err != nil { return err } err = os.Remove(path) if err != nil { return errors.Wrap(err, "failed to remove file") } return nil }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/cddvd.go#L73-L125
func (v *VM) DetachCDDVD(drive *CDDVDDrive) error { if running, _ := v.IsRunning(); running { return &Error{ Operation: "vm.DetachCDDVD", Code: 200002, Text: "Virtual machine must be powered off in order to detach CD/DVD drive.", } } // Loads VMX file in memory err := v.vmxfile.Read() if err != nil { return err } model := v.vmxfile.model switch drive.Bus { case vmx.IDE: for i, device := range model.IDEDevices { if drive.ID == device.VMXID { // This method of removing the element avoids memory leaks copy(model.IDEDevices[i:], model.IDEDevices[i+1:]) model.IDEDevices[len(model.IDEDevices)-1] = vmx.IDEDevice{} model.IDEDevices = model.IDEDevices[:len(model.IDEDevices)-1] } } case vmx.SCSI: for i, device := range model.SCSIDevices { if drive.ID == device.VMXID { copy(model.SCSIDevices[i:], model.SCSIDevices[i+1:]) model.SCSIDevices[len(model.SCSIDevices)-1] = vmx.SCSIDevice{} model.SCSIDevices = model.SCSIDevices[:len(model.SCSIDevices)-1] } } case vmx.SATA: for i, device := range model.SATADevices { if drive.ID == device.VMXID { copy(model.SATADevices[i:], model.SATADevices[i+1:]) model.SATADevices[len(model.SATADevices)-1] = vmx.SATADevice{} model.SATADevices = model.SATADevices[:len(model.SATADevices)-1] } } default: return &Error{ Operation: "vm.DetachCDDVD", Code: 200003, Text: fmt.Sprintf("Unrecognized bus type: %s\n", drive.Bus), } } return v.vmxfile.Write() }
https://github.com/bluekeyes/hatpear/blob/ffb42d5bb417aa8e12b3b7ff73d028b915dafa10/hatpear.go#L153-L167
func (e PanicError) Format(s fmt.State, verb rune) { switch verb { case 's': io.WriteString(s, e.Error()) case 'v': io.WriteString(s, e.Error()) for _, f := range e.stack { io.WriteString(s, "\n") if s.Flag('+') { fmt.Fprintf(s, "%s\n\t", f.Function) } fmt.Fprintf(s, "%s:%d", f.File, f.Line) } } }
https://github.com/scorredoira/email/blob/c1787f8317a847a7adc13673be80723268e6e639/email.go#L97-L101
func (m *Message) AddHeader(key string, value string) Header { newHeader := Header{Key: key, Value: value} m.Headers = append(m.Headers, newHeader) return newHeader }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/security/types.go#L157-L159
func (t CertificateErrorAction) MarshalEasyJSON(out *jwriter.Writer) { out.String(string(t)) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/version/version.go#L50-L56
func Cluster(v string) string { vs := strings.Split(v, ".") if len(vs) <= 2 { return v } return fmt.Sprintf("%s.%s", vs[0], vs[1]) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/pfs.go#L112-L117
func IsCommitNotFoundErr(err error) bool { if err == nil { return false } return commitNotFoundRe.MatchString(grpcutil.ScrubGRPC(err).Error()) }
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/skiplist/skiplist.go#L232-L236
func (s *Skiplist) Insert(itm unsafe.Pointer, cmp CompareFn, buf *ActionBuffer, sts *Stats) (success bool) { _, success = s.Insert2(itm, cmp, nil, buf, rand.Float32, sts) return }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/rawnode.go#L198-L203
func (rn *RawNode) Ready() Ready { rd := rn.newReady() rn.raft.msgs = nil rn.raft.reduceUncommittedSize(rd.CommittedEntries) return rd }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/rawnode.go#L259-L270
func (rn *RawNode) WithProgress(visitor func(id uint64, typ ProgressType, pr Progress)) { for id, pr := range rn.raft.prs { pr := *pr pr.ins = nil visitor(id, ProgressTypePeer, pr) } for id, pr := range rn.raft.learnerPrs { pr := *pr pr.ins = nil visitor(id, ProgressTypeLearner, pr) } }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/channel.go#L400-L406
func (ch *Channel) PeerInfo() LocalPeerInfo { ch.mutable.RLock() peerInfo := ch.mutable.peerInfo ch.mutable.RUnlock() return peerInfo }
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/gen-rawoption.go#L889-L894
func (o *ListComplex64Option) Set(value string) error { val := Complex64Option{} val.Set(value) *o = append(*o, val) return nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5187-L5190
func (e BucketEntryType) ValidEnum(v int32) bool { _, ok := bucketEntryTypeMap[v] return ok }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L2389-L2396
func NewTransactionExt(v int32, value interface{}) (result TransactionExt, err error) { result.V = v switch int32(v) { case 0: // void } return }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L410-L413
func (f *FakeClient) ClearMilestone(org, repo string, issueNum int) error { f.Milestone = 0 return nil }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/cmd/gazelle/metaresolver.go#L54-L61
func (mr metaResolver) Resolver(r *rule.Rule, pkgRel string) resolve.Resolver { for _, mappedKind := range mr.mappedKinds[pkgRel] { if mappedKind.KindName == r.Kind() { return mr.builtins[mappedKind.FromKind] } } return mr.builtins[r.Kind()] }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L161-L163
func (api *API) AccountGroupLocator(href string) *AccountGroupLocator { return &AccountGroupLocator{Href(href), api} }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gbytes/buffer.go#L222-L228
func (b *Buffer) CancelDetects() { b.lock.Lock() defer b.lock.Unlock() close(b.detectCloser) b.detectCloser = nil }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/ops.go#L843-L853
func txRange(st *State) { lhs := interfaceToNumeric(st.sb).Int() rhs := interfaceToNumeric(st.sa).Int() for i := lhs; i <= rhs; i++ { // push these to stack st.StackPush(i) } st.Advance() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L5412-L5416
func (v *GetBackgroundColorsReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss47(&r, v) return r.Error() }
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/outgoing.go#L673-L682
func NewInlineQueryResultMpeg4Gif(id, mpeg4URL, thumbURL string) *InlineQueryResultMpeg4Gif { return &InlineQueryResultMpeg4Gif{ InlineQueryResultBase: InlineQueryResultBase{ Type: PhotoResult, ID: id, }, Mpeg4URL: mpeg4URL, ThumbURL: thumbURL, } }
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/log/field.go#L196-L229
func (lf Field) Marshal(visitor Encoder) { switch lf.fieldType { case stringType: visitor.EmitString(lf.key, lf.stringVal) case boolType: visitor.EmitBool(lf.key, lf.numericVal != 0) case intType: visitor.EmitInt(lf.key, int(lf.numericVal)) case int32Type: visitor.EmitInt32(lf.key, int32(lf.numericVal)) case int64Type: visitor.EmitInt64(lf.key, int64(lf.numericVal)) case uint32Type: visitor.EmitUint32(lf.key, uint32(lf.numericVal)) case uint64Type: visitor.EmitUint64(lf.key, uint64(lf.numericVal)) case float32Type: visitor.EmitFloat32(lf.key, math.Float32frombits(uint32(lf.numericVal))) case float64Type: visitor.EmitFloat64(lf.key, math.Float64frombits(uint64(lf.numericVal))) case errorType: if err, ok := lf.interfaceVal.(error); ok { visitor.EmitString(lf.key, err.Error()) } else { visitor.EmitString(lf.key, "<nil>") } case objectType: visitor.EmitObject(lf.key, lf.interfaceVal) case lazyLoggerType: visitor.EmitLazyLogger(lf.interfaceVal.(LazyLogger)) case noopType: // intentionally left blank } }
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/pbuf.go#L179-L211
func (b *PointerRingBuf) Push(p []interface{}) (n int, err error) { for { if len(p) == 0 { // nothing (left) to copy in; notice we shorten our // local copy p (below) as we read from it. return } writeCapacity := b.N - b.Readable if writeCapacity <= 0 { // we are all full up already. return n, io.ErrShortWrite } if len(p) > writeCapacity { err = io.ErrShortWrite // leave err set and // keep going, write what we can. } writeStart := (b.Beg + b.Readable) % b.N upperLim := intMin(writeStart+writeCapacity, b.N) k := copy(b.A[writeStart:upperLim], p) n += k b.Readable += k p = p[k:] // we can fill from b.A[0:something] from // p's remainder, so loop } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L2372-L2376
func (v ResumeParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDebugger24(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mocktracer.go#L70-L72
func (t *MockTracer) RegisterInjector(format interface{}, injector Injector) { t.injectors[format] = injector }
https://github.com/libp2p/go-libp2p-routing/blob/15c28e7faa25921fd1160412003fecdc70e09a5c/options/options.go#L16-L23
func (opts *Options) Apply(options ...Option) error { for _, o := range options { if err := o(opts); err != nil { return err } } return nil }
https://github.com/knq/sdhook/blob/41b9ccbff0b5fa5a56fbdccf2eb8653e7afe8d4b/opts.go#L241-L269
func GoogleComputeCredentials(serviceAccount string) Option { return func(sh *StackdriverHook) error { var err error // get compute metadata scopes associated with the service account scopes, err := metadata.Scopes(serviceAccount) if err != nil { return err } // check if all the necessary scopes are provided for _, s := range requiredScopes { if !sliceContains(scopes, s) { // NOTE: if you are seeing this error, you probably need to // recreate your compute instance with the correct scope // // as of August 2016, there is not a way to add a scope to an // existing compute instance return fmt.Errorf("missing required scope %s in compute metadata", s) } } return HTTPClient(&http.Client{ Transport: &oauth2.Transport{ Source: google.ComputeTokenSource(serviceAccount), }, })(sh) } }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L2735-L2745
func (c *Client) MoveProjectCard(projectCardID int, newColumnID int) error { c.log("MoveProjectCard", projectCardID, newColumnID) _, err := c.request(&request{ method: http.MethodPost, path: fmt.Sprintf("/projects/columns/cards/%d/moves", projectCardID), accept: "application/vnd.github.symmetra-preview+json", // allow the description field -- https://developer.github.com/changes/2018-02-22-label-description-search-preview/ requestBody: fmt.Sprintf("{column_id: %d}", newColumnID), exitCodes: []int{201}, }, nil) return err }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/histogram.go#L119-L135
func (db *DB) buildHistogram(keyPrefix []byte) *sizeHistogram { txn := db.NewTransaction(false) defer txn.Discard() itr := txn.NewIterator(DefaultIteratorOptions) defer itr.Close() badgerHistogram := newSizeHistogram() // Collect key and value sizes. for itr.Seek(keyPrefix); itr.ValidForPrefix(keyPrefix); itr.Next() { item := itr.Item() badgerHistogram.keySizeHistogram.Update(item.KeySize()) badgerHistogram.valueSizeHistogram.Update(item.ValueSize()) } return badgerHistogram }
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/parser/parser.go#L89-L104
func Parse(xp string) (*Node, error) { var err error c := lexer.Lex(xp) n := &Node{} p := &parseStack{cur: n} for next := range c { if next.Typ != lexer.XItemError { parseMap[next.Typ](p, next) } else if err == nil { err = fmt.Errorf(next.Val) } } return n, err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tracing/tracing.go#L134-L137
func (p StartParams) WithBufferUsageReportingInterval(bufferUsageReportingInterval float64) *StartParams { p.BufferUsageReportingInterval = bufferUsageReportingInterval return &p }
https://github.com/VividCortex/godaemon/blob/3d9f6e0b234fe7d17448b345b2e14ac05814a758/daemon.go#L315-L321
func Stage() DaemonStage { if currStage == stageUnknown { s, _, _ := getStage() currStage = DaemonStage(s) } return currStage }
https://github.com/ipfs/go-ipfs-api/blob/a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32/shell.go#L511-L517
func (s *Shell) SwarmConnect(ctx context.Context, addr ...string) error { var conn *swarmConnection err := s.Request("swarm/connect"). Arguments(addr...). Exec(ctx, &conn) return err }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/wal/wal.go#L743-L771
func (w *WAL) Close() error { w.mu.Lock() defer w.mu.Unlock() if w.fp != nil { w.fp.Close() w.fp = nil } if w.tail() != nil { if err := w.sync(); err != nil { return err } } for _, l := range w.locks { if l == nil { continue } if err := l.Close(); err != nil { if w.lg != nil { w.lg.Warn("failed to close WAL", zap.Error(err)) } else { plog.Errorf("failed to unlock during closing wal: %s", err) } } } return w.dirFile.Close() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/db.go#L123-L129
func (n *Node) Transaction(f func(*NodeTx) error) error { nodeTx := &NodeTx{} return query.Transaction(n.db, func(tx *sql.Tx) error { nodeTx.tx = tx return f(nodeTx) }) }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/apps/put_apps_app_responses.go#L23-L54
func (o *PutAppsAppReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 200: result := NewPutAppsAppOK() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil case 400: result := NewPutAppsAppBadRequest() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 500: result := NewPutAppsAppInternalServerError() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result default: result := NewPutAppsAppDefault(response.Code()) if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result } }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3664-L3672
func (u InflationResult) MustPayouts() []InflationPayout { val, ok := u.GetPayouts() if !ok { panic("arm Payouts is not set") } return val }
https://github.com/ipfs/go-ipfs-api/blob/a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32/options/dag.go#L38-L43
func (dagOpts) Pin(pin string) DagPutOption { return func(opts *DagPutSettings) error { opts.Pin = pin return nil } }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/gitattributes/gitattributes.go#L108-L115
func (g *Group) IsLinguistGenerated(path string) bool { for _, p := range g.LinguistGeneratedPatterns { if p.Match(path) { return true } } return false }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/storage/storage_image.go#L122-L128
func (s *storageImageSource) GetBlob(ctx context.Context, info types.BlobInfo, cache types.BlobInfoCache) (rc io.ReadCloser, n int64, err error) { if info.Digest == image.GzippedEmptyLayerDigest { return ioutil.NopCloser(bytes.NewReader(image.GzippedEmptyLayer)), int64(len(image.GzippedEmptyLayer)), nil } rc, n, _, err = s.getBlobAndLayerID(info) return rc, n, err }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/gopherage/pkg/cov/aggregate.go#L26-L37
func AggregateProfiles(profiles [][]*cover.Profile) ([]*cover.Profile, error) { setProfiles := make([][]*cover.Profile, 0, len(profiles)) for _, p := range profiles { c := countToBoolean(p) setProfiles = append(setProfiles, c) } aggregateProfiles, err := MergeMultipleProfiles(setProfiles) if err != nil { return nil, err } return aggregateProfiles, nil }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/core/read.go#L42-L57
func (p *Process) ReadUint16(a Address) uint16 { m := p.findMapping(a) if m == nil { panic(fmt.Errorf("address %x is not mapped in the core file", a)) } b := m.contents[a.Sub(m.min):] if len(b) < 2 { var buf [2]byte b = buf[:] p.ReadAt(b, a) } if p.littleEndian { return binary.LittleEndian.Uint16(b) } return binary.BigEndian.Uint16(b) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5707-L5740
func NewLedgerEntryChange(aType LedgerEntryChangeType, value interface{}) (result LedgerEntryChange, err error) { result.Type = aType switch LedgerEntryChangeType(aType) { case LedgerEntryChangeTypeLedgerEntryCreated: tv, ok := value.(LedgerEntry) if !ok { err = fmt.Errorf("invalid value, must be LedgerEntry") return } result.Created = &tv case LedgerEntryChangeTypeLedgerEntryUpdated: tv, ok := value.(LedgerEntry) if !ok { err = fmt.Errorf("invalid value, must be LedgerEntry") return } result.Updated = &tv case LedgerEntryChangeTypeLedgerEntryRemoved: tv, ok := value.(LedgerKey) if !ok { err = fmt.Errorf("invalid value, must be LedgerKey") return } result.Removed = &tv case LedgerEntryChangeTypeLedgerEntryState: tv, ok := value.(LedgerEntry) if !ok { err = fmt.Errorf("invalid value, must be LedgerEntry") return } result.State = &tv } return }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/inmem_transport.go#L86-L97
func (i *InmemTransport) AppendEntriesPipeline(id ServerID, target ServerAddress) (AppendPipeline, error) { i.Lock() defer i.Unlock() peer, ok := i.peers[target] if !ok { return nil, fmt.Errorf("failed to connect to peer: %v", target) } pipeline := newInmemPipeline(i, peer, target) i.pipelines = append(i.pipelines, pipeline) return pipeline, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/blockade/blockade.go#L182-L220
func compileApplicableBlockades(org, repo string, log *logrus.Entry, blockades []plugins.Blockade) []blockade { if len(blockades) == 0 { return nil } orgRepo := fmt.Sprintf("%s/%s", org, repo) var compiled []blockade for _, raw := range blockades { // Only consider blockades that apply to this repo. if !stringInSlice(org, raw.Repos) && !stringInSlice(orgRepo, raw.Repos) { continue } b := blockade{} for _, str := range raw.BlockRegexps { if reg, err := regexp.Compile(str); err != nil { log.WithError(err).Errorf("Failed to compile the blockade regexp '%s'.", str) } else { b.blockRegexps = append(b.blockRegexps, reg) } } if len(b.blockRegexps) == 0 { continue } if raw.Explanation == "" { b.explanation = "Files are protected" } else { b.explanation = raw.Explanation } for _, str := range raw.ExceptionRegexps { if reg, err := regexp.Compile(str); err != nil { log.WithError(err).Errorf("Failed to compile the blockade regexp '%s'.", str) } else { b.exceptionRegexps = append(b.exceptionRegexps, reg) } } compiled = append(compiled, b) } return compiled }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/default_context.go#L171-L173
func (d *DefaultContext) LogField(key string, value interface{}) { d.logger = d.logger.WithField(key, value) }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dbase/text.go#L58-L63
func (g *Glyph) Copy() *Glyph { return &Glyph{ Path: g.Path.Copy(), Width: g.Width, } }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/servers/grpc/grpc.go#L46-L49
func (s *Server) Shutdown(ctx context.Context) (err error) { s.Server.GracefulStop() return }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/rawnode.go#L207-L225
func (rn *RawNode) HasReady() bool { r := rn.raft if !r.softState().equal(rn.prevSoftSt) { return true } if hardSt := r.hardState(); !IsEmptyHardState(hardSt) && !isHardStateEqual(hardSt, rn.prevHardSt) { return true } if r.raftLog.unstable.snapshot != nil && !IsEmptySnap(*r.raftLog.unstable.snapshot) { return true } if len(r.msgs) > 0 || len(r.raftLog.unstableEntries()) > 0 || r.raftLog.hasNextEnts() { return true } if len(r.readStates) != 0 { return true } return false }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/types.go#L305-L325
func (t *ClientNavigationReason) UnmarshalEasyJSON(in *jlexer.Lexer) { switch ClientNavigationReason(in.String()) { case ClientNavigationReasonFormSubmissionGet: *t = ClientNavigationReasonFormSubmissionGet case ClientNavigationReasonFormSubmissionPost: *t = ClientNavigationReasonFormSubmissionPost case ClientNavigationReasonHTTPHeaderRefresh: *t = ClientNavigationReasonHTTPHeaderRefresh case ClientNavigationReasonScriptInitiated: *t = ClientNavigationReasonScriptInitiated case ClientNavigationReasonMetaTagRefresh: *t = ClientNavigationReasonMetaTagRefresh case ClientNavigationReasonPageBlockInterstitial: *t = ClientNavigationReasonPageBlockInterstitial case ClientNavigationReasonReload: *t = ClientNavigationReasonReload default: in.AddError(errors.New("unknown ClientNavigationReason value")) } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_put.go#L22-L102
func containerPut(d *Daemon, r *http.Request) Response { project := projectParam(r) // Get the container name := mux.Vars(r)["name"] // Handle requests targeted to a container on a different node response, err := ForwardedResponseIfContainerIsRemote(d, r, project, name) if err != nil { return SmartError(err) } if response != nil { return response } c, err := containerLoadByProjectAndName(d.State(), project, name) if err != nil { return NotFound(err) } // Validate the ETag etag := []interface{}{c.Architecture(), c.LocalConfig(), c.LocalDevices(), c.IsEphemeral(), c.Profiles()} err = util.EtagCheck(r, etag) if err != nil { return PreconditionFailed(err) } configRaw := api.ContainerPut{} if err := json.NewDecoder(r.Body).Decode(&configRaw); err != nil { return BadRequest(err) } architecture, err := osarch.ArchitectureId(configRaw.Architecture) if err != nil { architecture = 0 } var do func(*operation) error var opType db.OperationType if configRaw.Restore == "" { // Update container configuration do = func(op *operation) error { args := db.ContainerArgs{ Architecture: architecture, Config: configRaw.Config, Description: configRaw.Description, Devices: configRaw.Devices, Ephemeral: configRaw.Ephemeral, Profiles: configRaw.Profiles, Project: project, } // FIXME: should set to true when not migrating err = c.Update(args, false) if err != nil { return err } return nil } opType = db.OperationSnapshotUpdate } else { // Snapshot Restore do = func(op *operation) error { return containerSnapRestore(d.State(), project, name, configRaw.Restore, configRaw.Stateful) } opType = db.OperationSnapshotRestore } resources := map[string][]string{} resources["containers"] = []string{name} op, err := operationCreate(d.cluster, project, operationClassTask, opType, resources, nil, do, nil, nil) if err != nil { return InternalError(err) } return OperationResponse(op) }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcawsprovisioner/tcawsprovisioner.go#L297-L301
func (awsProvisioner *AwsProvisioner) InstanceStarted(instanceId, token string) error { cd := tcclient.Client(*awsProvisioner) _, _, err := (&cd).APICall(nil, "GET", "/instance-started/"+url.QueryEscape(instanceId)+"/"+url.QueryEscape(token), nil, nil) return err }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/images.go#L768-L842
func (c *Cluster) ImageInsert(project, fp string, fname string, sz int64, public bool, autoUpdate bool, architecture string, createdAt time.Time, expiresAt time.Time, properties map[string]string) error { err := c.Transaction(func(tx *ClusterTx) error { enabled, err := tx.ProjectHasImages(project) if err != nil { return errors.Wrap(err, "Check if project has images") } if !enabled { project = "default" } return nil }) if err != nil { return err } arch, err := osarch.ArchitectureId(architecture) if err != nil { arch = 0 } err = c.Transaction(func(tx *ClusterTx) error { publicInt := 0 if public { publicInt = 1 } autoUpdateInt := 0 if autoUpdate { autoUpdateInt = 1 } stmt, err := tx.tx.Prepare(`INSERT INTO images (project_id, fingerprint, filename, size, public, auto_update, architecture, creation_date, expiry_date, upload_date) VALUES ((SELECT id FROM projects WHERE name = ?), ?, ?, ?, ?, ?, ?, ?, ?, ?)`) if err != nil { return err } defer stmt.Close() result, err := stmt.Exec(project, fp, fname, sz, publicInt, autoUpdateInt, arch, createdAt, expiresAt, time.Now().UTC()) if err != nil { return err } id64, err := result.LastInsertId() if err != nil { return err } id := int(id64) if len(properties) > 0 { pstmt, err := tx.tx.Prepare(`INSERT INTO images_properties (image_id, type, key, value) VALUES (?, 0, ?, ?)`) if err != nil { return err } defer pstmt.Close() for k, v := range properties { // we can assume, that there is just one // value per key _, err = pstmt.Exec(id, k, v) if err != nil { return err } } } _, err = tx.tx.Exec("INSERT INTO images_nodes(image_id, node_id) VALUES(?, ?)", id, c.nodeID) if err != nil { return err } return nil }) return err }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L260-L263
func (mat *Mat) Clone() *Mat { mat_new := C.cvCloneMat((*C.CvMat)(mat)) return (*Mat)(mat_new) }
https://github.com/tylerb/gls/blob/e606233f194d6c314156dc6a35f21a42a470c6f6/gls.go#L39-L47
func Set(key string, value interface{}) { gid := curGoroutineID() dataLock.Lock() if data[gid] == nil { data[gid] = Values{} } data[gid][key] = value dataLock.Unlock() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/net.go#L88-L105
func ServerTLSConfig(cert *shared.CertInfo) *tls.Config { config := shared.InitTLSConfig() config.ClientAuth = tls.RequestClientCert config.Certificates = []tls.Certificate{cert.KeyPair()} config.NextProtos = []string{"h2"} // Required by gRPC if cert.CA() != nil { pool := x509.NewCertPool() pool.AddCert(cert.CA()) config.RootCAs = pool config.ClientCAs = pool logger.Infof("LXD is in CA mode, only CA-signed certificates will be allowed") } config.BuildNameToCertificate() return config }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/admin.go#L82-L91
func (c APIClient) ExtractPipeline(pipelineName string) (*pps.CreatePipelineRequest, error) { op, err := c.AdminAPIClient.ExtractPipeline(c.Ctx(), &admin.ExtractPipelineRequest{Pipeline: NewPipeline(pipelineName)}) if err != nil { return nil, grpcutil.ScrubGRPC(err) } if op.Op1_9 == nil || op.Op1_9.Pipeline == nil { return nil, fmt.Errorf("malformed response is missing pipeline") } return op.Op1_9.Pipeline, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/flagutil/k8s_client.go#L64-L66
func (o *KubernetesClientOptions) KubeClient() (kubernetes.Interface, error) { return kube.GetKubernetesClient(o.masterURL, o.kubeConfig) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L6765-L6769
func (v *CollectClassNamesFromSubtreeReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom76(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/security/types.go#L91-L93
func (t State) MarshalEasyJSON(out *jwriter.Writer) { out.String(string(t)) }
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/context.go#L336-L339
func (w contextWriter) Write(p []byte) (int, error) { w.context.written = true return w.ResponseWriter.Write(p) }
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/log_windows.go#L72-L82
func NewLogBackend(out io.Writer, prefix string, flag int) *LogBackend { b := &LogBackend{Logger: log.New(out, prefix, flag)} // Unfortunately, the API used only takes an io.Writer where the Windows API // need the actual fd to change colors. if f, ok := out.(file); ok { b.f = f } return b }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domdebugger/easyjson.go#L449-L453
func (v RemoveInstrumentationBreakpointParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDomdebugger5(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L422-L424
func (cd Codec) AddMulti(c context.Context, items []*Item) error { return cd.set(c, items, pb.MemcacheSetRequest_ADD) }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/app.go#L1814-L1844
func appRebuildRoutes(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { a, err := getAppFromContext(r.URL.Query().Get(":app"), r) if err != nil { return err } allowed := permission.Check(t, permission.PermAppAdminRoutes, contextsForApp(&a)..., ) if !allowed { return permission.ErrUnauthorized } dry, _ := strconv.ParseBool(InputValue(r, "dry")) evt, err := event.New(&event.Opts{ Target: appTarget(a.Name), Kind: permission.PermAppAdminRoutes, Owner: t, CustomData: event.FormToCustomData(InputFields(r)), Allowed: event.Allowed(permission.PermAppReadEvents, contextsForApp(&a)...), }) if err != nil { return err } result := map[string]rebuild.RebuildRoutesResult{} defer func() { evt.DoneCustomData(err, result) }() w.Header().Set("Content-Type", "application/json") result, err = rebuild.RebuildRoutes(&a, dry) if err != nil { return err } return json.NewEncoder(w).Encode(&result) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/auth_command.go#L46-L73
func authEnableCommandFunc(cmd *cobra.Command, args []string) { if len(args) != 0 { ExitWithError(ExitBadArgs, fmt.Errorf("auth enable command does not accept any arguments")) } ctx, cancel := commandCtx(cmd) cli := mustClientFromCmd(cmd) var err error for err == nil { if _, err = cli.AuthEnable(ctx); err == nil { break } if err == rpctypes.ErrRootRoleNotExist { if _, err = cli.RoleAdd(ctx, "root"); err != nil { break } if _, err = cli.UserGrantRole(ctx, "root", "root"); err != nil { break } } } cancel() if err != nil { ExitWithError(ExitError, err) } fmt.Println("Authentication Enabled") }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/types.go#L344-L346
func (t *MediaSource) UnmarshalJSON(buf []byte) error { return easyjson.Unmarshal(buf, t) }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/config.go#L222-L265
func ValidateConfig(config *Config) error { // We don't actually support running as 0 in the library any more, but // we do understand it. protocolMin := ProtocolVersionMin if protocolMin == 0 { protocolMin = 1 } if config.ProtocolVersion < protocolMin || config.ProtocolVersion > ProtocolVersionMax { return fmt.Errorf("Protocol version %d must be >= %d and <= %d", config.ProtocolVersion, protocolMin, ProtocolVersionMax) } if len(config.LocalID) == 0 { return fmt.Errorf("LocalID cannot be empty") } if config.HeartbeatTimeout < 5*time.Millisecond { return fmt.Errorf("Heartbeat timeout is too low") } if config.ElectionTimeout < 5*time.Millisecond { return fmt.Errorf("Election timeout is too low") } if config.CommitTimeout < time.Millisecond { return fmt.Errorf("Commit timeout is too low") } if config.MaxAppendEntries <= 0 { return fmt.Errorf("MaxAppendEntries must be positive") } if config.MaxAppendEntries > 1024 { return fmt.Errorf("MaxAppendEntries is too large") } if config.SnapshotInterval < 5*time.Millisecond { return fmt.Errorf("Snapshot interval is too low") } if config.LeaderLeaseTimeout < 5*time.Millisecond { return fmt.Errorf("Leader lease timeout is too low") } if config.LeaderLeaseTimeout > config.HeartbeatTimeout { return fmt.Errorf("Leader lease timeout cannot be larger than heartbeat timeout") } if config.ElectionTimeout < config.HeartbeatTimeout { return fmt.Errorf("Election timeout must be equal or greater than Heartbeat Timeout") } return nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/watch.go#L103-L105
func (e *Event) IsCreate() bool { return e.Type == EventTypePut && e.Kv.CreateRevision == e.Kv.ModRevision }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/flagutil/github.go#L119-L146
func (o *GitHubOptions) GitClient(secretAgent *secret.Agent, dryRun bool) (client *git.Client, err error) { client, err = git.NewClient() if err != nil { return nil, err } // We must capture the value of client here to prevent issues related // to the use of named return values when an error is encountered. // Without this, we risk a nil pointer dereference. defer func(client *git.Client) { if err != nil { client.Clean() } }(client) // Get the bot's name in order to set credentials for the Git client. githubClient, err := o.GitHubClient(secretAgent, dryRun) if err != nil { return nil, fmt.Errorf("error getting GitHub client: %v", err) } botName, err := githubClient.BotName() if err != nil { return nil, fmt.Errorf("error getting bot name: %v", err) } client.SetCredentials(botName, secretAgent.GetTokenGenerator(o.TokenPath)) return client, nil }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/op.go#L27-L40
func NewOp(o OpType, args ...interface{}) Op { h := optypeToHandler(o) var arg interface{} if len(args) > 0 { arg = args[0] } return &op{ OpType: o, OpHandler: h, uArg: arg, } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/headlessexperimental/headlessexperimental.go#L63-L66
func (p BeginFrameParams) WithNoDisplayUpdates(noDisplayUpdates bool) *BeginFrameParams { p.NoDisplayUpdates = noDisplayUpdates return &p }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_server.go#L93-L107
func (r *ProtocolLXD) UseProject(name string) ContainerServer { return &ProtocolLXD{ server: r.server, http: r.http, httpCertificate: r.httpCertificate, httpHost: r.httpHost, httpProtocol: r.httpProtocol, httpUserAgent: r.httpUserAgent, bakeryClient: r.bakeryClient, bakeryInteractor: r.bakeryInteractor, requireAuthenticated: r.requireAuthenticated, clusterTarget: r.clusterTarget, project: name, } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_projects.go#L87-L99
func (r *ProtocolLXD) UpdateProject(name string, project api.ProjectPut, ETag string) error { if !r.HasExtension("projects") { return fmt.Errorf("The server is missing the required \"projects\" API extension") } // Send the request _, _, err := r.query("PUT", fmt.Sprintf("/projects/%s", url.QueryEscape(name)), project, ETag) if err != nil { return err } return nil }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/inbound.go#L38-L127
func (c *Connection) handleCallReq(frame *Frame) bool { now := c.timeNow() switch state := c.readState(); state { case connectionActive: break case connectionStartClose, connectionInboundClosed, connectionClosed: c.SendSystemError(frame.Header.ID, callReqSpan(frame), ErrChannelClosed) return true default: panic(fmt.Errorf("unknown connection state for call req: %v", state)) } callReq := new(callReq) callReq.id = frame.Header.ID initialFragment, err := parseInboundFragment(c.opts.FramePool, frame, callReq) if err != nil { // TODO(mmihic): Probably want to treat this as a protocol error c.log.WithFields( LogField{"header", frame.Header}, ErrField(err), ).Error("Couldn't decode initial fragment.") return true } call := new(InboundCall) call.conn = c ctx, cancel := newIncomingContext(call, callReq.TimeToLive) mex, err := c.inbound.newExchange(ctx, c.opts.FramePool, callReq.messageType(), frame.Header.ID, mexChannelBufferSize) if err != nil { if err == errDuplicateMex { err = errInboundRequestAlreadyActive } c.log.WithFields(LogField{"header", frame.Header}).Error("Couldn't register exchange.") c.protocolError(frame.Header.ID, errInboundRequestAlreadyActive) return true } // Close may have been called between the time we checked the state and us creating the exchange. if c.readState() != connectionActive { mex.shutdown() return true } response := new(InboundCallResponse) response.call = call response.calledAt = now response.timeNow = c.timeNow response.span = c.extractInboundSpan(callReq) if response.span != nil { mex.ctx = opentracing.ContextWithSpan(mex.ctx, response.span) } response.mex = mex response.conn = c response.cancel = cancel response.log = c.log.WithFields(LogField{"In-Response", callReq.ID()}) response.contents = newFragmentingWriter(response.log, response, initialFragment.checksumType.New()) response.headers = transportHeaders{} response.messageForFragment = func(initial bool) message { if initial { callRes := new(callRes) callRes.Headers = response.headers callRes.ResponseCode = responseOK if response.applicationError { callRes.ResponseCode = responseApplicationError } return callRes } return new(callResContinue) } call.mex = mex call.initialFragment = initialFragment call.serviceName = string(callReq.Service) call.headers = callReq.Headers call.response = response call.log = c.log.WithFields(LogField{"In-Call", callReq.ID()}) call.messageForFragment = func(initial bool) message { return new(callReqContinue) } call.contents = newFragmentingReader(call.log, call) call.statsReporter = c.statsReporter call.createStatsTags(c.commonStatsTags) response.statsReporter = c.statsReporter response.commonStatsTags = call.commonStatsTags setResponseHeaders(call.headers, response.headers) go c.dispatchInbound(c.connID, callReq.ID(), call, frame) return false }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/namespace/lease.go#L31-L33
func NewLease(l clientv3.Lease, prefix string) clientv3.Lease { return &leasePrefix{l, []byte(prefix)} }
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nitro.go#L581-L586
func CompareSnapshot(this, that unsafe.Pointer) int { thisItem := (*Snapshot)(this) thatItem := (*Snapshot)(that) return int(thisItem.sn) - int(thatItem.sn) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/member_command.go#L58-L67
func NewMemberRemoveCommand() *cobra.Command { cc := &cobra.Command{ Use: "remove <memberID>", Short: "Removes a member from the cluster", Run: memberRemoveCommandFunc, } return cc }