_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/helpers.go#L110-L146
func paramsInitializer(action *gen.Action, location int, varName string) string { var fields []string var optionals []*gen.ActionParam varName = fixReserved(varName) for _, param := range action.Params { if param.Location != location { continue } if param.Mandatory { name := param.Name if location == 1 { // QueryParam name = param.QueryName } fields = append(fields, fmt.Sprintf("\"%s\": %s,", name, fixReserved(param.VarName))) } else { optionals = append(optionals, param) } } if len(fields) == 0 && len(optionals) == 0 { return "" } var paramsDecl = fmt.Sprintf("rsapi.APIParams{\n%s\n}", strings.Join(fields, "\n\t")) if len(optionals) == 0 { return fmt.Sprintf("\n%s = %s", varName, paramsDecl) } var inits = make([]string, len(optionals)) for i, opt := range optionals { name := opt.Name if location == 1 { // QueryParam name = opt.QueryName } inits[i] = fmt.Sprintf("\tvar %sOpt = options[\"%s\"]\n\tif %sOpt != nil {\n\t\t%s[\"%s\"] = %sOpt\n\t}", opt.VarName, opt.Name, opt.VarName, varName, name, opt.VarName) } var paramsInits = strings.Join(inits, "\n\t") return fmt.Sprintf("\n%s = %s\n%s", varName, paramsDecl, paramsInits) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/helpers.go#L76-L87
func comment(elems ...string) string { var lines []string for _, e := range elems { lines = append(lines, strings.Split(e, "\n")...) } var trimmed = make([]string, len(lines)) for i, l := range lines { trimmed[i] = strings.TrimLeft(l, " \t") } t := strings.Join(trimmed, "\n") return text.Indent(t, "// ") }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/node.go#L410-L438
func listUnitsByApp(w http.ResponseWriter, r *http.Request, t auth.Token) error { appName := r.URL.Query().Get(":appname") a, err := app.GetByName(appName) if err != nil { if err == appTypes.ErrAppNotFound { return &tsuruErrors.HTTP{ Code: http.StatusNotFound, Message: err.Error(), } } return err } canRead := permission.Check(t, permission.PermAppRead, contextsForApp(a)..., ) if !canRead { return permission.ErrUnauthorized } units, err := a.Units() if err != nil { return err } if len(units) == 0 { w.WriteHeader(http.StatusNoContent) return nil } w.Header().Set("Content-Type", "application/json") return json.NewEncoder(w).Encode(units) }
https://github.com/Diggs/go-backoff/blob/f7b9f7e6b83be485b2e1b3eebba36652c6c4cd8a/backoff.go#L30-L34
func NewBackoff(strategy BackoffStrategy, start time.Duration, limit time.Duration) *Backoff { backoff := Backoff{strategy: strategy, start: start, limit: limit} backoff.Reset() return &backoff }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/migrate/migrate.go#L15-L41
func MigrateAppsCRDs() error { config.Set("kubernetes:use-pool-namespaces", false) defer config.Unset("kubernetes:use-pool-namespaces") prov := kubernetes.GetProvisioner() pools, err := pool.ListAllPools() if err != nil { return errors.Wrap(err, "failed to list pools") } var kubePools []string for _, p := range pools { if p.Provisioner == prov.GetName() { kubePools = append(kubePools, p.Name) } } apps, err := app.List(&app.Filter{Pools: kubePools}) if err != nil { return errors.Wrap(err, "failed to list apps") } multiErr := tsuruerrors.NewMultiError() for _, a := range apps { errProv := prov.Provision(&a) if errProv != nil { multiErr.Add(errProv) } } return multiErr.ToError() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_pools.go#L779-L798
func (c *Cluster) StoragePoolVolumeSnapshotsGetType(volumeName string, volumeType int, poolID int64) ([]string, error) { result := []string{} regexp := volumeName + shared.SnapshotDelimiter length := len(regexp) query := "SELECT name FROM storage_volumes WHERE storage_pool_id=? AND node_id=? AND type=? AND snapshot=? AND SUBSTR(name,1,?)=?" inargs := []interface{}{poolID, c.nodeID, volumeType, true, length, regexp} outfmt := []interface{}{volumeName} dbResults, err := queryScan(c.db, query, inargs, outfmt) if err != nil { return result, err } for _, r := range dbResults { result = append(result, r[0].(string)) } return result, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/images.go#L66-L104
func (c *Cluster) ImagesGetExpired(expiry int64) ([]string, error) { q := `SELECT fingerprint, last_use_date, upload_date FROM images WHERE cached=1` var fpStr string var useStr string var uploadStr string inargs := []interface{}{} outfmt := []interface{}{fpStr, useStr, uploadStr} dbResults, err := queryScan(c.db, q, inargs, outfmt) if err != nil { return []string{}, err } results := []string{} for _, r := range dbResults { // Figure out the expiry timestamp := r[2] if r[1] != "" { timestamp = r[1] } var imageExpiry time.Time err = imageExpiry.UnmarshalText([]byte(timestamp.(string))) if err != nil { return []string{}, err } imageExpiry = imageExpiry.Add(time.Duration(expiry*24) * time.Hour) // Check if expired if imageExpiry.After(time.Now()) { continue } results = append(results, r[0].(string)) } return results, nil }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/db.go#L919-L953
func (db *DB) calculateSize() { newInt := func(val int64) *expvar.Int { v := new(expvar.Int) v.Add(val) return v } totalSize := func(dir string) (int64, int64) { var lsmSize, vlogSize int64 err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { if err != nil { return err } ext := filepath.Ext(path) if ext == ".sst" { lsmSize += info.Size() } else if ext == ".vlog" { vlogSize += info.Size() } return nil }) if err != nil { db.elog.Printf("Got error while calculating total size of directory: %s", dir) } return lsmSize, vlogSize } lsmSize, vlogSize := totalSize(db.opt.Dir) y.LSMSize.Set(db.opt.Dir, newInt(lsmSize)) // If valueDir is different from dir, we'd have to do another walk. if db.opt.ValueDir != db.opt.Dir { _, vlogSize = totalSize(db.opt.ValueDir) } y.VlogSize.Set(db.opt.Dir, newInt(vlogSize)) }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dpdf/gc.go#L146-L156
func (gc *GraphicContext) GetStringBounds(s string) (left, top, right, bottom float64) { _, h := gc.pdf.GetFontSize() d := gc.pdf.GetFontDesc("", "") if d.Ascent == 0 { // not defined (standard font?), use average of 81% top = 0.81 * h } else { top = -float64(d.Ascent) * h / float64(d.Ascent-d.Descent) } return 0, top, gc.pdf.GetStringWidth(s), top + h }
https://github.com/nicholasjackson/bench/blob/2df9635f0ad020b2e82616b0fd87130aaa1ee12e/results/summary.go#L24-L34
func (r Row) String() string { rStr := fmt.Sprintf("Start Time: %v\n", r.StartTime.UTC()) rStr = fmt.Sprintf("%vElapsed Time: %v\n", rStr, r.ElapsedTime) rStr = fmt.Sprintf("%vThreads: %v\n", rStr, r.Threads) rStr = fmt.Sprintf("%vTotal Requests: %v\n", rStr, r.TotalRequests) rStr = fmt.Sprintf("%vAvg Request Time: %v\n", rStr, r.AvgRequestTime) rStr = fmt.Sprintf("%vTotal Success: %v\n", rStr, r.TotalSuccess) rStr = fmt.Sprintf("%vTotal Timeouts: %v\n", rStr, r.TotalTimeouts) return fmt.Sprintf("%vTotal Failures: %v\n", rStr, r.TotalFailures) }
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/outgoing.go#L369-L382
func (op *OutgoingUserProfilePhotosRequest) querystring() querystring { toReturn := map[string]string{} toReturn["user_id"] = fmt.Sprint(op.UserID) if op.Offset != 0 { toReturn["offset"] = fmt.Sprint(op.Offset) } if op.Limit != 0 { toReturn["limit"] = fmt.Sprint(op.Limit) } return querystring(toReturn) }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/frameset.go#L175-L177
func (s *FrameSet) HasFrame(frame int) bool { return s.rangePtr.Contains(frame) }
https://github.com/mattn/go-xmpp/blob/6093f50721ed2204a87a81109ca5a466a5bec6c1/xmpp.go#L566-L569
func (c *Client) IsEncrypted() bool { _, ok := c.conn.(*tls.Conn) return ok }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/count.go#L11-L40
func Count(tx *sql.Tx, table string, where string, args ...interface{}) (int, error) { stmt := fmt.Sprintf("SELECT COUNT(*) FROM %s", table) if where != "" { stmt += fmt.Sprintf(" WHERE %s", where) } rows, err := tx.Query(stmt, args...) if err != nil { return -1, err } defer rows.Close() // For sanity, make sure we read one and only one row. if !rows.Next() { return -1, fmt.Errorf("no rows returned") } var count int err = rows.Scan(&count) if err != nil { return -1, fmt.Errorf("failed to scan count column") } if rows.Next() { return -1, fmt.Errorf("more than one row returned") } err = rows.Err() if err != nil { return -1, err } return count, nil }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/servers/tls.go#L23-L26
func (s *TLS) Start(c context.Context, h http.Handler) error { s.Handler = h return s.ListenAndServeTLS(s.CertFile, s.KeyFile) }
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/base.go#L318-L358
func (b *Base) LogWithTime(level LogLevel, ts time.Time, m *Attrs, msg string, a ...interface{}) error { if !b.shouldLog(level) { return nil } if !b.isInitialized { return ErrNotInitialized } if len(b.config.FilenameAttr) > 0 || len(b.config.LineNumberAttr) > 0 { file, line := getCallerInfo() if m == nil { m = NewAttrs() } if len(b.config.FilenameAttr) > 0 { m.SetAttr(b.config.FilenameAttr, file) } if len(b.config.LineNumberAttr) > 0 { m.SetAttr(b.config.LineNumberAttr, line) } } if len(b.config.SequenceAttr) > 0 { if m == nil { m = NewAttrs() } seq := atomic.AddUint64(&b.sequence, 1) m.SetAttr(b.config.SequenceAttr, seq) } nm := newMessage(ts, b, level, m, msg, a...) for _, hook := range b.hookPreQueue { err := hook.PreQueue(nm) if err != nil { return err } } return b.queue.queueMessage(nm) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/blobinfocache/internal/prioritize/prioritize.go#L82-L100
func destructivelyPrioritizeReplacementCandidatesWithMax(cs []CandidateWithTime, primaryDigest, uncompressedDigest digest.Digest, maxCandidates int) []types.BICReplacementCandidate { // We don't need to use sort.Stable() because nanosecond timestamps are (presumably?) unique, so no two elements should // compare equal. sort.Sort(&candidateSortState{ cs: cs, primaryDigest: primaryDigest, uncompressedDigest: uncompressedDigest, }) resLength := len(cs) if resLength > maxCandidates { resLength = maxCandidates } res := make([]types.BICReplacementCandidate, resLength) for i := range res { res[i] = cs[i].Candidate } return res }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/idmap/idmapset_linux.go#L212-L219
func (e *IdmapEntry) shift_into_ns(id int64) (int64, error) { if id < e.Nsid || id >= e.Nsid+e.Maprange { // this mapping doesn't apply return 0, fmt.Errorf("ID mapping doesn't apply") } return id - e.Nsid + e.Hostid, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/types/devices.go#L17-L26
func (list Devices) Contains(k string, d Device) bool { // If it didn't exist, it's different if list[k] == nil { return false } old := list[k] return deviceEquals(old, d) }
https://github.com/akutz/gotil/blob/6fa2e80bd3ac40f15788cfc3d12ebba49a0add92/gotil.go#L136-L138
func LineReader(r io.Reader) (<-chan string, error) { return lineReader(func() (io.Reader, func(), error) { return r, nil, nil }) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/praxisgen/api_analyzer.go#L40-L68
func (a *APIAnalyzer) Analyze() (*gen.APIDescriptor, error) { descriptor := gen.APIDescriptor{ Version: a.Version, Resources: make(map[string]*gen.Resource), Types: make(map[string]*gen.ObjectDataType), } a.descriptor = &descriptor // Sort resource names so iterations are always done in the same order rawResourceNames := make([]string, len(a.RawResources)) idx := 0 for name := range a.RawResources { rawResourceNames[idx] = name idx++ } sort.Strings(rawResourceNames) // Analyze each resource for _, name := range rawResourceNames { err := a.AnalyzeResource(name, a.RawResources[name], &descriptor) if err != nil { return nil, err } } // We're done a.Registry.FinalizeTypeNames(&descriptor) return &descriptor, nil }
https://github.com/blacklabeldata/namedtuple/blob/c341f1db44f30b8164294aa8605ede42be604aba/schema/lexer.go#L162-L170
func (l *Lexer) next() (r rune) { if l.Pos >= len(l.input) { l.Width = 0 return eof } r, l.Width = utf8.DecodeRuneInString(l.remaining()) l.advance(l.Width) return }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/service/service_instance.go#L212-L230
func (si *ServiceInstance) BindApp(app bind.App, params BindAppParameters, shouldRestart bool, writer io.Writer, evt *event.Event, requestID string) error { args := bindPipelineArgs{ serviceInstance: si, app: app, writer: writer, shouldRestart: shouldRestart, params: params, event: evt, requestID: requestID, } actions := []*action.Action{ bindAppDBAction, bindAppEndpointAction, setBoundEnvsAction, bindUnitsAction, } pipeline := action.NewPipeline(actions...) return pipeline.Execute(&args) }
https://github.com/btcsuite/btclog/blob/84c8d2346e9fc8c7b947e243b9c24e6df9fd206a/log.go#L443-L448
func (l *slog) Critical(args ...interface{}) { lvl := l.Level() if lvl <= LevelCritical { l.b.print("CRT", l.tag, args...) } }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/replication.go#L342-L374
func (r *Raft) heartbeat(s *followerReplication, stopCh chan struct{}) { var failures uint64 req := AppendEntriesRequest{ RPCHeader: r.getRPCHeader(), Term: s.currentTerm, Leader: r.trans.EncodePeer(r.localID, r.localAddr), } var resp AppendEntriesResponse for { // Wait for the next heartbeat interval or forced notify select { case <-s.notifyCh: case <-randomTimeout(r.conf.HeartbeatTimeout / 10): case <-stopCh: return } start := time.Now() if err := r.trans.AppendEntries(s.peer.ID, s.peer.Address, &req, &resp); err != nil { r.logger.Error(fmt.Sprintf("Failed to heartbeat to %v: %v", s.peer.Address, err)) failures++ select { case <-time.After(backoff(failureWait, failures, maxFailureScale)): case <-stopCh: } } else { s.setLastContact() failures = 0 metrics.MeasureSince([]string{"raft", "replication", "heartbeat", string(s.peer.ID)}, start) s.notifyAll(resp.Success) } } }
https://github.com/gravitational/roundtrip/blob/e1e0cd6b05a6bb1791b262e63160038828fd7b3a/client.go#L659-L661
func (r *fileBuffer) rewind() { r.Reader = io.MultiReader(r.cache, r.File.Reader) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/transaction.go#L15-L20
func Transaction(muts ...TransactionMutator) (result *TransactionBuilder) { result = &TransactionBuilder{} result.Mutate(muts...) result.Mutate(Defaults{}) return }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L964-L997
func (r *Reader) Read() (*MergeNode, error) { _k, err := r.pbr.ReadBytes() if err != nil { return nil, err } if r.filter != nil { for { if r.filter(_k) { break } _, err = r.pbr.ReadBytes() if err != nil { return nil, err } _k, err = r.pbr.ReadBytes() if err != nil { return nil, err } } } k := make([]byte, len(_k)) copy(k, _k) _v, err := r.pbr.ReadBytes() if err != nil { return nil, err } v := make([]byte, len(_v)) copy(v, _v) return &MergeNode{ k: k, v: v, }, nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/stm.go#L197-L205
func (rs readSet) first() int64 { ret := int64(math.MaxInt64 - 1) for _, resp := range rs { if rev := resp.Header.Revision; rev < ret { ret = rev } } return ret }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/response.go#L28-L31
func (w *Response) Write(b []byte) (int, error) { w.Size = binary.Size(b) return w.ResponseWriter.Write(b) }
https://github.com/coreos/go-semver/blob/e214231b295a8ea9479f11b70b35d5acf3556d9b/semver/semver.go#L287-L292
func validateIdentifier(id string) error { if id != "" && !reIdentifier.MatchString(id) { return fmt.Errorf("%s is not a valid semver identifier", id) } return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/statusreconciler/controller.go#L139-L153
func (c *Controller) Run(stop <-chan os.Signal, changes <-chan config.Delta) { for { select { case change := <-changes: start := time.Now() if err := c.reconcile(change); err != nil { logrus.WithError(err).Error("Error reconciling statuses.") } logrus.WithField("duration", fmt.Sprintf("%v", time.Since(start))).Info("Statuses reconciled") case <-stop: logrus.Info("status-reconciler is shutting down...") return } } }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/helpers.go#L76-L89
func L(m Model, flag string, force bool) string { // lookup fields fields, _ := Init(m).Meta().FlaggedFields[flag] if len(fields) > 1 || (force && len(fields) == 0) { panic(fmt.Sprintf(`coal: no or multiple fields flagged as "%s" found on "%s"`, flag, m.Meta().Name)) } // return name if found if len(fields) > 0 { return fields[0].Name } return "" }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/db/storage/storage.go#L95-L97
func (s *Storage) Collection(name string) *Collection { return &Collection{Collection: s.session.DB(s.dbname).C(name)} }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3753-L3760
func (u ManageDataResult) ArmForSwitch(sw int32) (string, bool) { switch ManageDataResultCode(sw) { case ManageDataResultCodeManageDataSuccess: return "", true default: return "", true } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logger/format.go#L10-L17
func Pretty(input interface{}) string { pretty, err := json.MarshalIndent(input, "\t", "\t") if err != nil { return fmt.Sprintf("%v", input) } return fmt.Sprintf("\n\t%s", pretty) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/transport/timeout_transport.go#L27-L51
func NewTimeoutTransport(info TLSInfo, dialtimeoutd, rdtimeoutd, wtimeoutd time.Duration) (*http.Transport, error) { tr, err := NewTransport(info, dialtimeoutd) if err != nil { return nil, err } if rdtimeoutd != 0 || wtimeoutd != 0 { // the timed out connection will timeout soon after it is idle. // it should not be put back to http transport as an idle connection for future usage. tr.MaxIdleConnsPerHost = -1 } else { // allow more idle connections between peers to avoid unnecessary port allocation. tr.MaxIdleConnsPerHost = 1024 } tr.Dial = (&rwTimeoutDialer{ Dialer: net.Dialer{ Timeout: dialtimeoutd, KeepAlive: 30 * time.Second, }, rdtimeoutd: rdtimeoutd, wtimeoutd: wtimeoutd, }).Dial return tr, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/gateway.go#L516-L545
func (g *Gateway) currentRaftNodes() ([]db.RaftNode, error) { if g.raft == nil { return nil, raft.ErrNotLeader } servers, err := g.raft.Servers() if err != nil { return nil, err } provider := raftAddressProvider{db: g.db} nodes := make([]db.RaftNode, len(servers)) for i, server := range servers { address, err := provider.ServerAddr(server.ID) if err != nil { if err != db.ErrNoSuchObject { return nil, errors.Wrap(err, "Failed to fetch raft server address") } // Use the initial address as fallback. This is an edge // case that happens when a new leader is elected and // its raft_nodes table is not fully up-to-date yet. address = server.Address } id, err := strconv.Atoi(string(server.ID)) if err != nil { return nil, errors.Wrap(err, "Non-numeric server ID") } nodes[i].ID = int64(id) nodes[i].Address = string(address) } return nodes, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cdp/types.go#L35-L37
func WithExecutor(parent context.Context, executor Executor) context.Context { return context.WithValue(parent, executorKey, executor) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cachestorage/easyjson.go#L1112-L1116
func (v DataEntry) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoCachestorage9(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L9494-L9496
func (api *API) RightScriptAttachmentLocator(href string) *RightScriptAttachmentLocator { return &RightScriptAttachmentLocator{Href(href), api} }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L484-L502
func cephRBDVolumeSnapshotRename(clusterName string, poolName string, volumeName string, volumeType string, oldSnapshotName string, newSnapshotName string, userName string) error { _, err := shared.RunCommand( "rbd", "--id", userName, "--cluster", clusterName, "snap", "rename", fmt.Sprintf("%s/%s_%s@%s", poolName, volumeType, volumeName, oldSnapshotName), fmt.Sprintf("%s/%s_%s@%s", poolName, volumeType, volumeName, newSnapshotName)) if err != nil { return err } return nil }
https://github.com/olorin/nagiosplugin/blob/893f9702af4ea1e2dc4cd6528cbdcdb3dc7ca064/check.go#L81-L84
func (c *Check) AddResultf(status Status, format string, v ...interface{}) { msg := fmt.Sprintf(format, v...) c.AddResult(status, msg) }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/subchannel.go#L81-L92
func (c *SubChannel) BeginCall(ctx context.Context, methodName string, callOptions *CallOptions) (*OutboundCall, error) { if callOptions == nil { callOptions = defaultCallOptions } peer, err := c.peers.Get(callOptions.RequestState.PrevSelectedPeers()) if err != nil { return nil, err } return peer.BeginCall(ctx, c.ServiceName(), methodName, callOptions) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/transaction.go#L247-L256
func (m MemoText) MutateTransaction(o *TransactionBuilder) (err error) { if len([]byte(m.Value)) > MemoTextMaxLength { err = errors.New("Memo too long; over 28 bytes") return } o.TX.Memo, err = xdr.NewMemo(xdr.MemoTypeMemoText, m.Value) return }
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nitro.go#L512-L516
func SnapshotSize(p unsafe.Pointer) int { s := (*Snapshot)(p) return int(unsafe.Sizeof(s.sn) + unsafe.Sizeof(s.refCount) + unsafe.Sizeof(s.db) + unsafe.Sizeof(s.count) + unsafe.Sizeof(s.gclist)) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pkg/tracing/tracing.go#L186-L190
func CloseAndReportTraces() { if c, ok := opentracing.GlobalTracer().(io.Closer); ok { c.Close() } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/watch.go#L713-L729
func (w *watchGrpcStream) serveWatchClient(wc pb.Watch_WatchClient) { for { resp, err := wc.Recv() if err != nil { select { case w.errc <- err: case <-w.donec: } return } select { case w.respc <- resp: case <-w.donec: return } } }
https://github.com/brankas/sentinel/blob/0ff081867c31a45cb71f5976ea6144fd06a557b5/sentinel.go#L124-L134
func (s *Sentinel) ShutdownIgnore(err error) bool { if err == nil { return true } for _, f := range s.ignoreErrors { if z := f(err); z { return true } } return false }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/ep_command.go#L34-L46
func NewEndpointCommand() *cobra.Command { ec := &cobra.Command{ Use: "endpoint <subcommand>", Short: "Endpoint related commands", } ec.PersistentFlags().BoolVar(&epClusterEndpoints, "cluster", false, "use all endpoints from the cluster member list") ec.AddCommand(newEpHealthCommand()) ec.AddCommand(newEpStatusCommand()) ec.AddCommand(newEpHashKVCommand()) return ec }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/quota/quota.go#L46-L57
func (s *QuotaService) SetLimit(appName string, limit int) error { q, err := s.Storage.Get(appName) if err != nil { return err } if limit < 0 { limit = -1 } else if limit < q.InUse { return quota.ErrLimitLowerThanAllocated } return s.Storage.SetLimit(appName, limit) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L1248-L1252
func (v *EventTargetInfoChanged) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoTarget13(&r, v) return r.Error() }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/merger/fix.go#L190-L199
func removeLegacyGoRepository(f *rule.File) { for _, l := range f.Loads { if l.Name() == "@io_bazel_rules_go//go:def.bzl" { l.Remove("go_repository") if l.IsEmpty() { l.Delete() } } } }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/deploy/assets/assets.go#L1238-L1247
func AmazonSecret(region, bucket, id, secret, token, distribution string) map[string][]byte { return map[string][]byte{ "amazon-region": []byte(region), "amazon-bucket": []byte(bucket), "amazon-id": []byte(id), "amazon-secret": []byte(secret), "amazon-token": []byte(token), "amazon-distribution": []byte(distribution), } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L910-L916
func SearchInResource(frameID cdp.FrameID, url string, query string) *SearchInResourceParams { return &SearchInResourceParams{ FrameID: frameID, URL: url, Query: query, } }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/export.go#L130-L151
func FrameSet_Frames(id FrameSetId, out *C.int) C.int { fs, ok := sFrameSets.Get(id) if !ok { return C.int(0) } goframes := fs.Frames() size := len(goframes) if size == 0 { return C.int(0) } intSize := int(unsafe.Sizeof(C.int(0))) startPtr := uintptr(unsafe.Pointer(out)) for i, frame := range goframes { ptr := unsafe.Pointer(startPtr + uintptr(intSize*i)) *(*C.int)(ptr) = C.int(int32(frame)) } return C.int(size) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/pfsdb/pfsdb.go#L81-L90
func OpenCommits(etcdClient *etcd.Client, etcdPrefix string) col.Collection { return col.NewCollection( etcdClient, path.Join(etcdPrefix, openCommitsPrefix), nil, &pfs.Commit{}, nil, nil, ) }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/ghttp/handlers.go#L61-L65
func VerifyMimeType(mimeType string) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { Expect(strings.Split(req.Header.Get("Content-Type"), ";")[0]).Should(Equal(mimeType)) } }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/wood/asset_server.go#L17-L41
func NewAssetServer(prefix, directory string) http.Handler { // ensure prefix prefix = "/" + strings.Trim(prefix, "/") // create dir server dir := http.Dir(directory) // create file server fs := http.FileServer(dir) h := func(w http.ResponseWriter, r *http.Request) { // pre-check if file does exist f, err := dir.Open(r.URL.Path) if err != nil { r.URL.Path = "/" } else if f != nil { _ = f.Close() } // serve file fs.ServeHTTP(w, r) } return http.StripPrefix(prefix, http.HandlerFunc(h)) }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/context.go#L63-L65
func (o Operation) Write() bool { return o == Create || o == Update || o == Delete }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_volumes.go#L73-L86
func (r *ProtocolLXD) CreateStoragePoolVolume(pool string, volume api.StorageVolumesPost) error { if !r.HasExtension("storage") { return fmt.Errorf("The server is missing the required \"storage\" API extension") } // Send the request path := fmt.Sprintf("/storage-pools/%s/volumes/%s", url.QueryEscape(pool), url.QueryEscape(volume.Type)) _, _, err := r.query("POST", path, volume, "") if err != nil { return err } return nil }
https://github.com/malice-plugins/go-plugin-utils/blob/9ee76663c3b0a531b8c529f03f12a5a84ff9b61b/database/elasticsearch/elasticsearch.go#L49-L79
func (db *Database) getURL() { // If not set use defaults if len(strings.TrimSpace(db.Index)) == 0 { db.Index = defaultIndex } if len(strings.TrimSpace(db.Type)) == 0 { db.Type = defaultType } if len(strings.TrimSpace(db.Host)) == 0 { db.Host = defaultHost } if len(strings.TrimSpace(db.Port)) == 0 { db.Port = defaultPort } // If user set URL param use it if len(strings.TrimSpace(db.URL)) == 0 { db.URL = defaultURL } // If running in docker use `elasticsearch` if _, exists := os.LookupEnv("MALICE_IN_DOCKER"); exists { log.WithField("elasticsearch", db.URL).Debug("running malice in docker") // TODO: change MALICE_ELASTICSEARCH to MALICE_ELASTICSEARCH_HOST db.URL = utils.Getopt("MALICE_ELASTICSEARCH_URL", fmt.Sprintf("http://%s:%s", "elasticsearch", db.Port)) return } db.URL = utils.Getopts(db.URL, "MALICE_ELASTICSEARCH_URL", fmt.Sprintf("http://%s:%s", db.Host, db.Port)) }
https://github.com/stvp/pager/blob/17442a04891b757880b72d926848df3e3af06c15/pager.go#L155-L174
func post(reqBody []byte) (respBody map[string]string, err error) { resp, err := http.Post(endpoint, "application/json", bytes.NewReader(reqBody)) if err != nil { return nil, err } defer resp.Body.Close() bodyBytes, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("%s: %s", resp.Status, string(bodyBytes)) } respBody = map[string]string{} err = json.Unmarshal(bodyBytes, &respBody) return respBody, err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/easyjson.go#L1945-L1949
func (v EventInspectModeCanceled) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoOverlay20(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/examples/consumer/goconsumer/client.go#L137-L143
func (c *Client) Run() { http.HandleFunc("/login", c.loginHandler) http.HandleFunc("/logout", c.logoutHandler) http.HandleFunc("/", c.viewHandler) fmt.Println("User svc client running on port 8081") http.ListenAndServe(":8081", nil) }
https://github.com/gravitational/roundtrip/blob/e1e0cd6b05a6bb1791b262e63160038828fd7b3a/client.go#L354-L379
func (c *Client) Get(ctx context.Context, endpoint string, params url.Values) (*Response, error) { // If the sanitizer is enabled, make sure the requested path is safe. if c.sanitizerEnabled { err := isPathSafe(endpoint) if err != nil { return nil, err } } baseUrl, err := url.Parse(endpoint) if err != nil { return nil, err } baseUrl.RawQuery = params.Encode() tracer := c.newTracer() return tracer.Done(c.RoundTrip(func() (*http.Response, error) { req, err := http.NewRequest(http.MethodGet, baseUrl.String(), nil) if err != nil { return nil, err } req = req.WithContext(ctx) c.addAuth(req) tracer.Start(req) return c.client.Do(req) })) }
https://github.com/antlinker/go-dirtyfilter/blob/533f538ffaa112776b1258c3db63e6f55648e18b/manager.go#L14-L29
func NewDirtyManager(store DirtyStore, checkInterval ...time.Duration) *DirtyManager { interval := DefaultCheckInterval if len(checkInterval) > 0 { interval = checkInterval[0] } manage := &DirtyManager{ store: store, version: store.Version(), filter: NewNodeChanFilter(store.Read()), interval: interval, } go func() { manage.checkVersion() }() return manage }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/plugin/vault/pachyderm/renew.go#L71-L92
func renewUserCredentials(ctx context.Context, pachdAddress string, adminToken string, userToken string, ttl time.Duration) error { // Setup a single use client w the given admin token / address client, err := pclient.NewFromAddress(pachdAddress) if err != nil { return err } defer client.Close() // avoid leaking connections client = client.WithCtx(ctx) client.SetAuthToken(adminToken) _, err = client.AuthAPIClient.ExtendAuthToken(client.Ctx(), &auth.ExtendAuthTokenRequest{ Token: userToken, TTL: int64(ttl.Seconds()), }) if err != nil { return err } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/target.go#L247-L256
func (p *GetBrowserContextsParams) Do(ctx context.Context) (browserContextIds []BrowserContextID, err error) { // execute var res GetBrowserContextsReturns err = cdp.Execute(ctx, CommandGetBrowserContexts, nil, &res) if err != nil { return nil, err } return res.BrowserContextIds, nil }
https://github.com/go-audio/transforms/blob/51830ccc35a5ce4be9d09b1d1f3f82dad376c240/quantize.go#L10-L20
func Quantize(buf *audio.FloatBuffer, bitDepth int) { if buf == nil { return } max := math.Pow(2, float64(bitDepth)) - 1 bufLen := len(buf.Data) for i := 0; i < bufLen; i++ { buf.Data[i] = round((buf.Data[i]+1)*max)/max - 1.0 } }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L616-L619
func (r *Rule) SetKind(kind string) { r.kind = kind r.updated = true }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/types.go#L155-L171
func (t *Modifier) UnmarshalEasyJSON(in *jlexer.Lexer) { switch Modifier(in.Int64()) { case ModifierNone: *t = ModifierNone case ModifierAlt: *t = ModifierAlt case ModifierCtrl: *t = ModifierCtrl case ModifierMeta: *t = ModifierMeta case ModifierShift: *t = ModifierShift default: in.AddError(errors.New("unknown Modifier value")) } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L640-L652
func (r *ProtocolLXD) RefreshImage(fingerprint string) (Operation, error) { if !r.HasExtension("image_force_refresh") { return nil, fmt.Errorf("The server is missing the required \"image_force_refresh\" API extension") } // Send the request op, _, err := r.queryOperation("POST", fmt.Sprintf("/images/%s/refresh", url.QueryEscape(fingerprint)), nil, "") if err != nil { return nil, err } return op, nil }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/mex.go#L235-L247
func (mex *messageExchange) shutdown() { // The reader and writer side can both hit errors and try to shutdown the mex, // so we ensure that it's only shut down once. if !mex.shutdownAtomic.CAS(false, true) { return } if mex.errChNotified.CAS(false, true) { mex.errCh.Notify(errMexShutdown) } mex.mexset.removeExchange(mex.msgID) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/performance/easyjson.go#L324-L328
func (v GetMetricsParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoPerformance3(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v3compactor/periodic.go#L213-L217
func (pc *Periodic) Resume() { pc.mu.Lock() pc.paused = false pc.mu.Unlock() }
https://github.com/blacksails/cgp/blob/570ac705cf2d7a9235d911d00b6f976ab3386c2f/alias.go#L30-L42
func (acc *Account) Aliases() ([]*Alias, error) { var vl valueList err := acc.Domain.cgp.request(listAliases{Param: fmt.Sprintf("%s@%s", acc.Name, acc.Domain.Name)}, &vl) if err != nil { return []*Alias{}, err } vals := vl.compact() as := make([]*Alias, len(vals)) for i, v := range vals { as[i] = acc.Alias(v) } return as, nil }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/metadata.go#L43-L45
func (c *MetadataWriter) WriteHeader(pkg string, w io.Writer) error { return c.headerTmpl.Execute(w, pkg) }
https://github.com/ipfs/go-ipfs-api/blob/a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32/shell.go#L500-L504
func (s *Shell) SwarmPeers(ctx context.Context) (*SwarmConnInfos, error) { v := &SwarmConnInfos{} err := s.Request("swarm/peers").Exec(ctx, &v) return v, err }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/genny/newapp/core/options.go#L30-L95
func (opts *Options) Validate() error { if opts.App.IsZero() { opts.App = meta.New(".") } if len(opts.Version) == 0 { opts.Version = runtime.Version } if opts.Pop != nil { if opts.Pop.App.IsZero() { opts.Pop.App = opts.App } if err := opts.Pop.Validate(); err != nil { return err } } if opts.CI != nil { if opts.CI.App.IsZero() { opts.CI.App = opts.App } if err := opts.CI.Validate(); err != nil { return err } } if opts.Refresh != nil { if opts.Refresh.App.IsZero() { opts.Refresh.App = opts.App } if err := opts.Refresh.Validate(); err != nil { return err } } if opts.VCS != nil { if opts.VCS.App.IsZero() { opts.VCS.App = opts.App } if err := opts.VCS.Validate(); err != nil { return err } } if opts.App.WithModules && opts.App.WithDep { return ErrGoModulesWithDep } name := strings.ToLower(opts.App.Name.String()) fb := append(opts.ForbiddenNames, "buffalo", "test", "dev") for _, n := range fb { rx, err := regexp.Compile(n) if err != nil { return err } if rx.MatchString(name) { return fmt.Errorf("name %s is not allowed, try a different application name", opts.App.Name) } } if !nameRX.MatchString(name) { return fmt.Errorf("name %s is not allowed, application name can only contain [a-Z0-9-_]", opts.App.Name) } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L2939-L2943
func (v PseudoElementMatches) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss26(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L120-L123
func (p CallFunctionOnParams) WithSilent(silent bool) *CallFunctionOnParams { p.Silent = silent return &p }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/easyjson.go#L941-L945
func (v *GetPlaybackRateReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoAnimation9(&r, v) return r.Error() }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/json.go#L23-L66
func paranoidUnmarshalJSONObject(data []byte, fieldResolver func(string) interface{}) error { seenKeys := map[string]struct{}{} dec := json.NewDecoder(bytes.NewReader(data)) t, err := dec.Token() if err != nil { return jsonFormatError(err.Error()) } if t != json.Delim('{') { return jsonFormatError(fmt.Sprintf("JSON object expected, got \"%s\"", t)) } for { t, err := dec.Token() if err != nil { return jsonFormatError(err.Error()) } if t == json.Delim('}') { break } key, ok := t.(string) if !ok { // Coverage: This should never happen, dec.Token() rejects non-string-literals in this state. return jsonFormatError(fmt.Sprintf("Key string literal expected, got \"%s\"", t)) } if _, ok := seenKeys[key]; ok { return jsonFormatError(fmt.Sprintf("Duplicate key \"%s\"", key)) } seenKeys[key] = struct{}{} valuePtr := fieldResolver(key) if valuePtr == nil { return jsonFormatError(fmt.Sprintf("Unknown key \"%s\"", key)) } // This works like json.Unmarshal, in particular it allows us to implement UnmarshalJSON to implement strict parsing of the field value. if err := dec.Decode(valuePtr); err != nil { return jsonFormatError(err.Error()) } } if _, err := dec.Token(); err != io.EOF { return jsonFormatError("Unexpected data after JSON object") } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L2537-L2541
func (v *RestartFrameReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger25(&r, v) return r.Error() }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/exec/exec.go#L296-L317
func lookExtensions(path, dir string) (string, error) { if filepath.Base(path) == path { path = filepath.Join(".", path) } if dir == "" { return exec.LookPath(path) } if filepath.VolumeName(path) != "" { return exec.LookPath(path) } if len(path) > 1 && os.IsPathSeparator(path[0]) { return exec.LookPath(path) } dirandpath := filepath.Join(dir, path) // We assume that LookPath will only add file extension. lp, err := exec.LookPath(dirandpath) if err != nil { return "", err } ext := strings.TrimPrefix(lp, dirandpath) return path + ext, nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/admin.go#L24-L42
func (c APIClient) Extract(objects bool, f func(op *admin.Op) error) error { extractClient, err := c.AdminAPIClient.Extract(c.Ctx(), &admin.ExtractRequest{NoObjects: !objects}) if err != nil { return grpcutil.ScrubGRPC(err) } for { op, err := extractClient.Recv() if err == io.EOF { break } if err != nil { return grpcutil.ScrubGRPC(err) } if err := f(op); err != nil { return err } } return nil }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/genny/actions/build_actions.go#L14-L27
func buildActions(pres *presenter) genny.RunFn { return func(r *genny.Runner) error { fn := fmt.Sprintf("actions/%s.go", pres.Name.File()) xf, err := r.FindFile(fn) if err != nil { return buildNewActions(fn, pres)(r) } if err := appendActions(xf, pres)(r); err != nil { return err } return nil } }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/resolve/index.go#L217-L230
func (ix *RuleIndex) FindRulesByImport(imp ImportSpec, lang string) []FindResult { matches := ix.importMap[imp] results := make([]FindResult, 0, len(matches)) for _, m := range matches { if ix.mrslv(m.rule, "").Name() != lang { continue } results = append(results, FindResult{ Label: m.label, Embeds: m.embeds, }) } return results }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/genny/newapp/web/options.go#L19-L51
func (opts *Options) Validate() error { if opts.Options == nil { opts.Options = &core.Options{} } if err := opts.Options.Validate(); err != nil { return err } if opts.Docker != nil { if opts.Docker.App.IsZero() { opts.Docker.App = opts.App } if err := opts.Docker.Validate(); err != nil { return err } } if opts.Webpack != nil { if opts.Webpack.App.IsZero() { opts.Webpack.App = opts.App } if err := opts.Webpack.Validate(); err != nil { return err } } if opts.Standard != nil && opts.Webpack != nil { return errors.New("you can not use both webpack and standard generators") } return nil }
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L265-L269
func (l *Logger) Panic(args ...interface{}) { msg := fmt.Sprint(args...) l.Output(2, LevelError, msg) panic(msg) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/collection/transaction.go#L92-L95
func newSTMReadCommitted(ctx context.Context, c *v3.Client, apply func(STM) error) (*v3.TxnResponse, error) { s := &stmReadCommitted{stm{client: c, ctx: ctx, getOpts: []v3.OpOption{v3.WithSerializable()}}} return runSTM(s, apply, true) }
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/english/common.go#L118-L202
func stemSpecialWord(word string) (stemmed string) { switch word { case "skis": stemmed = "ski" case "skies": stemmed = "sky" case "dying": stemmed = "die" case "lying": stemmed = "lie" case "tying": stemmed = "tie" case "idly": stemmed = "idl" case "gently": stemmed = "gentl" case "ugly": stemmed = "ugli" case "early": stemmed = "earli" case "only": stemmed = "onli" case "singly": stemmed = "singl" case "sky": stemmed = "sky" case "news": stemmed = "news" case "howe": stemmed = "howe" case "atlas": stemmed = "atlas" case "cosmos": stemmed = "cosmos" case "bias": stemmed = "bias" case "andes": stemmed = "andes" case "inning": stemmed = "inning" case "innings": stemmed = "inning" case "outing": stemmed = "outing" case "outings": stemmed = "outing" case "canning": stemmed = "canning" case "cannings": stemmed = "canning" case "herring": stemmed = "herring" case "herrings": stemmed = "herring" case "earring": stemmed = "earring" case "earrings": stemmed = "earring" case "proceed": stemmed = "proceed" case "proceeds": stemmed = "proceed" case "proceeded": stemmed = "proceed" case "proceeding": stemmed = "proceed" case "exceed": stemmed = "exceed" case "exceeds": stemmed = "exceed" case "exceeded": stemmed = "exceed" case "exceeding": stemmed = "exceed" case "succeed": stemmed = "succeed" case "succeeds": stemmed = "succeed" case "succeeded": stemmed = "succeed" case "succeeding": stemmed = "succeed" } return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/webaudio/webaudio.go#L77-L86
func (p *GetRealtimeDataParams) Do(ctx context.Context) (realtimeData *ContextRealtimeData, err error) { // execute var res GetRealtimeDataReturns err = cdp.Execute(ctx, CommandGetRealtimeData, p, &res) if err != nil { return nil, err } return res.RealtimeData, nil }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/db.go#L1139-L1150
func (db *DB) KeySplits(prefix []byte) []string { var splits []string for _, ti := range db.Tables() { // We don't use ti.Left, because that has a tendency to store !badger // keys. if bytes.HasPrefix(ti.Right, prefix) { splits = append(splits, string(ti.Right)) } } sort.Strings(splits) return splits }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L189-L201
func (f *FakeClient) DeleteStaleComments(org, repo string, number int, comments []github.IssueComment, isStale func(github.IssueComment) bool) error { if comments == nil { comments, _ = f.ListIssueComments(org, repo, number) } for _, comment := range comments { if isStale(comment) { if err := f.DeleteComment(org, repo, comment.ID); err != nil { return fmt.Errorf("failed to delete stale comment with ID '%d'", comment.ID) } } } return nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/server/driver.go#L2819-L2850
func (d *driver) fileHistory(pachClient *client.APIClient, file *pfs.File, history int64, f func(*pfs.FileInfo) error) error { var fi *pfs.FileInfo for { _fi, err := d.inspectFile(pachClient, file) if err != nil { if _, ok := err.(pfsserver.ErrFileNotFound); ok { return f(fi) } return err } if fi != nil && bytes.Compare(fi.Hash, _fi.Hash) != 0 { if err := f(fi); err != nil { return err } if history > 0 { history-- if history == 0 { return nil } } } fi = _fi ci, err := d.inspectCommit(pachClient, file.Commit, pfs.CommitState_STARTED) if err != nil { return err } if ci.ParentCommit == nil { return f(fi) } file.Commit = ci.ParentCommit } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxc/utils.go#L123-L144
func containerDeviceAdd(client lxd.ContainerServer, name string, devName string, dev map[string]string) error { // Get the container entry container, etag, err := client.GetContainer(name) if err != nil { return err } // Check if the device already exists _, ok := container.Devices[devName] if ok { return fmt.Errorf(i18n.G("Device already exists: %s"), devName) } container.Devices[devName] = dev op, err := client.UpdateContainer(name, container.Writable(), etag) if err != nil { return err } return op.Wait() }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L1187-L1196
func (u LedgerEntryData) GetData() (result DataEntry, ok bool) { armName, _ := u.ArmForSwitch(int32(u.Type)) if armName == "Data" { result = *u.Data ok = true } return }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/stats/statsdreporter.go#L40-L47
func NewStatsdReporter(addr, prefix string) (tchannel.StatsReporter, error) { client, err := statsd.NewBufferedClient(addr, prefix, time.Second, 0) if err != nil { return nil, err } return NewStatsdReporterClient(client), nil }