_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/iterator.go#L70-L78
func (it *Iterator) Next() { it.iter.Next() it.count++ it.skipUnwanted() if it.refreshRate > 0 && it.count > it.refreshRate { it.Refresh() it.count = 0 } }
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/attrs.go#L82-L87
func (a *Attrs) GetAttr(key string) interface{} { a.attrsLock.RLock() defer a.attrsLock.RUnlock() return a.attrs[getAttrHash(key)] }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/sysregistriesv2/system_registries_v2.go#L41-L62
func (e *Endpoint) RewriteReference(ref reference.Named, prefix string) (reference.Named, error) { if ref == nil { return nil, fmt.Errorf("provided reference is nil") } if prefix == "" { return ref, nil } refString := ref.String() if refMatchesPrefix(refString, prefix) { newNamedRef := strings.Replace(refString, prefix, e.Location, 1) newParsedRef, err := reference.ParseNamed(newNamedRef) if newParsedRef != nil { logrus.Debugf("reference rewritten from '%v' to '%v'", refString, newParsedRef.String()) } if err != nil { return nil, errors.Wrapf(err, "error rewriting reference") } return newParsedRef, nil } return nil, fmt.Errorf("invalid prefix '%v' for reference '%v'", prefix, refString) }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/relay.go#L113-L130
func (r *relayItems) Delete(id uint32) (relayItem, bool) { r.Lock() item, ok := r.items[id] if !ok { r.Unlock() r.logger.WithFields(LogField{"id", id}).Warn("Attempted to delete non-existent relay item.") return item, false } delete(r.items, id) if item.tomb { r.tombs-- } r.Unlock() item.timeout.Stop() item.timeout.Release() return item, !item.tomb }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L3209-L3213
func (v *GetOuterHTMLReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom36(&r, v) return r.Error() }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/builder.go#L131-L134
func (p MailBuilder) HTML(body []byte) MailBuilder { p.html = body return p }
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/model/backpack.go#L27-L35
func (b Bag) Value() (driver.Value, error) { buf := bytes.NewBuffer(nil) err := gob.NewEncoder(buf).Encode(b) if err != nil { return nil, err } return buf.Bytes(), nil }
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cmd/getconfig.go#L31-L66
func GetConfigCmd() *cobra.Command { var cro = &cli.GetConfigOptions{} var getConfigCmd = &cobra.Command{ Use: "getconfig <NAME>", Short: "Manage Kubernetes configuration", Long: `Use this command to pull a kubeconfig file from a cluster so you can use kubectl. This command will attempt to find a cluster, and append a local kubeconfig file with a kubeconfig `, Run: func(cmd *cobra.Command, args []string) { switch len(args) { case 0: cro.Name = viper.GetString(keyKubicornName) case 1: cro.Name = args[0] default: logger.Critical("Too many arguments.") os.Exit(1) } if err := runGetConfig(cro); err != nil { logger.Critical(err.Error()) os.Exit(1) } }, } fs := getConfigCmd.Flags() bindCommonStateStoreFlags(&cro.StateStoreOptions, fs) bindCommonAwsFlags(&cro.AwsOptions, fs) fs.StringVar(&cro.GitRemote, keyGitConfig, viper.GetString(keyGitConfig), descGitConfig) return getConfigCmd }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/network.go#L182-L301
func (v *VM) AddNetworkAdapter(adapter *NetworkAdapter) error { isVMRunning, err := v.IsRunning() if err != nil { return err } if isVMRunning { return &Error{ Code: 100000, Text: "The VM has to be powered off in order to change its vmx settings", } } vmxPath, err := v.VmxPath() if err != nil { return err } vmx, err := readVmx(vmxPath) if err != nil { return err } if adapter == nil { adapter = &NetworkAdapter{} } adapter.present = true if adapter.Vdevice == NETWORK_DEVICE_VMXNET3 { hwversion, err := strconv.Atoi(vmx["virtualhw.version"]) if err != nil { return err } if hwversion < 7 { return &Error{ Operation: "vm.AddNetworkAdapter", Code: 100001, Text: fmt.Sprintf("Virtual hardware version needs to be 7 or higher in order to use vmxnet3. Current hardware version: %d", hwversion), } } } if adapter.LinkStatePropagation && (adapter.ConnType != NETWORK_BRIDGED) { return &Error{ Operation: "vm.AddNetworkAdapter", Code: 100003, Text: "Link state propagation is only permitted for bridged networks", } } macaddr := adapter.MacAddress.String() if macaddr != "" { if !strings.HasPrefix(macaddr, "00:50:56") { return &Error{ Operation: "vm.AddNetworkAdapter", Code: 100004, Text: "Static MAC addresses have to start with VMware officially assigned prefix: 00:50:56", } } } nextID := v.nextNetworkAdapterID(vmx) prefix := fmt.Sprintf("ethernet%d.", nextID) vmx[prefix+"present"] = strings.ToUpper(strconv.FormatBool(adapter.present)) if string(adapter.ConnType) != "" { vmx[prefix+"connectionType"] = string(adapter.ConnType) } else { //default vmx[prefix+"connectionType"] = "nat" } if string(adapter.Vdevice) != "" { vmx[prefix+"virtualDev"] = string(adapter.Vdevice) } else { //default vmx[prefix+"virtualDev"] = "e1000" } vmx[prefix+"wakeOnPcktRcv"] = strconv.FormatBool(adapter.WakeOnPcktRcv) if string(adapter.MacAddrType) != "" { vmx[prefix+"addressType"] = string(adapter.MacAddrType) } else { //default vmx[prefix+"addressType"] = "generated" } if macaddr != "" { vmx[prefix+"address"] = macaddr vmx[prefix+"addressType"] = "static" // Makes sure a generated MAC address is removed if it exists delete(vmx, "generatedAddress") delete(vmx, "generatedAddressOffset") } if adapter.LinkStatePropagation { vmx[prefix+"linkStatePropagation.enable"] = strconv.FormatBool(adapter.LinkStatePropagation) } if adapter.ConnType == NETWORK_CUSTOM { if !ExistVSwitch(adapter.VSwitch.id) { return &Error{ Operation: "vm.AddNetworkAdapter", Code: 100005, Text: "VSwitch " + adapter.VSwitch.id + " does not exist", } } vmx[prefix+"vnet"] = string(adapter.VSwitch.id) } vmx[prefix+"startConnected"] = strconv.FormatBool(adapter.StartConnected) return writeVmx(vmxPath, vmx) }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/internal/mail/message.go#L107-L110
func (m *Message) SetHeader(field string, value ...string) { m.encodeHeader(value) m.header[field] = value }
https://github.com/jmank88/nuts/blob/8b28145dffc87104e66d074f62ea8080edfad7c8/paths.go#L150-L260
func SeekPathConflict(c *bolt.Cursor, path []byte) ([]byte, []byte) { // Validation if len(path) == 0 { return nil, nil } if path[0] != '/' { return nil, nil } // Fast-path for exact and prefix match. if k, v := c.Seek(path); bytes.Equal(k, path) { return k, v } else if bytes.HasPrefix(k, path) { // Any prefixed k is good enough when path ends in '/'. if path[len(path)-1] == '/' { return nil, nil } // If k's last element is longer it could be a conflict. if k[len(path)] == '/' { return nil, nil } } // Prefix scan. i := 0 for { i++ // Match slash. prefix := path[:i] k, v := c.Seek(prefix) if !bytes.HasPrefix(k, prefix) { return nil, nil } // Exact match is a conflict for trailing slash. if i == len(path) { if len(k) == len(path) { return k, v } return nil, nil } // Advance cursor past exact match to first prefix match. if len(k) == len(prefix) { k, v = c.Next() if !bytes.HasPrefix(k, prefix) { return nil, nil } } // Find end of element. offset := bytes.IndexByte(path[i:], '/') last := offset < 0 if last { i = len(path) } else { i += offset } switch k[len(prefix)] { case '*': return k, v case ':': // Find end of element. kPrefix := k offset := bytes.IndexByte(k[len(prefix):], '/') if offset > 0 { kPrefix = k[:len(prefix)+offset] } // Exact match required through variable element. prefix = path[:i] if !bytes.Equal(prefix, kPrefix) { return k, v } if last { // Exact match is a conflict for the last element. if k, v = c.Seek(prefix); bytes.Equal(k, prefix) { return k, v } return nil, nil } default: // Static (non-variable) element required. next := path[len(prefix)] if next == ':' || next == '*' { return k, v } prefix = path[:i] k, v = c.Seek(prefix) if last { // Exact match is a conflict for the last element. if bytes.Equal(k, prefix) { return k, v } return nil, nil } if !bytes.HasPrefix(k, prefix) { return nil, nil } } } }
https://github.com/urandom/handler/blob/61508044a5569d1609521d81e81f6737567fd104/security/nonce.go#L71-L75
func Setter(s NonceSetter) Option { return Option{func(o *options) { o.setter = s }} }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/maintenance/aws-janitor/regions/regions.go#L37-L48
func GetAll(sess *session.Session) ([]string, error) { var regions []string svc := ec2.New(sess, &aws.Config{Region: aws.String(Default)}) resp, err := svc.DescribeRegions(nil) if err != nil { return nil, err } for _, region := range resp.Regions { regions = append(regions, *region.RegionName) } return regions, nil }
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/multi.go#L25-L37
func (b *multiLogger) Log(level Level, calldepth int, rec *Record) (err error) { for _, backend := range b.backends { if backend.IsEnabledFor(level, rec.Module) { // Shallow copy of the record for the formatted cache on Record and get the // record formatter from the backend. r2 := *rec if e := backend.Log(level, calldepth+1, &r2); e != nil { err = e } } } return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L1094-L1097
func (p RequestChildNodesParams) WithPierce(pierce bool) *RequestChildNodesParams { p.Pierce = pierce return &p }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/profiler.go#L137-L140
func (p StartPreciseCoverageParams) WithCallCount(callCount bool) *StartPreciseCoverageParams { p.CallCount = callCount return &p }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/archive/oci_transport.go#L62-L77
func NewReference(file, image string) (types.ImageReference, error) { resolved, err := explicitfilepath.ResolvePathToFullyExplicit(file) if err != nil { return nil, err } if err := internal.ValidateOCIPath(file); err != nil { return nil, err } if err := internal.ValidateImageName(image); err != nil { return nil, err } return ociArchiveReference{file: file, resolvedFile: resolved, image: image}, nil }
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsAO.go#L51-L66
func Between(s, left, right string) string { l := len(left) startPos := strings.Index(s, left) if startPos < 0 { return "" } endPos := IndexOf(s, right, startPos+l) //log.Printf("%s: left %s right %s start %d end %d", s, left, right, startPos+l, endPos) if endPos < 0 { return "" } else if right == "" { return s[endPos:] } else { return s[startPos+l : endPos] } }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/create_account.go#L53-L55
func (m Destination) MutateCreateAccount(o *xdr.CreateAccountOp) error { return setAccountId(m.AddressOrSeed, &o.Destination) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L11628-L11630
func (api *API) ServerArrayLocator(href string) *ServerArrayLocator { return &ServerArrayLocator{Href(href), api} }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/tls.go#L41-L54
func tlsCheckCert(r *http.Request, info *shared.CertInfo) bool { cert, err := x509.ParseCertificate(info.KeyPair().Certificate[0]) if err != nil { // Since we have already loaded this certificate, typically // using LoadX509KeyPair, an error should never happen, but // check for good measure. panic(fmt.Sprintf("invalid keypair material: %v", err)) } trustedCerts := map[string]x509.Certificate{"0": *cert} trusted, _ := util.CheckTrustState(*r.TLS.PeerCertificates[0], trustedCerts) return r.TLS != nil && trusted }
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/router.go#L142-L156
func (rt *router) ofFirstDefinedRoute(matches []*trie.Match) *trie.Match { minIndex := -1 var bestMatch *trie.Match for _, result := range matches { route := result.Route.(*Route) routeIndex := rt.index[route] if minIndex == -1 || routeIndex < minIndex { minIndex = routeIndex bestMatch = result } } return bestMatch }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L162-L176
func (l *PeerList) Remove(hostPort string) error { l.Lock() defer l.Unlock() p, ok := l.peersByHostPort[hostPort] if !ok { return ErrPeerNotFound } p.delSC() delete(l.peersByHostPort, hostPort) l.peerHeap.removePeer(p) return nil }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/level_handler.go#L261-L281
func (s *levelHandler) appendIterators(iters []y.Iterator, opt *IteratorOptions) []y.Iterator { s.RLock() defer s.RUnlock() tables := make([]*table.Table, 0, len(s.tables)) for _, t := range s.tables { if opt.pickTable(t) { tables = append(tables, t) } } if len(tables) == 0 { return iters } if s.level == 0 { // Remember to add in reverse order! // The newer table at the end of s.tables should be added first as it takes precedence. return appendIteratorsReversed(iters, tables, opt.Reverse) } return append(iters, table.NewConcatIterator(tables, opt.Reverse)) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/tackle/main.go#L228-L284
func createContext(co contextOptions) (string, error) { proj, err := selectProject(co.project) if err != nil { logrus.Info("Run gcloud auth login to initialize gcloud") return "", fmt.Errorf("get current project: %v", err) } fmt.Printf("Existing GKE clusters in %s:", proj) fmt.Println() clusters, err := currentClusters(proj) if err != nil { return "", fmt.Errorf("list %s clusters: %v", proj, err) } for name := range clusters { fmt.Println(" *", name) } if len(clusters) == 0 { fmt.Println(" No clusters") } var choice string create := co.create reuse := co.reuse switch { case create != "" && reuse != "": return "", errors.New("Cannot use both --create and --reuse") case create != "": fmt.Println("Creating new " + create + " cluster...") choice = "new" case reuse != "": fmt.Println("Reusing existing " + reuse + " cluster...") choice = reuse default: fmt.Print("Get credentials for existing cluster or [create new]: ") fmt.Scanln(&choice) } if choice == "" || choice == "new" { cluster, err := createCluster(proj, create) if err != nil { return "", fmt.Errorf("create cluster in %s: %v", proj, err) } return cluster.context(), nil } cluster, ok := clusters[choice] if !ok { return "", fmt.Errorf("cluster not found: %s", choice) } cmd := exec.Command("gcloud", "container", "clusters", "get-credentials", cluster.name, "--project="+cluster.project, "--zone="+cluster.zone) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { return "", fmt.Errorf("get credentials: %v", err) } return cluster.context(), nil }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/log/log.go#L135-L141
func (t *Target) Debugf(format string, v ...interface{}) { t.mut.RLock() defer t.mut.RUnlock() if t.logger != nil { t.logger.Debugf(format, v...) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L576-L581
func SetBlackboxedRanges(scriptID runtime.ScriptID, positions []*ScriptPosition) *SetBlackboxedRangesParams { return &SetBlackboxedRangesParams{ ScriptID: scriptID, Positions: positions, } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/webaudio/easyjson.go#L77-L81
func (v GetRealtimeDataReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoWebaudio(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dkit/draw2dkit.go#L44-L47
func Circle(path draw2d.PathBuilder, cx, cy, radius float64) { path.ArcTo(cx, cy, radius, radius, 0, -math.Pi*2) path.Close() }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/dco/dco.go#L248-L270
func handle(gc gitHubClient, cp commentPruner, log *logrus.Entry, org, repo string, pr github.PullRequest, addComment bool) error { l := log.WithField("pr", pr.Number) commitsMissingDCO, err := checkCommitMessages(gc, l, org, repo, pr.Number) if err != nil { l.WithError(err).Infof("Error running DCO check against commits in PR") return err } existingStatus, err := checkExistingStatus(gc, l, org, repo, pr.Head.SHA) if err != nil { l.WithError(err).Infof("Error checking existing PR status") return err } hasYesLabel, hasNoLabel, err := checkExistingLabels(gc, l, org, repo, pr.Number) if err != nil { l.WithError(err).Infof("Error checking existing PR labels") return err } return takeAction(gc, cp, l, org, repo, pr, commitsMissingDCO, existingStatus, hasYesLabel, hasNoLabel, addComment) }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/registry.go#L80-L93
func Descriptor(in error) (desc *ErrDescriptor) { err := From(in) descriptor := Get(err.Code()) if descriptor != nil { return descriptor } // return a new error descriptor with sane defaults return &ErrDescriptor{ MessageFormat: err.Error(), Type: err.Type(), Code: err.Code(), } }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/mock_service.go#L71-L75
func (m *MockService) DeleteInteractions() error { log.Println("[DEBUG] mock service delete interactions") url := fmt.Sprintf("%s/interactions", m.BaseURL) return m.call("DELETE", url, nil) }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/backup.go#L47-L120
func (stream *Stream) Backup(w io.Writer, since uint64) (uint64, error) { stream.KeyToList = func(key []byte, itr *Iterator) (*pb.KVList, error) { list := &pb.KVList{} for ; itr.Valid(); itr.Next() { item := itr.Item() if !bytes.Equal(item.Key(), key) { return list, nil } if item.Version() < since { // Ignore versions less than given timestamp, or skip older // versions of the given key. return list, nil } var valCopy []byte if !item.IsDeletedOrExpired() { // No need to copy value, if item is deleted or expired. var err error valCopy, err = item.ValueCopy(nil) if err != nil { stream.db.opt.Errorf("Key [%x, %d]. Error while fetching value [%v]\n", item.Key(), item.Version(), err) return nil, err } } // clear txn bits meta := item.meta &^ (bitTxn | bitFinTxn) kv := &pb.KV{ Key: item.KeyCopy(nil), Value: valCopy, UserMeta: []byte{item.UserMeta()}, Version: item.Version(), ExpiresAt: item.ExpiresAt(), Meta: []byte{meta}, } list.Kv = append(list.Kv, kv) switch { case item.DiscardEarlierVersions(): // If we need to discard earlier versions of this item, add a delete // marker just below the current version. list.Kv = append(list.Kv, &pb.KV{ Key: item.KeyCopy(nil), Version: item.Version() - 1, Meta: []byte{bitDelete}, }) return list, nil case item.IsDeletedOrExpired(): return list, nil } } return list, nil } var maxVersion uint64 stream.Send = func(list *pb.KVList) error { for _, kv := range list.Kv { if maxVersion < kv.Version { maxVersion = kv.Version } if err := writeTo(kv, w); err != nil { return err } } return nil } if err := stream.Orchestrate(context.Background()); err != nil { return 0, err } return maxVersion, nil }
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/zero/int.go#L111-L114
func (i *Int) SetValid(n int64) { i.Int64 = n i.Valid = true }
https://github.com/blacklabeldata/namedtuple/blob/c341f1db44f30b8164294aa8605ede42be604aba/schema/lexer.go#L122-L126
func (l *Lexer) run() { for state := lexText; state != nil; { state = state(l) } }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L148-L158
func (r *InclusiveRange) Len() int { if r.isLenCached { return r.cachedLen } // Offset by one to include the end value diff := math.Abs(float64(r.end-r.start)) + 1 r.cachedLen = int(math.Ceil(diff / math.Abs(float64(r.step)))) r.isLenCached = true return r.cachedLen }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/storage/chunk/storage.go#L30-L35
func (s *Storage) NewReader(ctx context.Context, dataRefs []*DataRef) io.ReadCloser { if len(dataRefs) == 0 { return ioutil.NopCloser(&bytes.Buffer{}) } return newReader(ctx, s.objC, s.prefix, dataRefs) }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/pact.go#L383-L396
func (p *Pact) VerifyProvider(t *testing.T, request types.VerifyRequest) (types.ProviderVerifierResponse, error) { res, err := p.VerifyProviderRaw(request) for _, example := range res.Examples { t.Run(example.Description, func(st *testing.T) { st.Log(example.FullDescription) if example.Status != "passed" { t.Errorf("%s\n%s\n", example.FullDescription, example.Exception.Message) } }) } return res, err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L1639-L1643
func (v EventDetachedFromTarget) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoTarget18(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/pandemicsyn/oort/blob/fca1d3baddc1d944387cc8bbe8b21f911ec9091b/oort/cmdctrl.go#L147-L155
func (o *Server) SelfUpgrade(version string, bindiff, checksum []byte) (bool, string) { o.cmdCtrlLock.Lock() defer o.cmdCtrlLock.Unlock() err := o.binaryUpgrade.Upgrade(version) if err != nil { return false, err.Error() } return true, "" }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/apps/get_apps_app_parameters.go#L77-L80
func (o *GetAppsAppParams) WithTimeout(timeout time.Duration) *GetAppsAppParams { o.SetTimeout(timeout) return o }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/internal/mail/send.go#L36-L44
func Send(s Sender, msg ...*Message) error { for i, m := range msg { if err := send(s, m); err != nil { return &SendError{Cause: err, Index: uint(i)} } } return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/apis/prowjobs/v1/zz_generated.deepcopy.go#L96-L103
func (in *GCSConfiguration) DeepCopy() *GCSConfiguration { if in == nil { return nil } out := new(GCSConfiguration) in.DeepCopyInto(out) return out }
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L608-L651
func (p *PubSub) pushMsg(vals []*topicVal, src peer.ID, msg *Message) { // reject messages from blacklisted peers if p.blacklist.Contains(src) { log.Warningf("dropping message from blacklisted peer %s", src) return } // even if they are forwarded by good peers if p.blacklist.Contains(msg.GetFrom()) { log.Warningf("dropping message from blacklisted source %s", src) return } // reject unsigned messages when strict before we even process the id if p.signStrict && msg.Signature == nil { log.Debugf("dropping unsigned message from %s", src) return } // have we already seen and validated this message? id := msgID(msg.Message) if p.seenMessage(id) { return } if len(vals) > 0 || msg.Signature != nil { // validation is asynchronous and globally throttled with the throttleValidate semaphore. // the purpose of the global throttle is to bound the goncurrency possible from incoming // network traffic; each validator also has an individual throttle to preclude // slow (or faulty) validators from starving other topics; see validate below. select { case p.validateThrottle <- struct{}{}: go func() { p.validate(vals, src, msg) <-p.validateThrottle }() default: log.Warningf("message validation throttled; dropping message from %s", src) } return } p.publishMessage(src, msg.Message) }
https://github.com/geoffgarside/ber/blob/27a1aff36ce64dbe5d93c08cc5f161983134ddc5/ber.go#L59-L70
func checkInteger(bytes []byte) error { if len(bytes) == 0 { return asn1.StructuralError{Msg: "empty integer"} } if len(bytes) == 1 { return nil } if (bytes[0] == 0 && bytes[1]&0x80 == 0) || (bytes[0] == 0xff && bytes[1]&0x80 == 0x80) { return asn1.StructuralError{Msg: "integer not minimally-encoded"} } return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L1042-L1055
func (r *ProtocolLXD) CreateContainerSnapshot(containerName string, snapshot api.ContainerSnapshotsPost) (Operation, error) { // Validate the request if snapshot.ExpiresAt != nil && !r.HasExtension("snapshot_expiry_creation") { return nil, fmt.Errorf("The server is missing the required \"snapshot_expiry_creation\" API extension") } // Send the request op, _, err := r.queryOperation("POST", fmt.Sprintf("/containers/%s/snapshots", url.QueryEscape(containerName)), snapshot, "") if err != nil { return nil, err } return op, nil }
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L654-L674
func (p *PubSub) validate(vals []*topicVal, src peer.ID, msg *Message) { if msg.Signature != nil { if !p.validateSignature(msg) { log.Warningf("message signature validation failed; dropping message from %s", src) return } } if len(vals) > 0 { if !p.validateTopic(vals, src, msg) { log.Warningf("message validation failed; dropping message from %s", src) return } } // all validators were successful, send the message p.sendMsg <- &sendReq{ from: src, msg: msg, } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/storage/storage.go#L28-L33
func ClearDataForOrigin(origin string, storageTypes string) *ClearDataForOriginParams { return &ClearDataForOriginParams{ Origin: origin, StorageTypes: storageTypes, } }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/worker/api_server.go#L693-L758
func (a *APIServer) runUserErrorHandlingCode(ctx context.Context, logger *taggedLogger, environ []string, stats *pps.ProcessStats, rawDatumTimeout *types.Duration) (retErr error) { logger.Logf("beginning to run user error handling code") defer func(start time.Time) { if retErr != nil { logger.Logf("errored running user error handling code after %v: %v", time.Since(start), retErr) } else { logger.Logf("finished running user error handling code after %v", time.Since(start)) } }(time.Now()) cmd := exec.CommandContext(ctx, a.pipelineInfo.Transform.ErrCmd[0], a.pipelineInfo.Transform.ErrCmd[1:]...) if a.pipelineInfo.Transform.ErrStdin != nil { cmd.Stdin = strings.NewReader(strings.Join(a.pipelineInfo.Transform.ErrStdin, "\n") + "\n") } cmd.Stdout = logger.userLogger() cmd.Stderr = logger.userLogger() cmd.Env = environ if a.uid != nil && a.gid != nil { cmd.SysProcAttr = &syscall.SysProcAttr{ Credential: &syscall.Credential{ Uid: *a.uid, Gid: *a.gid, }, } } cmd.Dir = a.pipelineInfo.Transform.WorkingDir err := cmd.Start() if err != nil { return fmt.Errorf("error cmd.Start: %v", err) } // A context w a deadline will successfully cancel/kill // the running process (minus zombies) state, err := cmd.Process.Wait() if err != nil { return fmt.Errorf("error cmd.Wait: %v", err) } if isDone(ctx) { if err = ctx.Err(); err != nil { return err } } // Because of this issue: https://github.com/golang/go/issues/18874 // We forked os/exec so that we can call just the part of cmd.Wait() that // happens after blocking on the process. Unfortunately calling // cmd.Process.Wait() then cmd.Wait() will produce an error. So instead we // close the IO using this helper err = cmd.WaitIO(state, err) // We ignore broken pipe errors, these occur very occasionally if a user // specifies Stdin but their process doesn't actually read everything from // Stdin. This is a fairly common thing to do, bash by default ignores // broken pipe errors. if err != nil && !strings.Contains(err.Error(), "broken pipe") { // (if err is an acceptable return code, don't return err) if exiterr, ok := err.(*exec.ExitError); ok { if status, ok := exiterr.Sys().(syscall.WaitStatus); ok { for _, returnCode := range a.pipelineInfo.Transform.AcceptReturnCode { if int(returnCode) == status.ExitStatus() { return nil } } } } return fmt.Errorf("error cmd.WaitIO: %v", err) } return nil }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L145-L158
func (l *PeerList) Get(prevSelected map[string]struct{}) (*Peer, error) { peer, err := l.GetNew(prevSelected) if err == ErrNoNewPeers { l.Lock() peer = l.choosePeer(nil, false /* avoidHost */) l.Unlock() } else if err != nil { return nil, err } if peer == nil { return nil, ErrNoPeers } return peer, nil }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/iterator.go#L237-L247
func (item *Item) EstimatedSize() int64 { if !item.hasValue() { return 0 } if (item.meta & bitValuePointer) == 0 { return int64(len(item.key) + len(item.vptr)) } var vp valuePointer vp.Decode(item.vptr) return int64(vp.Len) // includes key length. }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_pools.go#L808-L849
func (c *Cluster) StoragePoolVolumeGetType(project string, volumeName string, volumeType int, poolID, nodeID int64) (int64, *api.StorageVolume, error) { // Custom volumes are "global", i.e. they are associated with the // default project. if volumeType == StoragePoolVolumeTypeCustom { project = "default" } volumeID, err := c.StoragePoolVolumeGetTypeID(project, volumeName, volumeType, poolID, nodeID) if err != nil { return -1, nil, err } volumeNode, err := c.StorageVolumeNodeGet(volumeID) if err != nil { return -1, nil, err } volumeConfig, err := c.StorageVolumeConfigGet(volumeID) if err != nil { return -1, nil, err } volumeDescription, err := c.StorageVolumeDescriptionGet(volumeID) if err != nil { return -1, nil, err } volumeTypeName, err := StoragePoolVolumeTypeToName(volumeType) if err != nil { return -1, nil, err } storageVolume := api.StorageVolume{ Type: volumeTypeName, } storageVolume.Name = volumeName storageVolume.Description = volumeDescription storageVolume.Config = volumeConfig storageVolume.Location = volumeNode return volumeID, &storageVolume, nil }
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/taskmanager/task.go#L61-L66
func (s *Task) Read(read func(*Task) interface{}) interface{} { s.mutex.RLock() var ret = read(s) s.mutex.RUnlock() return ret }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/metadata/action.go#L36-L48
func (a *Action) MatchHref(href string) bool { hrefs := []string{href, href + "/"} for _, pattern := range a.PathPatterns { for _, href := range hrefs { indices := pattern.Regexp.FindStringIndex(href) // it is only an exact match if the pattern matches from the beginning to the length of the string if indices != nil && indices[0] == 0 && indices[1] == len(href) { return true } } } return false }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/taskqueue/taskqueue.go#L357-L363
func Delete(c context.Context, task *Task, queueName string) error { err := DeleteMulti(c, []*Task{task}, queueName) if me, ok := err.(appengine.MultiError); ok { return me[0] } return err }
https://github.com/kr/s3/blob/c070c8f9a8f0032d48f0d2a77d4e382788bd8a1d/sign.go#L81-L83
func Sign(r *http.Request, k Keys) { DefaultService.Sign(r, k) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/easyjson.go#L1212-L1216
func (v GetHistogramsParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoBrowser12(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/membership.go#L897-L916
func membershipCheckClusterStateForLeave(tx *db.ClusterTx, nodeID int64) error { // Check that it has no containers or images. message, err := tx.NodeIsEmpty(nodeID) if err != nil { return err } if message != "" { return fmt.Errorf(message) } // Check that it's not the last node. nodes, err := tx.Nodes() if err != nil { return err } if len(nodes) == 1 { return fmt.Errorf("node is the only node in the cluster") } return nil }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gbytes/buffer.go#L93-L109
func (b *Buffer) Read(d []byte) (int, error) { b.lock.Lock() defer b.lock.Unlock() if b.closed { return 0, errors.New("attempt to read from closed buffer") } if uint64(len(b.contents)) <= b.readCursor { return 0, io.EOF } n := copy(d, b.contents[b.readCursor:]) b.readCursor += uint64(n) return n, nil }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L556-L558
func And(src1, src2, dst *IplImage) { AndWithMask(src1, src2, dst, nil) }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/context_header.go#L97-L105
func Wrap(ctx context.Context) ContextWithHeaders { hctx := headerCtx{Context: ctx} if h := hctx.headers(); h != nil { return hctx } // If there is no header container, we should create an empty one. return WrapWithHeaders(ctx, nil) }
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/snapshot.go#L67-L72
func (c *Client) DeleteSnapshot(snapshotID string) (*http.Header, error) { url := snapshotColPath() + slash(snapshotID) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty) ret := &http.Header{} err := c.client.Delete(url, ret, http.StatusAccepted) return ret, err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L775-L778
func (p SetCookieParams) WithPath(path string) *SetCookieParams { p.Path = path return &p }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/ghproxy/ghcache/ghcache.go#L176-L185
func NewDiskCache(delegate http.RoundTripper, cacheDir string, cacheSizeGB, maxConcurrency int) http.RoundTripper { return NewFromCache(delegate, diskcache.NewWithDiskv( diskv.New(diskv.Options{ BasePath: path.Join(cacheDir, "data"), TempDir: path.Join(cacheDir, "temp"), CacheSizeMax: uint64(cacheSizeGB) * uint64(1000000000), // convert G to B })), maxConcurrency, ) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L224-L227
func (p CreateIsolatedWorldParams) WithGrantUniveralAccess(grantUniveralAccess bool) *CreateIsolatedWorldParams { p.GrantUniveralAccess = grantUniveralAccess return &p }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L4747-L4749
func (api *API) IpAddressLocator(href string) *IpAddressLocator { return &IpAddressLocator{Href(href), api} }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/manifest.go#L184-L217
func (mf *manifestFile) addChanges(changesParam []*pb.ManifestChange) error { changes := pb.ManifestChangeSet{Changes: changesParam} buf, err := changes.Marshal() if err != nil { return err } // Maybe we could use O_APPEND instead (on certain file systems) mf.appendLock.Lock() if err := applyChangeSet(&mf.manifest, &changes); err != nil { mf.appendLock.Unlock() return err } // Rewrite manifest if it'd shrink by 1/10 and it's big enough to care if mf.manifest.Deletions > mf.deletionsRewriteThreshold && mf.manifest.Deletions > manifestDeletionsRatio*(mf.manifest.Creations-mf.manifest.Deletions) { if err := mf.rewrite(); err != nil { mf.appendLock.Unlock() return err } } else { var lenCrcBuf [8]byte binary.BigEndian.PutUint32(lenCrcBuf[0:4], uint32(len(buf))) binary.BigEndian.PutUint32(lenCrcBuf[4:8], crc32.Checksum(buf, y.CastagnoliCrcTable)) buf = append(lenCrcBuf[:], buf...) if _, err := mf.fp.Write(buf); err != nil { mf.appendLock.Unlock() return err } } mf.appendLock.Unlock() return mf.fp.Sync() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L166-L169
func (p EvaluateOnCallFrameParams) WithGeneratePreview(generatePreview bool) *EvaluateOnCallFrameParams { p.GeneratePreview = generatePreview return &p }
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/service/logger/logger.go#L233-L242
func (hr HTTPRequest) MarshalLogObject(enc zapcore.ObjectEncoder) error { enc.AddString("method", hr.Method) enc.AddString("url", hr.URL) enc.AddString("userAgent", hr.UserAgent) enc.AddString("referrer", hr.Referrer) enc.AddString("responseStatusCode", hr.ResponseStatusCode) enc.AddString("remoteIp", hr.RemoteIP) return nil }
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/loadbalancer.go#L96-L101
func (c *Client) ListBalancedNics(dcid, lbalid string) (*Nics, error) { url := balnicColPath(dcid, lbalid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty) ret := &Nics{} err := c.client.Get(url, ret, http.StatusOK) return ret, err }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/json/context.go#L35-L38
func NewContext(timeout time.Duration) (Context, context.CancelFunc) { ctx, cancel := tchannel.NewContext(timeout) return tchannel.WrapWithHeaders(ctx, nil), cancel }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/saml.go#L25-L39
func samlMetadata(w http.ResponseWriter, r *http.Request) error { if app.AuthScheme.Name() != "saml" { return &errors.HTTP{ Code: http.StatusBadRequest, Message: "This URL is only supported with saml enabled", } } page, err := saml.Metadata() if err != nil { return err } w.Header().Set("Content-Type", "application/xml") w.Write([]byte(page)) return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L762-L766
func (v RunIfWaitingForDebuggerParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoRuntime7(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/ostree/ostree_src.go#L371-L410
func (s *ostreeImageSource) LayerInfosForCopy(ctx context.Context) ([]types.BlobInfo, error) { updatedBlobInfos := []types.BlobInfo{} manifestBlob, manifestType, err := s.GetManifest(ctx, nil) if err != nil { return nil, err } man, err := manifest.FromBlob(manifestBlob, manifestType) s.compressed = make(map[digest.Digest]digest.Digest) layerBlobs := man.LayerInfos() for _, layerBlob := range layerBlobs { branch := fmt.Sprintf("ociimage/%s", layerBlob.Digest.Hex()) found, uncompressedDigestStr, err := readMetadata(s.repo, branch, "docker.uncompressed_digest") if err != nil || !found { return nil, err } found, uncompressedSizeStr, err := readMetadata(s.repo, branch, "docker.uncompressed_size") if err != nil || !found { return nil, err } uncompressedSize, err := strconv.ParseInt(uncompressedSizeStr, 10, 64) if err != nil { return nil, err } uncompressedDigest := digest.Digest(uncompressedDigestStr) blobInfo := types.BlobInfo{ Digest: uncompressedDigest, Size: uncompressedSize, MediaType: layerBlob.MediaType, } s.compressed[uncompressedDigest] = layerBlob.Digest updatedBlobInfos = append(updatedBlobInfos, blobInfo) } return updatedBlobInfos, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/plugins.go#L333-L345
func (pa *ConfigAgent) ReviewCommentEventHandlers(owner, repo string) map[string]ReviewCommentEventHandler { pa.mut.Lock() defer pa.mut.Unlock() hs := map[string]ReviewCommentEventHandler{} for _, p := range pa.getPlugins(owner, repo) { if h, ok := reviewCommentEventHandlers[p]; ok { hs[p] = h } } return hs }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L4233-L4237
func (v *EvaluateParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime38(&r, v) return r.Error() }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/txn.go#L132-L136
func (o *oracle) setDiscardTs(ts uint64) { o.Lock() defer o.Unlock() o.discardTs = ts }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L12553-L12600
func (loc *ServerTemplateLocator) Publish(accountGroupHrefs []string, descriptions *Descriptions, options rsapi.APIParams) error { if len(accountGroupHrefs) == 0 { return fmt.Errorf("accountGroupHrefs is required") } if descriptions == nil { return fmt.Errorf("descriptions is required") } var params rsapi.APIParams var p rsapi.APIParams p = rsapi.APIParams{ "account_group_hrefs": accountGroupHrefs, "descriptions": descriptions, } var allowCommentsOpt = options["allow_comments"] if allowCommentsOpt != nil { p["allow_comments"] = allowCommentsOpt } var categoriesOpt = options["categories"] if categoriesOpt != nil { p["categories"] = categoriesOpt } var emailCommentsOpt = options["email_comments"] if emailCommentsOpt != nil { p["email_comments"] = emailCommentsOpt } uri, err := loc.ActionPath("ServerTemplate", "publish") if err != nil { return err } req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p) if err != nil { return err } resp, err := loc.api.PerformRequest(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode > 299 { respBody, _ := ioutil.ReadAll(resp.Body) sr := string(respBody) if sr != "" { sr = ": " + sr } return fmt.Errorf("invalid response %s%s", resp.Status, sr) } return nil }
https://github.com/ipfs/go-ipfs-api/blob/a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32/shell.go#L466-L473
func (s *Shell) ObjectStat(key string) (*ObjectStats, error) { var stat ObjectStats err := s.Request("object/stat", key).Exec(context.Background(), &stat) if err != nil { return nil, err } return &stat, nil }
https://github.com/blacksails/cgp/blob/570ac705cf2d7a9235d911d00b6f976ab3386c2f/mailing_list.go#L15-L17
func (dom *Domain) MailingList(name string) *MailingList { return &MailingList{Domain: dom, Name: name} }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.go#L152-L179
func (c *Cluster) ProfilesGet(project string, names []string) ([]api.Profile, error) { profiles := make([]api.Profile, len(names)) err := c.Transaction(func(tx *ClusterTx) error { enabled, err := tx.ProjectHasProfiles(project) if err != nil { return errors.Wrap(err, "Check if project has profiles") } if !enabled { project = "default" } for i, name := range names { profile, err := tx.ProfileGet(project, name) if err != nil { return errors.Wrapf(err, "Load profile %q", name) } profiles[i] = *ProfileToAPI(profile) } return nil }) if err != nil { return nil, err } return profiles, nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/snap/snapshotter.go#L219-L235
func (s *Snapshotter) snapNames() ([]string, error) { dir, err := os.Open(s.dir) if err != nil { return nil, err } defer dir.Close() names, err := dir.Readdirnames(-1) if err != nil { return nil, err } snaps := checkSuffix(s.lg, names) if len(snaps) == 0 { return nil, ErrNoSnapshot } sort.Sort(sort.Reverse(sort.StringSlice(snaps))) return snaps, nil }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dpdf/gc.go#L61-L64
func rgb(c color.Color) (int, int, int) { r, g, b, _ := c.RGBA() return int(float64(r) * c255), int(float64(g) * c255), int(float64(b) * c255) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxc/config/config.go#L65-L73
func NewConfig(configDir string, defaults bool) *Config { config := &Config{ConfigDir: configDir} if defaults { config.Remotes = DefaultRemotes config.DefaultRemote = "local" } return config }
https://github.com/qor/roles/blob/d6375609fe3e5da46ad3a574fae244fb633e79c1/permissioner.go#L9-L17
func ConcatPermissioner(ps ...Permissioner) Permissioner { var newPS []Permissioner for _, p := range ps { if p != nil { newPS = append(newPS, p) } } return permissioners(newPS) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/tools/etcd-dump-logs/main.go#L223-L228
func printInternalRaftRequest(entry raftpb.Entry) { var rr etcdserverpb.InternalRaftRequest if err := rr.Unmarshal(entry.Data); err == nil { fmt.Printf("%4d\t%10d\tnorm\t%s", entry.Term, entry.Index, rr.String()) } }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/routes/post_apps_app_routes_parameters.go#L84-L87
func (o *PostAppsAppRoutesParams) WithTimeout(timeout time.Duration) *PostAppsAppRoutesParams { o.SetTimeout(timeout) return o }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/managed_db.go#L24-L27
func OpenManaged(opts Options) (*DB, error) { opts.managedTxns = true return Open(opts) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L891-L893
func (p *SetExtraHTTPHeadersParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetExtraHTTPHeaders, p, nil) }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/meshconn/peer.go#L79-L98
func (p *Peer) ReadFrom(b []byte) (n int, remote net.Addr, err error) { c := make(chan struct{}) p.actions <- func() { go func() { // so as not to block loop defer close(c) select { case pkt := <-p.recv: n = copy(b, pkt.Buf) remote = MeshAddr{PeerName: pkt.SrcName, PeerUID: pkt.SrcUID} if n < len(pkt.Buf) { err = ErrShortRead } case <-p.quit: err = ErrPeerClosed } }() } <-c return n, remote, err }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/jenkins/jenkins.go#L135-L137
func (jb *Build) IsFailure() bool { return jb.Result != nil && (*jb.Result == failure || *jb.Result == unstable) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L1286-L1294
func (c APIClient) DeleteFile(repoName string, commitID string, path string) error { _, err := c.PfsAPIClient.DeleteFile( c.Ctx(), &pfs.DeleteFileRequest{ File: NewFile(repoName, commitID, path), }, ) return err }
https://github.com/go-bongo/bongo/blob/761759e31d8fed917377aa7085db01d218ce50d8/main.go#L74-L82
func (m *Connection) CollectionFromDatabase(name string, database string) *Collection { // Just create a new instance - it's cheap and only has name and a database name return &Collection{ Connection: m, Context: m.Context, Database: database, Name: name, } }
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/dependency/sqltypes/value.go#L60-L82
func NewValue(typ querypb.Type, val []byte) (v Value, err error) { switch { case IsSigned(typ): if _, err := strconv.ParseInt(string(val), 0, 64); err != nil { return NULL, err } return MakeTrusted(typ, val), nil case IsUnsigned(typ): if _, err := strconv.ParseUint(string(val), 0, 64); err != nil { return NULL, err } return MakeTrusted(typ, val), nil case IsFloat(typ) || typ == Decimal: if _, err := strconv.ParseFloat(string(val), 64); err != nil { return NULL, err } return MakeTrusted(typ, val), nil case IsQuoted(typ) || typ == Null: return MakeTrusted(typ, val), nil } // All other types are unsafe or invalid. return NULL, fmt.Errorf("invalid type specified for MakeValue: %v", typ) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L2017-L2039
func (c *Client) CreateTeam(org string, team Team) (*Team, error) { c.log("CreateTeam", org, team) if team.Name == "" { return nil, errors.New("team.Name must be non-empty") } if c.fake { return nil, nil } else if c.dry { return &team, nil } path := fmt.Sprintf("/orgs/%s/teams", org) var retTeam Team _, err := c.request(&request{ method: http.MethodPost, path: path, // This accept header enables the nested teams preview. // https://developer.github.com/changes/2017-08-30-preview-nested-teams/ accept: "application/vnd.github.hellcat-preview+json", requestBody: &team, exitCodes: []int{201}, }, &retTeam) return &retTeam, err }
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L713-L718
func (g *Glg) LogFunc(f func() string) error { if g.isModeEnable(LOG) { return g.out(LOG, "%s", f()) } return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/schema.go#L292-L338
func queryCurrentVersion(tx *sql.Tx) (int, error) { versions, err := selectSchemaVersions(tx) if err != nil { return -1, fmt.Errorf("failed to fetch update versions: %v", err) } // Fix bad upgrade code between 30 and 32 hasVersion := func(v int) bool { return shared.IntInSlice(v, versions) } if hasVersion(30) && hasVersion(32) && !hasVersion(31) { err = insertSchemaVersion(tx, 31) if err != nil { return -1, fmt.Errorf("failed to insert missing schema version 31") } versions, err = selectSchemaVersions(tx) if err != nil { return -1, fmt.Errorf("failed to fetch update versions: %v", err) } } // Fix broken schema version between 37 and 38 if hasVersion(37) && !hasVersion(38) { count, err := query.Count(tx, "config", "key = 'cluster.https_address'") if err != nil { return -1, fmt.Errorf("Failed to check if cluster.https_address is set: %v", err) } if count == 1 { // Insert the missing version. err := insertSchemaVersion(tx, 38) if err != nil { return -1, fmt.Errorf("Failed to insert missing schema version 38") } versions = append(versions, 38) } } current := 0 if len(versions) > 0 { err = checkSchemaVersionsHaveNoHoles(versions) if err != nil { return -1, err } current = versions[len(versions)-1] // Highest recorded version } return current, nil }
https://github.com/r3labs/sse/blob/2f90368216802092e9ed520c43e974e11d50438d/event.go#L64-L73
func (e *EventStreamReader) ReadEvent() ([]byte, error) { if e.scanner.Scan() { event := e.scanner.Bytes() return event, nil } if err := e.scanner.Err(); err != nil { return nil, err } return nil, io.EOF }
https://github.com/malice-plugins/go-plugin-utils/blob/9ee76663c3b0a531b8c529f03f12a5a84ff9b61b/clitable/table.go#L48-L54
func New(fields []string) *Table { return &Table{ Fields: fields, Rows: make([]map[string]string, 0), fieldSizes: make(map[string]int), } }
https://github.com/marcuswestin/go-errs/blob/b09b17aacd5a8213690bc30f9ccfe7400be7b380/errs.go#L204-L207
func concatArgs(args ...interface{}) string { res := fmt.Sprintln(args...) return res[0 : len(res)-1] // Remove newline at the end }