_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/innkeeperclient/fake/ik_client.go#L25-L40
func (s *IKClient) ProvisionHost(sku string, tenantid string) (result *innkeeperclient.ProvisionHostResponse, err error) { s.SpyTenantID.Store(tenantid) result = new(innkeeperclient.ProvisionHostResponse) result.Data = make([]innkeeperclient.RequestData, 1) if len(s.FakeStatus) > s.cnt { result.Status = s.FakeStatus[s.cnt] } if len(s.FakeData) > s.cnt { result.Data[0] = s.FakeData[s.cnt] } if len(s.FakeMessage) > s.cnt { result.Message = s.FakeMessage[s.cnt] } s.cnt++ return }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/rpclog/grpc.go#L31-L36
func ClientOptions(log ttnlog.Interface) []grpc.DialOption { return []grpc.DialOption{ grpc.WithUnaryInterceptor(UnaryClientInterceptor(log)), grpc.WithStreamInterceptor(StreamClientInterceptor(log)), } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L5741-L5745
func (v FontFace) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss50(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/knq/sdhook/blob/41b9ccbff0b5fa5a56fbdccf2eb8653e7afe8d4b/opts.go#L226-L235
func GoogleServiceAccountCredentialsFile(path string) Option { return func(sh *StackdriverHook) error { buf, err := ioutil.ReadFile(path) if err != nil { return err } return GoogleServiceAccountCredentialsJSON(buf)(sh) } }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/archive/transport.go#L152-L154
func (ref archiveReference) NewImageDestination(ctx context.Context, sys *types.SystemContext) (types.ImageDestination, error) { return newImageDestination(sys, ref) }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/apps/get_apps_app_parameters.go#L110-L113
func (o *GetAppsAppParams) WithApp(app string) *GetAppsAppParams { o.SetApp(app) return o }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/deck/jobs/jobs.go#L101-L109
func (ja *JobAgent) Start() { ja.tryUpdate() go func() { t := time.Tick(period) for range t { ja.tryUpdate() } }() }
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/render.go#L60-L81
func (render *Render) RegisterViewPath(paths ...string) { for _, pth := range paths { if filepath.IsAbs(pth) { render.ViewPaths = append(render.ViewPaths, pth) render.AssetFileSystem.RegisterPath(pth) } else { if absPath, err := filepath.Abs(pth); err == nil && isExistingDir(absPath) { render.ViewPaths = append(render.ViewPaths, absPath) render.AssetFileSystem.RegisterPath(absPath) } else if isExistingDir(filepath.Join(utils.AppRoot, "vendor", pth)) { render.AssetFileSystem.RegisterPath(filepath.Join(utils.AppRoot, "vendor", pth)) } else { for _, gopath := range utils.GOPATH() { if p := filepath.Join(gopath, "src", pth); isExistingDir(p) { render.ViewPaths = append(render.ViewPaths, p) render.AssetFileSystem.RegisterPath(p) } } } } } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/election.go#L132-L145
func (e *Election) Resign(ctx context.Context) (err error) { if e.leaderSession == nil { return nil } client := e.session.Client() cmp := v3.Compare(v3.CreateRevision(e.leaderKey), "=", e.leaderRev) resp, err := client.Txn(ctx).If(cmp).Then(v3.OpDelete(e.leaderKey)).Commit() if err == nil { e.hdr = resp.Header } e.leaderKey = "" e.leaderSession = nil return err }
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/internal/value/sort.go#L36-L104
func isLess(x, y reflect.Value) bool { switch x.Type().Kind() { case reflect.Bool: return !x.Bool() && y.Bool() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return x.Int() < y.Int() case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return x.Uint() < y.Uint() case reflect.Float32, reflect.Float64: fx, fy := x.Float(), y.Float() return fx < fy || math.IsNaN(fx) && !math.IsNaN(fy) case reflect.Complex64, reflect.Complex128: cx, cy := x.Complex(), y.Complex() rx, ix, ry, iy := real(cx), imag(cx), real(cy), imag(cy) if rx == ry || (math.IsNaN(rx) && math.IsNaN(ry)) { return ix < iy || math.IsNaN(ix) && !math.IsNaN(iy) } return rx < ry || math.IsNaN(rx) && !math.IsNaN(ry) case reflect.Ptr, reflect.UnsafePointer, reflect.Chan: return x.Pointer() < y.Pointer() case reflect.String: return x.String() < y.String() case reflect.Array: for i := 0; i < x.Len(); i++ { if isLess(x.Index(i), y.Index(i)) { return true } if isLess(y.Index(i), x.Index(i)) { return false } } return false case reflect.Struct: for i := 0; i < x.NumField(); i++ { if isLess(x.Field(i), y.Field(i)) { return true } if isLess(y.Field(i), x.Field(i)) { return false } } return false case reflect.Interface: vx, vy := x.Elem(), y.Elem() if !vx.IsValid() || !vy.IsValid() { return !vx.IsValid() && vy.IsValid() } tx, ty := vx.Type(), vy.Type() if tx == ty { return isLess(x.Elem(), y.Elem()) } if tx.Kind() != ty.Kind() { return vx.Kind() < vy.Kind() } if tx.String() != ty.String() { return tx.String() < ty.String() } if tx.PkgPath() != ty.PkgPath() { return tx.PkgPath() < ty.PkgPath() } // This can happen in rare situations, so we fallback to just comparing // the unique pointer for a reflect.Type. This guarantees deterministic // ordering within a program, but it is obviously not stable. return reflect.ValueOf(vx.Type()).Pointer() < reflect.ValueOf(vy.Type()).Pointer() default: // Must be Func, Map, or Slice; which are not comparable. panic(fmt.Sprintf("%T is not comparable", x.Type())) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L5126-L5130
func (v *CallFrame) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger48(&r, v) return r.Error() }
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/skiplist/stats.go#L30-L50
func (report *StatsReport) Apply(s *Stats) { var totalNextPtrs int var totalNodes int report.ReadConflicts += s.readConflicts report.InsertConflicts += s.insertConflicts for i, c := range s.levelNodesCount { report.NodeDistribution[i] += c nodesAtlevel := report.NodeDistribution[i] totalNodes += int(nodesAtlevel) totalNextPtrs += (i + 1) * int(nodesAtlevel) } report.SoftDeletes += s.softDeletes report.NodeCount = totalNodes report.NextPointersPerNode = float64(totalNextPtrs) / float64(totalNodes) report.NodeAllocs += s.nodeAllocs report.NodeFrees += s.nodeFrees report.Memory += s.usedBytes }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/auth.go#L108-L115
func newCookieSigner(builder loginRequestBuilder, accountID int) Authenticator { return &cookieSigner{ builder: builder, accountID: accountID, refreshAt: time.Now().Add(-2 * time.Minute), client: httpclient.NewNoRedirect(), } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/profiler.go#L97-L99
func (p *SetSamplingIntervalParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetSamplingInterval, p, nil) }
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L803-L808
func SuccessFunc(f func() string) error { if isModeEnable(OK) { return glg.out(OK, "%s", f()) } return nil }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/service/service_instance.go#L292-L313
func (si *ServiceInstance) UnbindApp(unbindArgs UnbindAppArgs) error { if si.FindApp(unbindArgs.App.GetName()) == -1 { return ErrAppNotBound } args := bindPipelineArgs{ serviceInstance: si, app: unbindArgs.App, writer: unbindArgs.Event, shouldRestart: unbindArgs.Restart, event: unbindArgs.Event, requestID: unbindArgs.RequestID, forceRemove: unbindArgs.ForceRemove, } actions := []*action.Action{ &unbindUnits, &unbindAppDB, &unbindAppEndpoint, &removeBoundEnvs, } pipeline := action.NewPipeline(actions...) return pipeline.Execute(&args) }
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L902-L904
func CustomLog(level string, val ...interface{}) error { return glg.out(glg.TagStringToLevel(level), blankFormat(len(val)), val...) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L474-L483
func (p *GetRequestPostDataParams) Do(ctx context.Context) (postData string, err error) { // execute var res GetRequestPostDataReturns err = cdp.Execute(ctx, CommandGetRequestPostData, p, &res) if err != nil { return "", err } return res.PostData, nil }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/boundary.go#L156-L188
func locateBoundary(buf, boundaryPrefix []byte) (idx int, complete bool) { bpLen := len(boundaryPrefix) idx = bytes.Index(buf, boundaryPrefix) if idx == -1 { return } // Handle CR if present if idx > 0 && buf[idx-1] == '\r' { idx-- bpLen++ } // Fast forward to the end of the boundary prefix buf = buf[idx+bpLen:] if len(buf) == 0 { // Need more bytes to verify completeness return } if len(buf) > 1 { if buf[0] == '-' && buf[1] == '-' { return idx, true } } buf = bytes.TrimLeft(buf, " \t") if len(buf) > 0 { if buf[0] == '\r' || buf[0] == '\n' { return idx, true } } return }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/repoowners/repoowners.go#L605-L638
func (o *RepoOwners) entriesForFile(path string, people map[string]map[*regexp.Regexp]sets.String, leafOnly bool) sets.String { d := path if !o.enableMDYAML || !strings.HasSuffix(path, ".md") { // if path is a directory, this will remove the leaf directory, and returns "." for topmost dir d = filepath.Dir(d) d = canonicalize(path) } out := sets.NewString() for { relative, err := filepath.Rel(d, path) if err != nil { o.log.WithError(err).WithField("path", path).Errorf("Unable to find relative path between %q and path.", d) return nil } for re, s := range people[d] { if re == nil || re.MatchString(relative) { out.Insert(s.List()...) } } if leafOnly && out.Len() > 0 { break } if d == baseDirConvention { break } if o.options[d].NoParentOwners { break } d = filepath.Dir(d) d = canonicalize(d) } return out }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/pretty/pretty.go#L195-L206
func PrintDetailedFileInfo(fileInfo *pfs.FileInfo) error { template, err := template.New("FileInfo").Funcs(funcMap).Parse( `Path: {{.File.Path}} Type: {{fileType .FileType}} Size: {{prettySize .SizeBytes}} Children: {{range .Children}} {{.}} {{end}} `) if err != nil { return err } return template.Execute(os.Stdout, fileInfo) }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/context.go#L253-L267
func (c *Context) Respond(value interface{}) error { // encode response bytes, err := json.Marshal(value) if err != nil { return err } // write token _, err = c.ResponseWriter.Write(bytes) if err != nil { return err } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/overlay.go#L473-L475
func (p *SetShowHitTestBordersParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetShowHitTestBorders, p, nil) }
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/sessionInit.go#L13-L19
func SessionInit(expire time.Duration, pool *conn.RedisPool, cookie http.Cookie) { sessExpire = expire redisPool = pool httpCookie = cookie httpCookie.MaxAge = int(sessExpire.Seconds()) Use(session) }
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/ctors.go#L148-L161
func (api *TelegramBotAPI) NewOutgoingVoice(recipient Recipient, fileName string, reader io.Reader) *OutgoingVoice { return &OutgoingVoice{ outgoingMessageBase: outgoingMessageBase{ outgoingBase: outgoingBase{ api: api, Recipient: recipient, }, }, outgoingFileBase: outgoingFileBase{ fileName: fileName, r: reader, }, } }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/common/aws/common.go#L39-L60
func GetAWSCreds(r *common.Resource) (credentials.Value, error) { val := credentials.Value{} if r.Type != ResourceType { return val, fmt.Errorf("Wanted resource of type %q, got %q", ResourceType, r.Type) } accessKey, ok := r.UserData.Map.Load(UserDataAccessIDKey) if !ok { return val, errors.New("No Access Key ID in UserData") } secretKey, ok := r.UserData.Map.Load(UserDataSecretAccessKey) if !ok { return val, errors.New("No Secret Access Key in UserData") } val.AccessKeyID = accessKey.(string) val.SecretAccessKey = secretKey.(string) return val, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_post.go#L252-L392
func containerPostClusteringMigrate(d *Daemon, c container, oldName, newName, newNode string) Response { cert := d.endpoints.NetworkCert() var sourceAddress string var targetAddress string // Save the original value of the "volatile.apply_template" config key, // since we'll want to preserve it in the copied container. origVolatileApplyTemplate := c.LocalConfig()["volatile.apply_template"] err := d.cluster.Transaction(func(tx *db.ClusterTx) error { var err error sourceAddress, err = tx.NodeAddress() if err != nil { return errors.Wrap(err, "Failed to get local node address") } node, err := tx.NodeByName(newNode) if err != nil { return errors.Wrap(err, "Failed to get new node address") } targetAddress = node.Address return nil }) if err != nil { return SmartError(err) } run := func(*operation) error { // Connect to the source host, i.e. ourselves (the node the container is running on). source, err := cluster.Connect(sourceAddress, cert, false) if err != nil { return errors.Wrap(err, "Failed to connect to source server") } // Connect to the destination host, i.e. the node to migrate the container to. dest, err := cluster.Connect(targetAddress, cert, false) if err != nil { return errors.Wrap(err, "Failed to connect to destination server") } dest = dest.UseTarget(newNode) destName := newName isSameName := false // If no new name was provided, the user wants to keep the same // container name. In that case we need to generate a temporary // name. if destName == "" || destName == oldName { isSameName = true destName = fmt.Sprintf("move-%s", uuid.NewRandom().String()) } // First make a copy on the new node of the container to be moved. entry, _, err := source.GetContainer(oldName) if err != nil { return errors.Wrap(err, "Failed to get container info") } args := lxd.ContainerCopyArgs{ Name: destName, Mode: "pull", } copyOp, err := dest.CopyContainer(source, *entry, &args) if err != nil { return errors.Wrap(err, "Failed to issue copy container API request") } err = copyOp.Wait() if err != nil { return errors.Wrap(err, "Copy container operation failed") } // Delete the container on the original node. deleteOp, err := source.DeleteContainer(oldName) if err != nil { return errors.Wrap(err, "Failed to issue delete container API request") } err = deleteOp.Wait() if err != nil { return errors.Wrap(err, "Delete container operation failed") } // If the destination name is not set, we have generated a random name for // the new container, so we need to rename it. if isSameName { containerPost := api.ContainerPost{ Name: oldName, } op, err := dest.RenameContainer(destName, containerPost) if err != nil { return errors.Wrap(err, "Failed to issue rename container API request") } err = op.Wait() if err != nil { return errors.Wrap(err, "Rename container operation failed") } destName = oldName } // Restore the original value of "volatile.apply_template" id, err := d.cluster.ContainerID(destName) if err != nil { return errors.Wrap(err, "Failed to get ID of moved container") } err = d.cluster.ContainerConfigRemove(id, "volatile.apply_template") if err != nil { return errors.Wrap(err, "Failed to remove volatile.apply_template config key") } if origVolatileApplyTemplate != "" { config := map[string]string{ "volatile.apply_template": origVolatileApplyTemplate, } err := d.cluster.Transaction(func(tx *db.ClusterTx) error { return tx.ContainerConfigInsert(id, config) }) if err != nil { return errors.Wrap(err, "Failed to set volatile.apply_template config key") } } return nil } resources := map[string][]string{} resources["containers"] = []string{oldName} op, err := operationCreate(d.cluster, c.Project(), operationClassTask, db.OperationContainerMigrate, resources, nil, run, nil, nil) if err != nil { return InternalError(err) } return OperationResponse(op) }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/connection.go#L406-L413
func (c *Connection) handlePingRes(frame *Frame) bool { if err := c.outbound.forwardPeerFrame(frame); err != nil { c.log.WithFields(LogField{"response", frame.Header}).Warn("Unexpected ping response.") return true } // ping req is waiting for this frame, and will release it. return false }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/key.go#L244-L261
func DecodeKey(encoded string) (*Key, error) { // Re-add padding. if m := len(encoded) % 4; m != 0 { encoded += strings.Repeat("=", 4-m) } b, err := base64.URLEncoding.DecodeString(encoded) if err != nil { return nil, err } ref := new(pb.Reference) if err := proto.Unmarshal(b, ref); err != nil { return nil, err } return protoToKey(ref) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/flags/strings.go#L28-L31
func (ss *StringsValue) Set(s string) error { *ss = strings.Split(s, ",") return nil }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/client/service_manager.go#L64-L95
func (s *ServiceManager) Stop(pid int) (bool, error) { log.Println("[DEBUG] stopping service with pid", pid) cmd := s.processMap.Get(pid) // Remove service from registry go func() { s.commandCompleteChan <- cmd }() // Wait for error, kill if it takes too long var err error done := make(chan error, 1) go func() { done <- cmd.Wait() }() select { case <-time.After(3 * time.Second): if err = cmd.Process.Kill(); err != nil { log.Println("[ERROR] timeout reached, killing pid", pid) return false, err } case err = <-done: if err != nil { log.Println("[ERROR] error waiting for process to complete", err) return false, err } } return true, nil }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/service/sync.go#L120-L131
func (b *bindSyncer) Shutdown(ctx context.Context) error { if !b.started { return nil } b.shutdown <- struct{}{} select { case <-b.done: case <-ctx.Done(): } b.started = false return ctx.Err() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/connection.go#L140-L170
func ConnectSimpleStreams(url string, args *ConnectionArgs) (ImageServer, error) { logger.Debugf("Connecting to a remote simplestreams server") // Cleanup URL url = strings.TrimSuffix(url, "/") // Use empty args if not specified if args == nil { args = &ConnectionArgs{} } // Initialize the client struct server := ProtocolSimpleStreams{ httpHost: url, httpUserAgent: args.UserAgent, httpCertificate: args.TLSServerCert, } // Setup the HTTP client httpClient, err := tlsHTTPClient(args.HTTPClient, args.TLSClientCert, args.TLSClientKey, args.TLSCA, args.TLSServerCert, args.InsecureSkipVerify, args.Proxy) if err != nil { return nil, err } server.http = httpClient // Get simplestreams client ssClient := simplestreams.NewClient(url, *httpClient, args.UserAgent) server.ssClient = ssClient return &server, nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/integration/cluster.go#L427-L470
func (c *cluster) waitLeader(t testing.TB, membs []*member) int { possibleLead := make(map[uint64]bool) var lead uint64 for _, m := range membs { possibleLead[uint64(m.s.ID())] = true } cc := MustNewHTTPClient(t, getMembersURLs(membs), nil) kapi := client.NewKeysAPI(cc) // ensure leader is up via linearizable get for { ctx, cancel := context.WithTimeout(context.Background(), 10*tickDuration+time.Second) _, err := kapi.Get(ctx, "0", &client.GetOptions{Quorum: true}) cancel() if err == nil || strings.Contains(err.Error(), "Key not found") { break } } for lead == 0 || !possibleLead[lead] { lead = 0 for _, m := range membs { select { case <-m.s.StopNotify(): continue default: } if lead != 0 && lead != m.s.Lead() { lead = 0 time.Sleep(10 * tickDuration) break } lead = m.s.Lead() } } for i, m := range membs { if uint64(m.s.ID()) == lead { return i } } return -1 }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/buffer.go#L83-L96
func (r *ReadBuffer) ReadBytes(n int) []byte { if r.err != nil { return nil } if len(r.remaining) < n { r.err = ErrEOF return nil } b := r.remaining[0:n] r.remaining = r.remaining[n:] return b }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/detect.go#L31-L40
func detectAttachmentHeader(header textproto.MIMEHeader) bool { mediatype, params, _, _ := parseMediaType(header.Get(hnContentDisposition)) if strings.ToLower(mediatype) == cdAttachment || (strings.ToLower(mediatype) == cdInline && len(params) > 0) { return true } mediatype, _, _, _ = parseMediaType(header.Get(hnContentType)) return strings.ToLower(mediatype) == cdAttachment }
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/message.go#L71-L77
func NewMessage(id MessageID, body []byte, cmdChan chan<- Command) *Message { return &Message{ ID: id, Body: body, cmdChan: cmdChan, } }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/token-counter/token-counter.go#L78-L94
func CreateTokenHandler(tokenStream io.Reader, influxdb *InfluxDB) (*TokenHandler, error) { token, err := ioutil.ReadAll(tokenStream) if err != nil { return nil, err } client := GetGitHubClient(strings.TrimSpace(string(token))) login, err := GetUsername(client) // Get user name for token if err != nil { return nil, err } return &TokenHandler{ gClient: client, login: login, influxdb: influxdb, }, nil }
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/consumer.go#L52-L62
func (c *ConsumerConfig) validate() error { if len(c.Topic) == 0 { return errors.New("creating a new consumer requires a non-empty topic") } if len(c.Channel) == 0 { return errors.New("creating a new consumer requires a non-empty channel") } return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/label_sync/main.go#L390-L393
func kill(repo string, label Label) Update { logrus.WithField("repo", repo).WithField("label", label.Name).Info("kill") return Update{Why: "dead", Current: &label, repo: repo} }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L2956-L2960
func (v GetResourceTreeParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage31(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/jenkins/jenkins.go#L598-L601
func (c *Client) Build(pj *prowapi.ProwJob, buildID string) error { c.logger.WithFields(pjutil.ProwJobFields(pj)).Info("Build") return c.BuildFromSpec(&pj.Spec, buildID, pj.ObjectMeta.Name) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L186-L195
func (p *CaptureSnapshotParams) Do(ctx context.Context) (data string, err error) { // execute var res CaptureSnapshotReturns err = cdp.Execute(ctx, CommandCaptureSnapshot, p, &res) if err != nil { return "", err } return res.Data, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L867-L869
func (p *SetDataSizeLimitsForTestParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetDataSizeLimitsForTest, p, nil) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/connection.go#L128-L135
func ConnectPublicLXD(url string, args *ConnectionArgs) (ImageServer, error) { logger.Debugf("Connecting to a remote public LXD over HTTPs") // Cleanup URL url = strings.TrimSuffix(url, "/") return httpsLXD(url, args) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L8312-L8314
func (api *API) RepositoryLocator(href string) *RepositoryLocator { return &RepositoryLocator{Href(href), api} }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/contrib/recipes/double_barrier.go#L78-L138
func (b *DoubleBarrier) Leave() error { client := b.s.Client() resp, err := client.Get(b.ctx, b.key+"/waiters", clientv3.WithPrefix()) if err != nil { return err } if len(resp.Kvs) == 0 { return nil } lowest, highest := resp.Kvs[0], resp.Kvs[0] for _, k := range resp.Kvs { if k.ModRevision < lowest.ModRevision { lowest = k } if k.ModRevision > highest.ModRevision { highest = k } } isLowest := string(lowest.Key) == b.myKey.Key() if len(resp.Kvs) == 1 { // this is the only node in the barrier; finish up if _, err = client.Delete(b.ctx, b.key+"/ready"); err != nil { return err } return b.myKey.Delete() } // this ensures that if a process fails, the ephemeral lease will be // revoked, its barrier key is removed, and the barrier can resume // lowest process in node => wait on highest process if isLowest { _, err = WaitEvents( client, string(highest.Key), highest.ModRevision, []mvccpb.Event_EventType{mvccpb.DELETE}) if err != nil { return err } return b.Leave() } // delete self and wait on lowest process if err = b.myKey.Delete(); err != nil { return err } key := string(lowest.Key) _, err = WaitEvents( client, key, lowest.ModRevision, []mvccpb.Event_EventType{mvccpb.DELETE}) if err != nil { return err } return b.Leave() }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3024-L3045
func NewManageOfferSuccessResultOffer(effect ManageOfferEffect, value interface{}) (result ManageOfferSuccessResultOffer, err error) { result.Effect = effect switch ManageOfferEffect(effect) { case ManageOfferEffectManageOfferCreated: tv, ok := value.(OfferEntry) if !ok { err = fmt.Errorf("invalid value, must be OfferEntry") return } result.Offer = &tv case ManageOfferEffectManageOfferUpdated: tv, ok := value.(OfferEntry) if !ok { err = fmt.Errorf("invalid value, must be OfferEntry") return } result.Offer = &tv default: // void } return }
https://github.com/gravitational/roundtrip/blob/e1e0cd6b05a6bb1791b262e63160038828fd7b3a/client.go#L133-L151
func NewClient(addr, v string, params ...ClientParam) (*Client, error) { c := &Client{ addr: addr, v: v, client: &http.Client{}, } for _, p := range params { if err := p(c); err != nil { return nil, err } } if c.jar != nil { c.client.Jar = c.jar } if c.newTracer == nil { c.newTracer = NewNopTracer } return c, nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5092-L5100
func (u LedgerKey) MustTrustLine() LedgerKeyTrustLine { val, ok := u.GetTrustLine() if !ok { panic("arm TrustLine is not set") } return val }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L2367-L2371
func (v *NavigationEntry) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage24(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/backgroundservice/backgroundservice.go#L57-L59
func (p *StopObservingParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandStopObserving, p, nil) }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/client/clientset/versioned/typed/tsuru/v1/app.go#L65-L74
func (c *apps) List(opts meta_v1.ListOptions) (result *v1.AppList, err error) { result = &v1.AppList{} err = c.client.Get(). Namespace(c.ns). Resource("apps"). VersionedParams(&opts, scheme.ParameterCodec). Do(). Into(result) return }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/imgproc.go#L134-L142
func ArcLength(curve *Seq, slice Slice, is_closed bool) float64 { is_closed_int := 0 if is_closed { is_closed_int = 1 } return float64(C.cvArcLength(unsafe.Pointer(curve), (C.CvSlice)(slice), C.int(is_closed_int))) }
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/internal/function/func.go#L38-L66
func IsType(t reflect.Type, ft funcType) bool { if t == nil || t.Kind() != reflect.Func || t.IsVariadic() { return false } ni, no := t.NumIn(), t.NumOut() switch ft { case tbFunc: // func(T) bool if ni == 1 && no == 1 && t.Out(0) == boolType { return true } case ttbFunc: // func(T, T) bool if ni == 2 && no == 1 && t.In(0) == t.In(1) && t.Out(0) == boolType { return true } case trbFunc: // func(T, R) bool if ni == 2 && no == 1 && t.Out(0) == boolType { return true } case tibFunc: // func(T, I) bool if ni == 2 && no == 1 && t.In(0).AssignableTo(t.In(1)) && t.Out(0) == boolType { return true } case trFunc: // func(T) R if ni == 1 && no == 1 { return true } } return false }
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/cache/cache.go#L88-L92
func (c *Cache) Collect(in chan<- prometheus.Metric) { c.hitsTotal.Collect(in) c.refreshTotal.Collect(in) c.missesTotal.Collect(in) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv2/command/format.go#L26-L60
func printResponseKey(resp *client.Response, format string) { // Format the result. switch format { case "simple": if resp.Action != "delete" { fmt.Println(resp.Node.Value) } else { fmt.Println("PrevNode.Value:", resp.PrevNode.Value) } case "extended": // Extended prints in a rfc2822 style format fmt.Println("Key:", resp.Node.Key) fmt.Println("Created-Index:", resp.Node.CreatedIndex) fmt.Println("Modified-Index:", resp.Node.ModifiedIndex) if resp.PrevNode != nil { fmt.Println("PrevNode.Value:", resp.PrevNode.Value) } fmt.Println("TTL:", resp.Node.TTL) fmt.Println("Index:", resp.Index) if resp.Action != "delete" { fmt.Println("") fmt.Println(resp.Node.Value) } case "json": b, err := json.Marshal(resp) if err != nil { panic(err) } fmt.Println(string(b)) default: fmt.Fprintln(os.Stderr, "Unsupported output format:", format) } }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L238-L242
func (l *PeerList) Len() int { l.RLock() defer l.RUnlock() return l.peerHeap.Len() }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/thrift/thrift-gen/main.go#L232-L236
func NewStringSliceFlag(name string, usage string) *[]string { var ss stringSliceFlag flag.Var(&ss, name, usage) return (*[]string)(&ss) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L6111-L6115
func (v *EventAttributeModified) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom68(&r, v) return r.Error() }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/wal/repair.go#L30-L131
func Repair(lg *zap.Logger, dirpath string) bool { f, err := openLast(lg, dirpath) if err != nil { return false } defer f.Close() if lg != nil { lg.Info("repairing", zap.String("path", f.Name())) } else { plog.Noticef("repairing %v", f.Name()) } rec := &walpb.Record{} decoder := newDecoder(f) for { lastOffset := decoder.lastOffset() err := decoder.decode(rec) switch err { case nil: // update crc of the decoder when necessary switch rec.Type { case crcType: crc := decoder.crc.Sum32() // current crc of decoder must match the crc of the record. // do no need to match 0 crc, since the decoder is a new one at this case. if crc != 0 && rec.Validate(crc) != nil { return false } decoder.updateCRC(rec.Crc) } continue case io.EOF: if lg != nil { lg.Info("repaired", zap.String("path", f.Name()), zap.Error(io.EOF)) } return true case io.ErrUnexpectedEOF: bf, bferr := os.Create(f.Name() + ".broken") if bferr != nil { if lg != nil { lg.Warn("failed to create backup file", zap.String("path", f.Name()+".broken"), zap.Error(bferr)) } else { plog.Errorf("could not repair %v, failed to create backup file", f.Name()) } return false } defer bf.Close() if _, err = f.Seek(0, io.SeekStart); err != nil { if lg != nil { lg.Warn("failed to read file", zap.String("path", f.Name()), zap.Error(err)) } else { plog.Errorf("could not repair %v, failed to read file", f.Name()) } return false } if _, err = io.Copy(bf, f); err != nil { if lg != nil { lg.Warn("failed to copy", zap.String("from", f.Name()+".broken"), zap.String("to", f.Name()), zap.Error(err)) } else { plog.Errorf("could not repair %v, failed to copy file", f.Name()) } return false } if err = f.Truncate(lastOffset); err != nil { if lg != nil { lg.Warn("failed to truncate", zap.String("path", f.Name()), zap.Error(err)) } else { plog.Errorf("could not repair %v, failed to truncate file", f.Name()) } return false } if err = fileutil.Fsync(f.File); err != nil { if lg != nil { lg.Warn("failed to fsync", zap.String("path", f.Name()), zap.Error(err)) } else { plog.Errorf("could not repair %v, failed to sync file", f.Name()) } return false } if lg != nil { lg.Info("repaired", zap.String("path", f.Name()), zap.Error(io.ErrUnexpectedEOF)) } return true default: if lg != nil { lg.Warn("failed to repair", zap.String("path", f.Name()), zap.Error(err)) } else { plog.Errorf("could not repair error (%v)", err) } return false } } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L5577-L5581
func (v *EventDistributedNodesUpdated) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom62(&r, v) return r.Error() }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/crds/resources_config_crd.go#L158-L163
func (in *ResourcesConfigCollection) DeepCopyObject() runtime.Object { if c := in.deepCopy(); c != nil { return c } return nil }
https://github.com/Knetic/govaluate/blob/9aa49832a739dcd78a5542ff189fb82c3e423116/EvaluableExpression.go#L268-L276
func (this EvaluableExpression) Vars() []string { var varlist []string for _, val := range this.Tokens() { if val.Kind == VARIABLE { varlist = append(varlist, val.Value.(string)) } } return varlist }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/node.go#L206-L256
func (n *node) Remove(dir, recursive bool, callback func(path string)) *v2error.Error { if !n.IsDir() { // key-value pair _, name := path.Split(n.Path) // find its parent and remove the node from the map if n.Parent != nil && n.Parent.Children[name] == n { delete(n.Parent.Children, name) } if callback != nil { callback(n.Path) } if !n.IsPermanent() { n.store.ttlKeyHeap.remove(n) } return nil } if !dir { // cannot delete a directory without dir set to true return v2error.NewError(v2error.EcodeNotFile, n.Path, n.store.CurrentIndex) } if len(n.Children) != 0 && !recursive { // cannot delete a directory if it is not empty and the operation // is not recursive return v2error.NewError(v2error.EcodeDirNotEmpty, n.Path, n.store.CurrentIndex) } for _, child := range n.Children { // delete all children child.Remove(true, true, callback) } // delete self _, name := path.Split(n.Path) if n.Parent != nil && n.Parent.Children[name] == n { delete(n.Parent.Children, name) if callback != nil { callback(n.Path) } if !n.IsPermanent() { n.store.ttlKeyHeap.remove(n) } } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L3831-L3835
func (v Request) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork25(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/systeminfo/easyjson.go#L218-L222
func (v *GetProcessInfoReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoSysteminfo1(&r, v) return r.Error() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/sys.go#L158-L169
func GetExecPath() string { execPath := os.Getenv("LXD_EXEC_PATH") if execPath != "" { return execPath } execPath, err := os.Readlink("/proc/self/exe") if err != nil { execPath = "bad-exec-path" } return execPath }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/key.go#L91-L112
func (k *Key) valid() bool { if k == nil { return false } for ; k != nil; k = k.parent { if k.kind == "" || k.appID == "" { return false } if k.stringID != "" && k.intID != 0 { return false } if k.parent != nil { if k.parent.Incomplete() { return false } if k.parent.appID != k.appID || k.parent.namespace != k.namespace { return false } } } return true }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/adt/interval_tree.go#L455-L476
func (ivt *IntervalTree) Contains(ivl Interval) bool { var maxEnd, minBegin Comparable isContiguous := true ivt.Visit(ivl, func(n *IntervalValue) bool { if minBegin == nil { minBegin = n.Ivl.Begin maxEnd = n.Ivl.End return true } if maxEnd.Compare(n.Ivl.Begin) < 0 { isContiguous = false return false } if n.Ivl.End.Compare(maxEnd) > 0 { maxEnd = n.Ivl.End } return true }) return isContiguous && minBegin != nil && maxEnd.Compare(ivl.End) >= 0 && minBegin.Compare(ivl.Begin) <= 0 }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L7838-L7840
func (api *API) PublicationLocator(href string) *PublicationLocator { return &PublicationLocator{Href(href), api} }
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/ext/tags.go#L187-L189
func (tag uint16TagName) Set(span opentracing.Span, value uint16) { span.SetTag(string(tag), value) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxc/utils.go#L147-L169
func profileDeviceAdd(client lxd.ContainerServer, name string, devName string, dev map[string]string) error { // Get the profile entry profile, profileEtag, err := client.GetProfile(name) if err != nil { return err } // Check if the device already exists _, ok := profile.Devices[devName] if ok { return fmt.Errorf(i18n.G("Device already exists: %s"), devName) } // Add the device to the container profile.Devices[devName] = dev err = client.UpdateProfile(name, profile.Writable(), profileEtag) if err != nil { return err } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/log/easyjson.go#L593-L597
func (v *Entry) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoLog4(&r, v) return r.Error() }
https://github.com/malice-plugins/go-plugin-utils/blob/9ee76663c3b0a531b8c529f03f12a5a84ff9b61b/utils/utils.go#L190-L224
func Unzip(archive, target string) error { // fmt.Println("Unzip archive ", target) reader, err := zip.OpenReader(archive) if err != nil { return err } defer reader.Close() for _, file := range reader.File { filePath := filepath.Join(target, file.Name) if file.FileInfo().IsDir() { os.MkdirAll(filePath, file.Mode()) continue } fileReader, err := file.Open() if err != nil { return err } defer fileReader.Close() targetFile, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode()) if err != nil { return err } defer targetFile.Close() if _, err := io.Copy(targetFile, fileReader); err != nil { return err } } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/browser.go#L75-L77
func (p *ResetPermissionsParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandResetPermissions, p, nil) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L572-L576
func (v StartScreencastParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage5(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/default_context.go#L70-L74
func (d *DefaultContext) Set(key string, value interface{}) { d.moot.Lock() d.data[key] = value d.moot.Unlock() }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L165-L167
func ScanAST(pkg string, bzlFile *bzl.File) *File { return ScanASTBody(pkg, "", bzlFile) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv2/command/backup_command.go#L187-L257
func saveDB(destDB, srcDB string, idx uint64, v3 bool) { // open src db to safely copy db state if v3 { var src *bolt.DB ch := make(chan *bolt.DB, 1) go func() { db, err := bolt.Open(srcDB, 0444, &bolt.Options{ReadOnly: true}) if err != nil { log.Fatal(err) } ch <- db }() select { case src = <-ch: case <-time.After(time.Second): log.Println("waiting to acquire lock on", srcDB) src = <-ch } defer src.Close() tx, err := src.Begin(false) if err != nil { log.Fatal(err) } // copy srcDB to destDB dest, err := os.Create(destDB) if err != nil { log.Fatal(err) } if _, err := tx.WriteTo(dest); err != nil { log.Fatal(err) } dest.Close() if err := tx.Rollback(); err != nil { log.Fatal(err) } } db, err := bolt.Open(destDB, 0644, &bolt.Options{}) if err != nil { log.Fatal(err) } tx, err := db.Begin(true) if err != nil { log.Fatal(err) } // remove membership information; should be clobbered by --force-new-cluster for _, bucket := range []string{"members", "members_removed", "cluster"} { tx.DeleteBucket([]byte(bucket)) } // update consistent index to match hard state if !v3 { idxBytes := make([]byte, 8) binary.BigEndian.PutUint64(idxBytes, idx) b, err := tx.CreateBucketIfNotExists([]byte("meta")) if err != nil { log.Fatal(err) } b.Put([]byte("consistent_index"), idxBytes) } if err := tx.Commit(); err != nil { log.Fatal(err) } if err := db.Close(); err != nil { log.Fatal(err) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L604-L606
func (p *ReplayXHRParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandReplayXHR, p, nil) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/common/common.go#L153-L161
func (r *CommaSeparatedStrings) Set(value string) error { if len(*r) > 0 { return errors.New("resTypes flag already set") } for _, rtype := range strings.Split(value, ",") { *r = append(*r, rtype) } return nil }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cv.go#L157-L168
func AdaptiveThreshold(src, dst *IplImage, max_value float64, adaptive_method, threshold_type, block_size int, thresh_C float64) { C.cvAdaptiveThreshold( unsafe.Pointer(src), unsafe.Pointer(dst), C.double(max_value), C.int(adaptive_method), C.int(threshold_type), C.int(block_size), C.double(thresh_C), ) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L488-L507
func (p *GetResourceContentParams) Do(ctx context.Context) (content []byte, err error) { // execute var res GetResourceContentReturns err = cdp.Execute(ctx, CommandGetResourceContent, p, &res) if err != nil { return nil, err } // decode var dec []byte if res.Base64encoded { dec, err = base64.StdEncoding.DecodeString(res.Content) if err != nil { return nil, err } } else { dec = []byte(res.Content) } return dec, nil }
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/httputil/response.go#L53-L60
func SetDetectedContentType(w http.ResponseWriter, p []byte) string { ct := w.Header().Get("Content-Type") if ct == "" { ct = http.DetectContentType(p) w.Header().Set("Content-Type", ct) } return ct }
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/genmai.go#L575-L577
func (db *DB) SetLogFormat(format string) error { return db.logger.SetFormat(format) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L2061-L2065
func (v InternalPropertyDescriptor) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoRuntime18(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L6907-L6910
func (e ScpStatementType) ValidEnum(v int32) bool { _, ok := scpStatementTypeMap[v] return ok }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L512-L521
func (u Asset) GetAlphaNum12() (result AssetAlphaNum12, ok bool) { armName, _ := u.ArmForSwitch(int32(u.Type)) if armName == "AlphaNum12" { result = *u.AlphaNum12 ok = true } return }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/serviceenv/service_env.go#L85-L89
func InitWithKube(config *Configuration) *ServiceEnv { env := InitServiceEnv(config) env.kubeEg.Go(env.initKubeClient) return env // env is not ready yet }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L500-L503
func (p GetPropertiesParams) WithOwnProperties(ownProperties bool) *GetPropertiesParams { p.OwnProperties = ownProperties return &p }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/errors.go#L16-L22
func (e Error) Error() string { message := fmt.Sprintf("cannot set '%s'", e.Name) if e.Value != nil { message += fmt.Sprintf(" to '%v'", e.Value) } return message + fmt.Sprintf(": %s", e.Reason) }
https://github.com/shaleman/libOpenflow/blob/ef74a407cc85370620a5515d627580b20f18a582/util/stream.go#L145-L159
func (m *MessageStream) parse() { for { b := <-m.pool.Full log.Debugf("Rcvd: %v", b.Bytes()) msg, err := m.parser.Parse(b.Bytes()) // Log all message parsing errors. if err != nil { log.Print(err) } m.Inbound <- msg b.Reset() m.pool.Empty <- b } }
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/reflect.go#L105-L127
func isDefaultValue(rv reflect.Value) (erv reflect.Value, isDefaultValue bool) { rv, _, isNilPtr := derefPointers(rv) if isNilPtr { return rv, true } else { switch rv.Kind() { case reflect.Bool: return rv, rv.Bool() == false case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return rv, rv.Int() == 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return rv, rv.Uint() == 0 case reflect.String: return rv, rv.Len() == 0 case reflect.Chan, reflect.Map, reflect.Slice: return rv, rv.IsNil() || rv.Len() == 0 case reflect.Func, reflect.Interface: return rv, rv.IsNil() default: return rv, false } } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/gateway.go#L451-L497
func (g *Gateway) init() error { logger.Debugf("Initializing database gateway") raft, err := newRaft(g.db, g.cert, g.options.latency) if err != nil { return errors.Wrap(err, "Failed to create raft factory") } // If the resulting raft instance is not nil, it means that this node // should serve as database node, so create a dqlite driver to be // exposed it over gRPC. if raft != nil { listener, err := net.Listen("unix", "") if err != nil { return errors.Wrap(err, "Failed to allocate loopback port") } if raft.HandlerFunc() == nil { g.memoryDial = dqliteMemoryDial(listener) g.store.inMemory = dqlite.NewInmemServerStore() g.store.Set(context.Background(), []dqlite.ServerInfo{{Address: "0"}}) } else { go runDqliteProxy(listener, g.acceptCh) g.store.inMemory = nil } provider := &raftAddressProvider{db: g.db} server, err := dqlite.NewServer( raft.Raft(), raft.Registry(), listener, dqlite.WithServerAddressProvider(provider), dqlite.WithServerLogFunc(DqliteLog), ) if err != nil { return errors.Wrap(err, "Failed to create dqlite server") } g.server = server g.raft = raft } else { g.server = nil g.raft = nil g.store.inMemory = nil } g.store.onDisk = dqlite.NewServerStore(g.db.DB(), "main", "raft_nodes", "address") return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L7613-L7617
func (v *AddScriptToEvaluateOnNewDocumentParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage84(&r, v) return r.Error() }
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/spanish/step0.go#L9-L74
func step0(word *snowballword.SnowballWord) bool { // Search for the longest among the following suffixes suffix1, suffix1Runes := word.FirstSuffixIn(word.RVstart, len(word.RS), "selas", "selos", "sela", "selo", "las", "les", "los", "nos", "me", "se", "la", "le", "lo", ) // If the suffix empty or not in RV, we have nothing to do. if suffix1 == "" { return false } // We'll remove suffix1, if comes after one of the following suffix2, suffix2Runes := word.FirstSuffixIn(word.RVstart, len(word.RS)-len(suffix1), "iéndo", "iendo", "yendo", "ando", "ándo", "ár", "ér", "ír", "ar", "er", "ir", ) switch suffix2 { case "": // Nothing to do return false case "iéndo", "ándo", "ár", "ér", "ír": // In these cases, deletion is followed by removing // the acute accent (e.g., haciéndola -> haciendo). var suffix2repl string switch suffix2 { case "": return false case "iéndo": suffix2repl = "iendo" case "ándo": suffix2repl = "ando" case "ár": suffix2repl = "ar" case "ír": suffix2repl = "ir" } word.RemoveLastNRunes(len(suffix1Runes)) word.ReplaceSuffixRunes(suffix2Runes, []rune(suffix2repl), true) return true case "ando", "iendo", "ar", "er", "ir": word.RemoveLastNRunes(len(suffix1Runes)) return true case "yendo": // In the case of "yendo", the "yendo" must lie in RV, // and be preceded by a "u" somewhere in the word. for i := 0; i < len(word.RS)-(len(suffix1)+len(suffix2)); i++ { // Note, the unicode code point for "u" is 117. if word.RS[i] == 117 { word.RemoveLastNRunes(len(suffix1Runes)) return true } } } return false }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L886-L905
func (app *App) SetUnitStatus(unitName string, status provision.Status) error { units, err := app.Units() if err != nil { return err } for _, unit := range units { if strings.HasPrefix(unit.ID, unitName) { prov, err := app.getProvisioner() if err != nil { return err } unitProv, ok := prov.(provision.UnitStatusProvisioner) if !ok { return nil } return unitProv.SetUnitStatus(unit, status) } } return &provision.UnitNotFoundError{ID: unitName} }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L430-L455
func cephRBDVolumeUnmarkDeleted(clusterName string, poolName string, volumeName string, volumeType string, userName string, oldSuffix string, newSuffix string) error { oldName := fmt.Sprintf("%s/zombie_%s_%s", poolName, volumeType, volumeName) if oldSuffix != "" { oldName = fmt.Sprintf("%s_%s", oldName, oldSuffix) } newName := fmt.Sprintf("%s/%s_%s", poolName, volumeType, volumeName) if newSuffix != "" { newName = fmt.Sprintf("%s_%s", newName, newSuffix) } _, err := shared.RunCommand( "rbd", "--id", userName, "--cluster", clusterName, "mv", oldName, newName) if err != nil { return err } return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/gopherage/cmd/aggregate/aggregate.go#L34-L48
func MakeCommand() *cobra.Command { flags := &flags{} cmd := &cobra.Command{ Use: "aggregate [files...]", Short: "Aggregates multiple Go coverage files.", Long: `Given multiple Go coverage files from identical binaries recorded in "count" or "atomic" mode, produces a new Go coverage file in the same mode that counts how many of those coverage profiles hit a block at least once.`, Run: func(cmd *cobra.Command, args []string) { run(flags, cmd, args) }, } cmd.Flags().StringVarP(&flags.OutputFile, "output", "o", "-", "output file") return cmd }