_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/attrs.go#L90-L95
func (a *Attrs) RemoveAttr(key string) { a.attrsLock.Lock() defer a.attrsLock.Unlock() delete(a.attrs, getAttrHash(key)) }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/socket/socket_vm.go#L41-L43
func LookupIP(ctx context.Context, host string) (addrs []net.IP, err error) { return net.LookupIP(host) }
https://github.com/pandemicsyn/oort/blob/fca1d3baddc1d944387cc8bbe8b21f911ec9091b/oort/cmdctrl.go#L113-L125
func (o *Server) Stop() error { o.cmdCtrlLock.Lock() defer o.cmdCtrlLock.Unlock() if o.stopped { return fmt.Errorf("Service already stopped") } close(o.ch) o.backend.StopListenAndServe() o.backend.Wait() o.backend.Stop() o.stopped = true return nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/deploy/assets/assets.go#L691-L782
func EtcdDeployment(opts *AssetOpts, hostPath string) *apps.Deployment { cpu := resource.MustParse(opts.EtcdCPURequest) mem := resource.MustParse(opts.EtcdMemRequest) var volumes []v1.Volume if hostPath == "" { volumes = []v1.Volume{ { Name: "etcd-storage", VolumeSource: v1.VolumeSource{ PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{ ClaimName: etcdVolumeClaimName, }, }, }, } } else { volumes = []v1.Volume{ { Name: "etcd-storage", VolumeSource: v1.VolumeSource{ HostPath: &v1.HostPathVolumeSource{ Path: filepath.Join(hostPath, "etcd"), }, }, }, } } resourceRequirements := v1.ResourceRequirements{ Requests: v1.ResourceList{ v1.ResourceCPU: cpu, v1.ResourceMemory: mem, }, } if !opts.NoGuaranteed { resourceRequirements.Limits = v1.ResourceList{ v1.ResourceCPU: cpu, v1.ResourceMemory: mem, } } // Don't want to strip the registry out of etcdImage since it's from quay // not docker hub. image := etcdImage if opts.Registry != "" { image = AddRegistry(opts.Registry, etcdImage) } return &apps.Deployment{ TypeMeta: metav1.TypeMeta{ Kind: "Deployment", APIVersion: "apps/v1beta1", }, ObjectMeta: objectMeta(etcdName, labels(etcdName), nil, opts.Namespace), Spec: apps.DeploymentSpec{ Replicas: replicas(1), Selector: &metav1.LabelSelector{ MatchLabels: labels(etcdName), }, Template: v1.PodTemplateSpec{ ObjectMeta: objectMeta(etcdName, labels(etcdName), nil, opts.Namespace), Spec: v1.PodSpec{ Containers: []v1.Container{ { Name: etcdName, Image: image, //TODO figure out how to get a cluster of these to talk to each other Command: etcdCmd, Ports: []v1.ContainerPort{ { ContainerPort: 2379, Name: "client-port", }, { ContainerPort: 2380, Name: "peer-port", }, }, VolumeMounts: []v1.VolumeMount{ { Name: "etcd-storage", MountPath: "/var/data/etcd", }, }, ImagePullPolicy: "IfNotPresent", Resources: resourceRequirements, }, }, Volumes: volumes, ImagePullSecrets: imagePullSecrets(opts), }, }, }, } }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/pool/pool.go#L144-L155
func (p *Pool) Close() error { close(p.done) var retErr error for _, conn := range p.conns { if conn.cc != nil { if err := conn.cc.Close(); err != nil { retErr = err } } } return retErr }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/interaction.go#L32-L36
func (i *Interaction) UponReceiving(description string) *Interaction { i.Description = description return i }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/internal/stack/stack.go#L84-L99
func (s *Stack) Set(i int, v interface{}) error { if i < 0 { return errors.New("invalid index into stack") } if i >= s.BufferSize() { s.Resize(calcNewSize(i)) } for len(*s) < i + 1 { *s = append(*s, nil) } (*s)[i] = v return nil }
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/genmai.go#L544-L546
func (db *DB) Quote(s string) string { return db.dialect.Quote(s) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/contrib/recipes/client.go#L33-L43
func deleteRevKey(kv v3.KV, key string, rev int64) (bool, error) { cmp := v3.Compare(v3.ModRevision(key), "=", rev) req := v3.OpDelete(key) txnresp, err := kv.Txn(context.TODO()).If(cmp).Then(req).Commit() if err != nil { return false, err } else if !txnresp.Succeeded { return false, nil } return true, nil }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vm.go#L981-L1002
func (v *VM) RootSnapshot(index int) (*Snapshot, error) { var snapshotHandle C.VixHandle = C.VIX_INVALID_HANDLE var err C.VixError = C.VIX_OK err = C.VixVM_GetRootSnapshot(v.handle, C.int(index), &snapshotHandle) if C.VIX_OK != err { return nil, &Error{ Operation: "vm.RootSnapshot", Code: int(err & 0xFFFF), Text: C.GoString(C.Vix_GetErrorText(err, nil)), } } snapshot := &Snapshot{handle: snapshotHandle} runtime.SetFinalizer(snapshot, cleanupSnapshot) return snapshot, nil }
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/template.go#L137-L147
func (tmpl *Template) Execute(templateName string, obj interface{}, req *http.Request, w http.ResponseWriter) error { result, err := tmpl.Render(templateName, obj, req, w) if err == nil { if w.Header().Get("Content-Type") == "" { w.Header().Set("Content-Type", "text/html") } _, err = w.Write([]byte(result)) } return err }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/auth/server/api_server.go#L1317-L1334
func (a *apiServer) getScope(ctx context.Context, subject string, acl *authclient.ACL) (authclient.Scope, error) { // Get scope based on user's direct access scope := acl.Entries[subject] // Expand scope based on group access groups, err := a.getGroups(ctx, subject) if err != nil { return authclient.Scope_NONE, fmt.Errorf("could not retrieve caller's "+ "group memberships: %v", err) } for _, g := range groups { groupScope := acl.Entries[g] if scope < groupScope { scope = groupScope } } return scope, nil }
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/client.go#L21-L36
func NewClient(addrs []string, config *Config) (*Client, error) { if config == nil { config = NewConfig() } if err := config.Validate(); err != nil { return nil, err } client, err := sarama.NewClient(addrs, &config.Config) if err != nil { return nil, err } return &Client{Client: client, config: *config}, nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/integration/cluster.go#L587-L690
func mustNewMember(t testing.TB, mcfg memberConfig) *member { var err error m := &member{} peerScheme := schemeFromTLSInfo(mcfg.peerTLS) clientScheme := schemeFromTLSInfo(mcfg.clientTLS) pln := newLocalListener(t) m.PeerListeners = []net.Listener{pln} m.PeerURLs, err = types.NewURLs([]string{peerScheme + "://" + pln.Addr().String()}) if err != nil { t.Fatal(err) } m.PeerTLSInfo = mcfg.peerTLS cln := newLocalListener(t) m.ClientListeners = []net.Listener{cln} m.ClientURLs, err = types.NewURLs([]string{clientScheme + "://" + cln.Addr().String()}) if err != nil { t.Fatal(err) } m.ClientTLSInfo = mcfg.clientTLS m.Name = mcfg.name m.DataDir, err = ioutil.TempDir(os.TempDir(), "etcd") if err != nil { t.Fatal(err) } clusterStr := fmt.Sprintf("%s=%s://%s", mcfg.name, peerScheme, pln.Addr().String()) m.InitialPeerURLsMap, err = types.NewURLsMap(clusterStr) if err != nil { t.Fatal(err) } m.InitialClusterToken = clusterName m.NewCluster = true m.BootstrapTimeout = 10 * time.Millisecond if m.PeerTLSInfo != nil { m.ServerConfig.PeerTLSInfo = *m.PeerTLSInfo } m.ElectionTicks = electionTicks m.InitialElectionTickAdvance = true m.TickMs = uint(tickDuration / time.Millisecond) m.QuotaBackendBytes = mcfg.quotaBackendBytes m.MaxTxnOps = mcfg.maxTxnOps if m.MaxTxnOps == 0 { m.MaxTxnOps = embed.DefaultMaxTxnOps } m.MaxRequestBytes = mcfg.maxRequestBytes if m.MaxRequestBytes == 0 { m.MaxRequestBytes = embed.DefaultMaxRequestBytes } m.SnapshotCount = etcdserver.DefaultSnapshotCount if mcfg.snapshotCount != 0 { m.SnapshotCount = mcfg.snapshotCount } m.SnapshotCatchUpEntries = etcdserver.DefaultSnapshotCatchUpEntries if mcfg.snapshotCatchUpEntries != 0 { m.SnapshotCatchUpEntries = mcfg.snapshotCatchUpEntries } // for the purpose of integration testing, simple token is enough m.AuthToken = "simple" if mcfg.authToken != "" { m.AuthToken = mcfg.authToken } m.BcryptCost = uint(bcrypt.MinCost) // use min bcrypt cost to speedy up integration testing m.grpcServerOpts = []grpc.ServerOption{} if mcfg.grpcKeepAliveMinTime > time.Duration(0) { m.grpcServerOpts = append(m.grpcServerOpts, grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{ MinTime: mcfg.grpcKeepAliveMinTime, PermitWithoutStream: false, })) } if mcfg.grpcKeepAliveInterval > time.Duration(0) && mcfg.grpcKeepAliveTimeout > time.Duration(0) { m.grpcServerOpts = append(m.grpcServerOpts, grpc.KeepaliveParams(keepalive.ServerParameters{ Time: mcfg.grpcKeepAliveInterval, Timeout: mcfg.grpcKeepAliveTimeout, })) } m.clientMaxCallSendMsgSize = mcfg.clientMaxCallSendMsgSize m.clientMaxCallRecvMsgSize = mcfg.clientMaxCallRecvMsgSize m.useIP = mcfg.useIP m.LeaseCheckpointInterval = mcfg.leaseCheckpointInterval m.InitialCorruptCheck = true lcfg := logutil.DefaultZapLoggerConfig m.LoggerConfig = &lcfg m.LoggerConfig.OutputPaths = []string{"/dev/null"} m.LoggerConfig.ErrorOutputPaths = []string{"/dev/null"} if os.Getenv("CLUSTER_DEBUG") != "" { m.LoggerConfig.OutputPaths = []string{"stderr"} m.LoggerConfig.ErrorOutputPaths = []string{"stderr"} } m.Logger, err = m.LoggerConfig.Build() if err != nil { t.Fatal(err) } return m }
https://github.com/qor/action_bar/blob/136e5e2c5b8c50976dc39edddf523fcaab0a73b8/controller.go#L15-L24
func (controller) SwitchMode(context *admin.Context) { utils.SetCookie(http.Cookie{Name: "qor-action-bar", Value: context.Request.URL.Query().Get("checked")}, context.Context) referrer := context.Request.Referer() if referrer == "" { referrer = "/" } http.Redirect(context.Writer, context.Request, referrer, http.StatusFound) }
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/jump/jump.go#L41-L50
func Sum64(key string) uint64 { h := hasher.Get().(hash.Hash64) if _, err := io.WriteString(h, key); err != nil { panic(err) } r := h.Sum64() h.Reset() hasher.Put(h) return r }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/log_unstable.go#L56-L75
func (u *unstable) maybeTerm(i uint64) (uint64, bool) { if i < u.offset { if u.snapshot == nil { return 0, false } if u.snapshot.Metadata.Index == i { return u.snapshot.Metadata.Term, true } return 0, false } last, ok := u.maybeLastIndex() if !ok { return 0, false } if i > last { return 0, false } return u.entries[i-u.offset].Term, true }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/log_unstable.go#L151-L159
func (u *unstable) mustCheckOutOfBounds(lo, hi uint64) { if lo > hi { u.logger.Panicf("invalid unstable.slice %d > %d", lo, hi) } upper := u.offset + uint64(len(u.entries)) if lo < u.offset || hi > upper { u.logger.Panicf("unstable.slice[%d,%d) out of bound [%d,%d]", lo, hi, u.offset, upper) } }
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/codec.go#L43-L52
func (reg *Registry) Register(mimetype string, codec Codec) { defer reg.mutex.Unlock() reg.mutex.Lock() if reg.codecs == nil { reg.codecs = make(map[string]Codec) } reg.codecs[mimetype] = codec }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/cluster.go#L16-L25
func (e *Endpoints) ClusterAddress() string { e.mu.RLock() defer e.mu.RUnlock() listener := e.listeners[cluster] if listener == nil { return "" } return listener.Addr().String() }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/builder.go#L337-L339
func (p MailBuilder) Equals(o MailBuilder) bool { return reflect.DeepEqual(p, o) }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L462-L473
func CreateSparseMat(sizes []int, type_ int) *SparseMat { dims := C.int(len(sizes)) sizes_c := make([]C.int, len(sizes)) for i := 0; i < len(sizes); i++ { sizes_c[i] = C.int(sizes[i]) } mat := C.cvCreateSparseMat( dims, (*C.int)(&sizes_c[0]), C.int(type_), ) return (*SparseMat)(mat) }
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/release/pivnetrelease.go#L42-L53
func (r *PivnetRelease) readPivnetRelease(path string) error { walker := pkg.NewZipWalker(path) walker.OnMatch("releases/", func(file pkg.FileEntry) error { br, berr := readBoshRelease(file.Reader) if berr != nil { return berr } r.BoshRelease[br.ReleaseManifest.Name] = br return nil }) return walker.Walk() }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/auth.go#L275-L278
func (t *tokenAuthenticator) CanAuthenticate(host string) error { client := httpclient.New() return testAuth(t, client, host, false) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5193-L5196
func (e BucketEntryType) String() string { name, _ := bucketEntryTypeMap[int32(e)] return name }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/kube/client.go#L179-L193
func (c *Client) requestRetryStream(r *request) (io.ReadCloser, error) { if c.fake && r.deckPath == "" { return nil, nil } resp, err := c.retry(r) if err != nil { return nil, err } if resp.StatusCode == 409 { return nil, NewConflictError(fmt.Errorf("body cannot be streamed")) } else if resp.StatusCode < 200 || resp.StatusCode > 299 { return nil, fmt.Errorf("response has status \"%s\"", resp.Status) } return resp.Body, nil }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/message.go#L60-L64
func (p *Message) Given(state string) *Message { p.States = []State{State{Name: state}} return p }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/relay_timer_pool.go#L126-L133
func (rt *relayTimer) Stop() bool { rt.verifyNotReleased() stopped := rt.timer.Stop() if stopped { rt.markTimerInactive() } return stopped }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/common/common.go#L199-L206
func (ud *UserData) Set(id string, in interface{}) error { b, err := yaml.Marshal(in) if err != nil { return err } ud.Store(id, string(b)) return nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4528-L4535
func NewTransactionResultExt(v int32, value interface{}) (result TransactionResultExt, err error) { result.V = v switch int32(v) { case 0: // void } return }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/matcher.go#L261-L273
func objectToString(obj interface{}) string { switch content := obj.(type) { case string: return content default: jsonString, err := json.Marshal(obj) if err != nil { log.Println("[DEBUG] objectToString: error unmarshaling object into string:", err.Error()) return "" } return string(jsonString) } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/mvcc/watcher_group.go#L270-L292
func (wg *watcherGroup) watcherSetByKey(key string) watcherSet { wkeys := wg.keyWatchers[key] wranges := wg.ranges.Stab(adt.NewStringAffinePoint(key)) // zero-copy cases switch { case len(wranges) == 0: // no need to merge ranges or copy; reuse single-key set return wkeys case len(wranges) == 0 && len(wkeys) == 0: return nil case len(wranges) == 1 && len(wkeys) == 0: return wranges[0].Val.(watcherSet) } // copy case ret := make(watcherSet) ret.union(wg.keyWatchers[key]) for _, item := range wranges { ret.union(item.Val.(watcherSet)) } return ret }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/signature.go#L68-L79
func newUntrustedSignature(dockerManifestDigest digest.Digest, dockerReference string) untrustedSignature { // Use intermediate variables for these values so that we can take their addresses. // Golang guarantees that they will have a new address on every execution. creatorID := "atomic " + version.Version timestamp := time.Now().Unix() return untrustedSignature{ UntrustedDockerManifestDigest: dockerManifestDigest, UntrustedDockerReference: dockerReference, UntrustedCreatorID: &creatorID, UntrustedTimestamp: &timestamp, } }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift-copies.go#L898-L928
func tlsCacheGet(config *restConfig) (http.RoundTripper, error) { // REMOVED: any actual caching // Get the TLS options for this client config tlsConfig, err := tlsConfigFor(config) if err != nil { return nil, err } // The options didn't require a custom TLS config if tlsConfig == nil { return http.DefaultTransport, nil } // REMOVED: Call to k8s.io/apimachinery/pkg/util/net.SetTransportDefaults; instead of the generic machinery and conditionals, hard-coded the result here. t := &http.Transport{ // http.ProxyFromEnvironment doesn't respect CIDRs and that makes it impossible to exclude things like pod and service IPs from proxy settings // ProxierWithNoProxyCIDR allows CIDR rules in NO_PROXY Proxy: newProxierWithNoProxyCIDR(http.ProxyFromEnvironment), TLSHandshakeTimeout: 10 * time.Second, TLSClientConfig: tlsConfig, Dial: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, }).Dial, } // Allow clients to disable http2 if needed. if s := os.Getenv("DISABLE_HTTP2"); len(s) == 0 { _ = http2.ConfigureTransport(t) } return t, nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4476-L4484
func (u TransactionResultResult) MustResults() []OperationResult { val, ok := u.GetResults() if !ok { panic("arm Results is not set") } return val }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/networks.go#L149-L224
func (c *ClusterTx) NetworkCreatePending(node, name string, conf map[string]string) error { // First check if a network with the given name exists, and, if // so, that it's in the pending state. network := struct { id int64 state int }{} var errConsistency error dest := func(i int) []interface{} { // Sanity check that there is at most one pool with the given name. if i != 0 { errConsistency = fmt.Errorf("more than one network exists with the given name") } return []interface{}{&network.id, &network.state} } stmt, err := c.tx.Prepare("SELECT id, state FROM networks WHERE name=?") if err != nil { return err } defer stmt.Close() err = query.SelectObjects(stmt, dest, name) if err != nil { return err } if errConsistency != nil { return errConsistency } var networkID = network.id if networkID == 0 { // No existing network with the given name was found, let's create // one. columns := []string{"name"} values := []interface{}{name} networkID, err = query.UpsertObject(c.tx, "networks", columns, values) if err != nil { return err } } else { // Check that the existing network is in the pending state. if network.state != networkPending { return fmt.Errorf("network is not in pending state") } } // Get the ID of the node with the given name. nodeInfo, err := c.NodeByName(node) if err != nil { return err } // Check that no network entry for this node and network exists yet. count, err := query.Count( c.tx, "networks_nodes", "network_id=? AND node_id=?", networkID, nodeInfo.ID) if err != nil { return err } if count != 0 { return ErrAlreadyDefined } // Insert the node-specific configuration. columns := []string{"network_id", "node_id"} values := []interface{}{networkID, nodeInfo.ID} _, err = query.UpsertObject(c.tx, "networks_nodes", columns, values) if err != nil { return err } err = c.NetworkConfigAdd(networkID, nodeInfo.ID, conf) if err != nil { return err } return nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/watch_command.go#L194-L360
func parseWatchArgs(osArgs, commandArgs []string, envKey, envRange string, interactive bool) (watchArgs []string, execArgs []string, err error) { rawArgs := make([]string, len(osArgs)) copy(rawArgs, osArgs) watchArgs = make([]string, len(commandArgs)) copy(watchArgs, commandArgs) // remove preceding commands (e.g. ./bin/etcdctl watch) // handle "./bin/etcdctl watch foo -- echo watch event" for idx := range rawArgs { if rawArgs[idx] == "watch" { rawArgs = rawArgs[idx+1:] break } } // remove preceding commands (e.g. "watch foo bar" in interactive mode) // handle "./bin/etcdctl watch foo -- echo watch event" if interactive { if watchArgs[0] != "watch" { // "watch" not found watchPrefix, watchRev, watchPrevKey = false, 0, false return nil, nil, errBadArgsInteractiveWatch } watchArgs = watchArgs[1:] } execIdx, execExist := 0, false if !interactive { for execIdx = range rawArgs { if rawArgs[execIdx] == "--" { execExist = true break } } if execExist && execIdx == len(rawArgs)-1 { // "watch foo bar --" should error return nil, nil, errBadArgsNumSeparator } // "watch" with no argument should error if !execExist && len(rawArgs) < 1 && envKey == "" { return nil, nil, errBadArgsNum } if execExist && envKey != "" { // "ETCDCTL_WATCH_KEY=foo watch foo -- echo 1" should error // (watchArgs==["foo","echo","1"]) widx, ridx := len(watchArgs)-1, len(rawArgs)-1 for ; widx >= 0; widx-- { if watchArgs[widx] == rawArgs[ridx] { ridx-- continue } // watchArgs has extra: // ETCDCTL_WATCH_KEY=foo watch foo -- echo 1 // watchArgs: foo echo 1 if ridx == execIdx { return nil, nil, errBadArgsNumConflictEnv } } } // check conflicting arguments // e.g. "watch --rev 1 -- echo Hello World" has no conflict if !execExist && len(watchArgs) > 0 && envKey != "" { // "ETCDCTL_WATCH_KEY=foo watch foo" should error // (watchArgs==["foo"]) return nil, nil, errBadArgsNumConflictEnv } } else { for execIdx = range watchArgs { if watchArgs[execIdx] == "--" { execExist = true break } } if execExist && execIdx == len(watchArgs)-1 { // "watch foo bar --" should error watchPrefix, watchRev, watchPrevKey = false, 0, false return nil, nil, errBadArgsNumSeparator } flagset := NewWatchCommand().Flags() if perr := flagset.Parse(watchArgs); perr != nil { watchPrefix, watchRev, watchPrevKey = false, 0, false return nil, nil, perr } pArgs := flagset.Args() // "watch" with no argument should error if !execExist && envKey == "" && len(pArgs) < 1 { watchPrefix, watchRev, watchPrevKey = false, 0, false return nil, nil, errBadArgsNum } // check conflicting arguments // e.g. "watch --rev 1 -- echo Hello World" has no conflict if !execExist && len(pArgs) > 0 && envKey != "" { // "ETCDCTL_WATCH_KEY=foo watch foo" should error // (watchArgs==["foo"]) watchPrefix, watchRev, watchPrevKey = false, 0, false return nil, nil, errBadArgsNumConflictEnv } } argsWithSep := rawArgs if interactive { // interactive mode directly passes "--" to the command args argsWithSep = watchArgs } idx, foundSep := 0, false for idx = range argsWithSep { if argsWithSep[idx] == "--" { foundSep = true break } } if foundSep { execArgs = argsWithSep[idx+1:] } if interactive { flagset := NewWatchCommand().Flags() if perr := flagset.Parse(argsWithSep); perr != nil { return nil, nil, perr } watchArgs = flagset.Args() watchPrefix, err = flagset.GetBool("prefix") if err != nil { return nil, nil, err } watchRev, err = flagset.GetInt64("rev") if err != nil { return nil, nil, err } watchPrevKey, err = flagset.GetBool("prev-kv") if err != nil { return nil, nil, err } } // "ETCDCTL_WATCH_KEY=foo watch -- echo hello" // should translate "watch foo -- echo hello" // (watchArgs=["echo","hello"] should be ["foo","echo","hello"]) if envKey != "" { ranges := []string{envKey} if envRange != "" { ranges = append(ranges, envRange) } watchArgs = append(ranges, watchArgs...) } if !foundSep { return watchArgs, nil, nil } // "watch foo bar --rev 1 -- echo hello" or "watch foo --rev 1 bar -- echo hello", // then "watchArgs" is "foo bar echo hello" // so need ignore args after "argsWithSep[idx]", which is "--" endIdx := 0 for endIdx = len(watchArgs) - 1; endIdx >= 0; endIdx-- { if watchArgs[endIdx] == argsWithSep[idx+1] { break } } watchArgs = watchArgs[:endIdx] return watchArgs, execArgs, nil }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/inbound.go#L347-L356
func (response *InboundCallResponse) SetApplicationError() error { if response.state > reqResWriterPreArg2 { return response.failed(errReqResWriterStateMismatch{ state: response.state, expectedState: reqResWriterPreArg2, }) } response.applicationError = true return nil }
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L847-L849
func (g *Glg) Warn(val ...interface{}) error { return g.out(WARN, blankFormat(len(val)), val...) }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vm.go#L1959-L2001
func (v *VM) updateVMX(updateFunc func(model *vmx.VirtualMachine) error) error { isVMRunning, err := v.IsRunning() if err != nil { return err } if isVMRunning { return &Error{ Operation: "vm.updateVMX", Code: 100000, Text: "The VM has to be powered off in order to change its vmx settings", } } err = v.vmxfile.Read() if err != nil { return &Error{ Operation: "vm.updateVMX", Code: 300001, Text: fmt.Sprintf("Error reading vmx file: %s", err), } } err = updateFunc(v.vmxfile.model) if err != nil { return &Error{ Operation: "vm.updateVMX", Code: 300002, Text: fmt.Sprintf("Error changing vmx value: %s", err), } } err = v.vmxfile.Write() if err != nil { return &Error{ Operation: "vm.updateVMX", Code: 300003, Text: fmt.Sprintf("Error writing vmx file: %s", err), } } return nil }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/geometry/geometry.go#L166-L189
func CubicCurve(gc draw2d.GraphicContext, x, y, width, height float64) { sx, sy := width/162, height/205 x0, y0 := x, y+sy*100.0 x1, y1 := x+sx*75, y+sy*205 x2, y2 := x+sx*125, y x3, y3 := x+sx*205, y+sy*100 gc.SetStrokeColor(image.Black) gc.SetFillColor(color.NRGBA{0xAA, 0xAA, 0xAA, 0xFF}) gc.SetLineWidth(width / 10) gc.MoveTo(x0, y0) gc.CubicCurveTo(x1, y1, x2, y2, x3, y3) gc.Stroke() gc.SetStrokeColor(color.NRGBA{0xFF, 0x33, 0x33, 0x88}) gc.SetLineWidth(width / 20) // draw segment of curve gc.MoveTo(x0, y0) gc.LineTo(x1, y1) gc.LineTo(x2, y2) gc.LineTo(x3, y3) gc.Stroke() }
https://github.com/geoffgarside/ber/blob/27a1aff36ce64dbe5d93c08cc5f161983134ddc5/ber.go#L413-L461
func parseSequenceOf(bytes []byte, sliceType reflect.Type, elemType reflect.Type) (ret reflect.Value, err error) { expectedTag, compoundType, ok := getUniversalType(elemType) if !ok { err = asn1.StructuralError{Msg: "unknown Go type for slice"} return } // First we iterate over the input and count the number of elements, // checking that the types are correct in each case. numElements := 0 for offset := 0; offset < len(bytes); { var t tagAndLength t, offset, err = parseTagAndLength(bytes, offset) if err != nil { return } switch t.tag { case tagIA5String, tagGeneralString, tagT61String, tagUTF8String: // We pretend that various other string types are // PRINTABLE STRINGs so that a sequence of them can be // parsed into a []string. t.tag = tagPrintableString case tagGeneralizedTime, tagUTCTime: // Likewise, both time types are treated the same. t.tag = tagUTCTime } if t.class != classUniversal || t.isCompound != compoundType || t.tag != expectedTag { err = asn1.StructuralError{Msg: "sequence tag mismatch"} return } if invalidLength(offset, t.length, len(bytes)) { err = asn1.SyntaxError{Msg: "truncated sequence"} return } offset += t.length numElements++ } ret = reflect.MakeSlice(sliceType, numElements, numElements) params := fieldParameters{} offset := 0 for i := 0; i < numElements; i++ { offset, err = parseField(ret.Index(i), bytes, offset, params) if err != nil { return } } return }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pps.go#L260-L283
func (c APIClient) FlushJob(commits []*pfs.Commit, toPipelines []string, f func(*pps.JobInfo) error) error { req := &pps.FlushJobRequest{ Commits: commits, } for _, pipeline := range toPipelines { req.ToPipelines = append(req.ToPipelines, NewPipeline(pipeline)) } client, err := c.PpsAPIClient.FlushJob(c.Ctx(), req) if err != nil { return grpcutil.ScrubGRPC(err) } for { jobInfo, err := client.Recv() if err != nil { if err == io.EOF { return nil } return grpcutil.ScrubGRPC(err) } if err := f(jobInfo); err != nil { return err } } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L1307-L1309
func (p *AddCompilationCacheParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandAddCompilationCache, p, nil) }
https://github.com/libp2p/go-libp2p-crypto/blob/9d2fed53443f745e6dc4d02bdcc94d9742a0ca84/key.go#L305-L318
func UnmarshalPrivateKey(data []byte) (PrivKey, error) { pmes := new(pb.PrivateKey) err := proto.Unmarshal(data, pmes) if err != nil { return nil, err } um, ok := PrivKeyUnmarshallers[pmes.GetType()] if !ok { return nil, ErrBadKeyType } return um(pmes.GetData()) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L637-L643
func (c APIClient) ReadObject(hash string) ([]byte, error) { var buffer bytes.Buffer if err := c.GetObject(hash, &buffer); err != nil { return nil, grpcutil.ScrubGRPC(err) } return buffer.Bytes(), nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L2647-L2651
func (v SecurityDetails) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork19(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/inmem_snapshot.go#L89-L93
func (s *InmemSnapshotSink) Write(p []byte) (n int, err error) { written, err := io.Copy(s.contents, bytes.NewReader(p)) s.meta.Size += written return int(written), err }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L323-L329
func (h *dbHashTree) FSSize() int64 { rootNode, err := h.Get("/") if err != nil { return 0 } return rootNode.SubtreeSize }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_pools.go#L39-L53
func (c *ClusterTx) StoragePoolID(name string) (int64, error) { stmt := "SELECT id FROM storage_pools WHERE name=?" ids, err := query.SelectIntegers(c.tx, stmt, name) if err != nil { return -1, err } switch len(ids) { case 0: return -1, ErrNoSuchObject case 1: return int64(ids[0]), nil default: return -1, fmt.Errorf("more than one pool has the given name") } }
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/read.go#L190-L192
func (r *Reader) Trailer() Value { return Value{r, r.trailerptr, r.trailer} }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L439-L454
func (c *ClusterTx) NodeOfflineThreshold() (time.Duration, error) { threshold := time.Duration(DefaultOfflineThreshold) * time.Second values, err := query.SelectStrings( c.tx, "SELECT value FROM config WHERE key='cluster.offline_threshold'") if err != nil { return -1, err } if len(values) > 0 { seconds, err := strconv.Atoi(values[0]) if err != nil { return -1, err } threshold = time.Duration(seconds) * time.Second } return threshold, nil }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/ostree/ostree_src.go#L95-L117
func (s *ostreeImageSource) GetManifest(ctx context.Context, instanceDigest *digest.Digest) ([]byte, string, error) { if instanceDigest != nil { return nil, "", errors.Errorf(`Manifest lists are not supported by "ostree:"`) } if s.repo == nil { repo, err := openRepo(s.ref.repo) if err != nil { return nil, "", err } s.repo = repo } b := fmt.Sprintf("ociimage/%s", s.ref.branchName) found, out, err := readMetadata(s.repo, b, "docker.manifest") if err != nil { return nil, "", err } if !found { return nil, "", errors.New("manifest not found") } m := []byte(out) return m, manifest.GuessMIMEType(m), nil }
https://github.com/malice-plugins/go-plugin-utils/blob/9ee76663c3b0a531b8c529f03f12a5a84ff9b61b/clitable/table.go#L230-L235
func (t *Table) stringTableDash() string { if t.Markdown { return t.stringMarkdownDash() } return t.stringDash() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/types.go#L377-L379
func (t *DispatchMouseEventPointerType) UnmarshalJSON(buf []byte) error { return easyjson.Unmarshal(buf, t) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L740-L743
func (p PrintToPDFParams) WithMarginRight(marginRight float64) *PrintToPDFParams { p.MarginRight = marginRight return &p }
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/models/object.go#L88-L94
func (o *Object) GetMetadataAll(attr bool) map[string]string { metadataAll := make(map[string]string) for k, v := range o.Metadata { metadataAll[k] = v.value } return metadataAll }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/map.go#L135-L142
func (m *Map) GetInt64(name string) int64 { m.schema.assertKeyType(name, Int64) n, err := strconv.ParseInt(m.GetRaw(name), 10, 64) if err != nil { panic(fmt.Sprintf("cannot convert to int64: %v", err)) } return n }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/ranch/storage.go#L84-L86
func (s *Storage) UpdateResource(resource common.Resource) error { return s.resources.Update(resource) }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selection_actions.go#L62-L72
func (s *Selection) Fill(text string) error { return s.forEachElement(func(selectedElement element.Element) error { if err := selectedElement.Clear(); err != nil { return fmt.Errorf("failed to clear %s: %s", s, err) } if err := selectedElement.Value(text); err != nil { return fmt.Errorf("failed to enter text into %s: %s", s, err) } return nil }) }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/deploy.go#L34-L121
func deploy(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { opts, err := prepareToBuild(r) if err != nil { return err } if opts.File != nil { defer opts.File.Close() } commit := InputValue(r, "commit") w.Header().Set("Content-Type", "text") appName := r.URL.Query().Get(":appname") origin := InputValue(r, "origin") if opts.Image != "" { origin = "image" } if origin != "" { if !app.ValidateOrigin(origin) { return &tsuruErrors.HTTP{ Code: http.StatusBadRequest, Message: "Invalid deployment origin", } } } var userName string if t.IsAppToken() { if t.GetAppName() != appName && t.GetAppName() != app.InternalAppName { return &tsuruErrors.HTTP{Code: http.StatusUnauthorized, Message: "invalid app token"} } userName = InputValue(r, "user") } else { commit = "" userName = t.GetUserName() } instance, err := app.GetByName(appName) if err != nil { return &tsuruErrors.HTTP{Code: http.StatusNotFound, Message: err.Error()} } message := InputValue(r, "message") if commit != "" && message == "" { var messages []string messages, err = repository.Manager().CommitMessages(instance.Name, commit, 1) if err != nil { return err } if len(messages) > 0 { message = messages[0] } } if origin == "" && commit != "" { origin = "git" } opts.App = instance opts.Commit = commit opts.User = userName opts.Origin = origin opts.Message = message opts.GetKind() if t.GetAppName() != app.InternalAppName { canDeploy := permission.Check(t, permSchemeForDeploy(opts), contextsForApp(instance)...) if !canDeploy { return &tsuruErrors.HTTP{Code: http.StatusForbidden, Message: "User does not have permission to do this action in this app"} } } var imageID string evt, err := event.New(&event.Opts{ Target: appTarget(appName), Kind: permission.PermAppDeploy, RawOwner: event.Owner{Type: event.OwnerTypeUser, Name: userName}, CustomData: opts, Allowed: event.Allowed(permission.PermAppReadEvents, contextsForApp(instance)...), AllowedCancel: event.Allowed(permission.PermAppUpdateEvents, contextsForApp(instance)...), Cancelable: true, }) if err != nil { return err } defer func() { evt.DoneCustomData(err, map[string]string{"image": imageID}) }() w.Header().Set(eventIDHeader, evt.UniqueID.Hex()) opts.Event = evt writer := tsuruIo.NewKeepAliveWriter(w, 30*time.Second, "please wait...") defer writer.Stop() opts.OutputStream = writer imageID, err = app.Deploy(opts) if err == nil { fmt.Fprintln(w, "\nOK") } return err }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L265-L282
func (l *PeerList) onPeerChange(p *Peer) { l.RLock() ps, psScore, ok := l.getPeerScore(p.hostPort) sc := l.scoreCalculator l.RUnlock() if !ok { return } newScore := sc.GetScore(ps.Peer) if newScore == psScore { return } l.Lock() l.updatePeer(ps, newScore) l.Unlock() }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/models/task_all_of1.go#L138-L143
func (m *TaskAllOf1) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/api_client.go#L67-L165
func (c Client) RequestContext(ctx context.Context, method, path string, query url.Values, body io.Reader, accept []string) (resp *http.Response, err error) { if !strings.HasPrefix(c.Endpoint, "http://") && !strings.HasPrefix(c.Endpoint, "https://") { c.Endpoint = "http://" + c.Endpoint } u, err := url.Parse(c.Endpoint) if err != nil { return } u.Path += path u.RawQuery = query.Encode() req, err := http.NewRequest(method, u.String(), body) if err != nil { return } if ctx != nil { req = req.WithContext(ctx) } for _, a := range accept { req.Header.Add("Accept", a) } if c.UserAgent != "" { req.Header.Set("User-Agent", c.UserAgent) } for key, value := range c.Headers { req.Header.Set(key, value) } if c.Key != "" { keyHeader := c.KeyHeader if keyHeader == "" { keyHeader = DefaultKeyHeader } req.Header.Set(keyHeader, c.Key) } if c.BasicAuth != nil { req.SetBasicAuth(c.BasicAuth.Username, c.BasicAuth.Password) } httpClient := c.HTTPClient if httpClient == nil { httpClient = http.DefaultClient } resp, err = httpClient.Do(req) if err != nil { return } if 200 > resp.StatusCode || resp.StatusCode >= 300 { defer func() { io.Copy(ioutil.Discard, resp.Body) resp.Body.Close() }() message := struct { Message string `json:"message"` Code *int `json:"code"` }{} var body []byte body, err = ioutil.ReadAll(resp.Body) if err != nil { return } if resp.ContentLength != 0 && strings.Contains(resp.Header.Get("Content-Type"), "application/json") { if err = json.Unmarshal(body, &message); err != nil { switch e := err.(type) { case *json.SyntaxError: line, col := getLineColFromOffset(body, e.Offset) message.Message = fmt.Sprintf("json %s, line: %d, column: %d", e, line, col) case *json.UnmarshalTypeError: // If the type of message is not as expected, // continue with http based error reporting. default: return } } } if message.Code != nil && c.ErrorRegistry != nil { if err = c.ErrorRegistry.Error(*message.Code); err != nil { return } if handler := c.ErrorRegistry.Handler(*message.Code); handler != nil { err = handler(body) return } } var msg string if message.Message != "" { msg = message.Message } else { msg = "http status: " + strings.ToLower(http.StatusText(resp.StatusCode)) } err = &Error{ Message: msg, Code: resp.StatusCode, } } return }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/agent/handler.go#L89-L97
func (srv *Server) createEtcdLogFile() error { var err error srv.etcdLogFile, err = os.Create(srv.Member.Etcd.LogOutputs[0]) if err != nil { return err } srv.lg.Info("created etcd log file", zap.String("path", srv.Member.Etcd.LogOutputs[0])) return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/easyjson.go#L1432-L1436
func (v ScreenOrientation) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoEmulation15(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L874-L883
func deleteDir(tx *bolt.Tx, path string) error { c := fs(tx).Cursor() prefix := append(b(path), nullByte[0]) for k, _ := c.Seek(prefix); bytes.HasPrefix(k, prefix); k, _ = c.Next() { if err := c.Delete(); err != nil { return err } } return fs(tx).Delete(b(path)) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/approve/approvers/owners.go#L295-L305
func (ap *Approvers) AddLGTMer(login, reference string, noIssue bool) { if ap.shouldNotOverrideApproval(login, noIssue) { return } ap.approvers[strings.ToLower(login)] = Approval{ Login: login, How: "LGTM", Reference: reference, NoIssue: noIssue, } }
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/ast.go#L2236-L2251
func ExprFromValue(value sqltypes.Value) (Expr, error) { // The type checks here follow the rules defined in sqltypes/types.go. switch { case value.Type() == sqltypes.Null: return &NullVal{}, nil case value.IsIntegral(): return NewIntVal(value.ToBytes()), nil case value.IsFloat() || value.Type() == sqltypes.Decimal: return NewFloatVal(value.ToBytes()), nil case value.IsQuoted(): return NewStrVal(value.ToBytes()), nil default: // We cannot support sqltypes.Expression, or any other invalid type. return nil, fmt.Errorf("cannot convert value %v to AST", value) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L968-L973
func QuerySelectorAll(nodeID cdp.NodeID, selector string) *QuerySelectorAllParams { return &QuerySelectorAllParams{ NodeID: nodeID, Selector: selector, } }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/table/builder.go#L101-L109
func (b Builder) keyDiff(newKey []byte) []byte { var i int for i = 0; i < len(newKey) && i < len(b.baseKey); i++ { if newKey[i] != b.baseKey[i] { break } } return newKey[i:] }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L176-L200
func (s *FileSequence) Format(tpl string) (string, error) { c := map[string]interface{}{ "dir": s.Dirname, "base": s.Basename, "ext": s.Ext, "startf": s.Start, "endf": s.End, "len": s.Len, "pad": s.Padding, "zfill": s.ZFill, "frange": s.FrameRange, "inverted": s.InvertedFrameRange, } t, err := template.New("sequence").Funcs(c).Parse(tpl) if err != nil { return "", err } var buf bytes.Buffer err = t.Execute(&buf, c) if err != nil { return "", err } return buf.String(), nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/flags/unique_urls.go#L37-L56
func (us *UniqueURLs) Set(s string) error { if _, ok := us.Values[s]; ok { return nil } if _, ok := us.Allowed[s]; ok { us.Values[s] = struct{}{} return nil } ss, err := types.NewURLs(strings.Split(s, ",")) if err != nil { return err } us.Values = make(map[string]struct{}) us.uss = make([]url.URL, 0) for _, v := range ss { us.Values[v.String()] = struct{}{} us.uss = append(us.uss, v) } return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logging/log_posix.go#L10-L24
func getSystemHandler(syslog string, debug bool, format log.Format) log.Handler { // SyslogHandler if syslog != "" { if !debug { return log.LvlFilterHandler( log.LvlInfo, log.Must.SyslogHandler(syslog, format), ) } return log.Must.SyslogHandler(syslog, format) } return nil }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/maintenance/maintenance.go#L312-L323
func (s Service) OffHandler(w http.ResponseWriter, r *http.Request) { changed, err := s.store.Off() if err != nil { s.logger.Errorf("maintenance off: %s", err) jsonInternalServerErrorResponse(w) return } if changed { s.logger.Infof("maintenance off") } jsonOKResponse(w) }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/internal/api.go#L252-L255
func fromContext(ctx netcontext.Context) *context { c, _ := ctx.Value(&contextKey).(*context) return c }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/module/module.go#L50-L61
func SetNumInstances(c context.Context, module, version string, instances int) error { req := &pb.SetNumInstancesRequest{} if module != "" { req.Module = &module } if version != "" { req.Version = &version } req.Instances = proto.Int64(int64(instances)) res := &pb.SetNumInstancesResponse{} return internal.Call(c, "modules", "SetNumInstances", req, res) }
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/consumer.go#L158-L168
func (c *Consumer) MarkOffsets(s *OffsetStash) { s.mu.Lock() defer s.mu.Unlock() for tp, info := range s.offsets { if sub := c.subs.Fetch(tp.Topic, tp.Partition); sub != nil { sub.MarkOffset(info.Offset, info.Metadata) } delete(s.offsets, tp) } }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/format/format.go#L67-L72
func Message(actual interface{}, message string, expected ...interface{}) string { if len(expected) == 0 { return fmt.Sprintf("Expected\n%s\n%s", Object(actual, 1), message) } return fmt.Sprintf("Expected\n%s\n%s\n%s", Object(actual, 1), message, Object(expected[0], 1)) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L575-L579
func (v *SetScriptSourceReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger5(&r, v) return r.Error() }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/recorder/main.go#L147-L155
func write(b []byte) { f, err := os.OpenFile(output, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644) if err != nil { fail("failed to open output file") } f.Write(b) f.WriteString("\n") f.Close() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L4919-L4923
func (v *EventWindowOpen) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage50(&r, v) return r.Error() }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/mex.go#L347-L359
func (mexset *messageExchangeSet) deleteExchange(msgID uint32) (found, timedOut bool) { if _, found := mexset.exchanges[msgID]; found { delete(mexset.exchanges, msgID) return true, false } if _, expired := mexset.expiredExchanges[msgID]; expired { delete(mexset.expiredExchanges, msgID) return false, true } return false, false }
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/spanish/step2b.go#L11-L46
func step2b(word *snowballword.SnowballWord) bool { suffix, suffixRunes := word.FirstSuffixIn(word.RVstart, len(word.RS), "iésemos", "iéramos", "iríamos", "eríamos", "aríamos", "ásemos", "áramos", "ábamos", "isteis", "iríais", "iremos", "ieseis", "ierais", "eríais", "eremos", "asteis", "aríais", "aremos", "íamos", "irías", "irían", "iréis", "ieses", "iesen", "ieron", "ieras", "ieran", "iendo", "erías", "erían", "eréis", "aseis", "arías", "arían", "aréis", "arais", "abais", "íais", "iste", "iría", "irás", "irán", "imos", "iese", "iera", "idos", "idas", "ería", "erás", "erán", "aste", "ases", "asen", "aría", "arás", "arán", "aron", "aras", "aran", "ando", "amos", "ados", "adas", "abas", "aban", "ías", "ían", "éis", "áis", "iré", "irá", "ido", "ida", "eré", "erá", "emos", "ase", "aré", "ará", "ara", "ado", "ada", "aba", "ís", "ía", "ió", "ir", "id", "es", "er", "en", "ed", "as", "ar", "an", "ad", ) switch suffix { case "": return false case "en", "es", "éis", "emos": // Delete, and if preceded by gu delete the u (the gu need not be in RV) word.RemoveLastNRunes(len(suffixRunes)) guSuffix, _ := word.FirstSuffix("gu") if guSuffix != "" { word.RemoveLastNRunes(1) } default: // Delete word.RemoveLastNRunes(len(suffixRunes)) } return true }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/internal/mail/message.go#L292-L296
func SetCopyFunc(f func(io.Writer) error) FileSetting { return func(fi *file) { fi.CopyFunc = f } }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/repoowners/repoowners.go#L658-L660
func (o *RepoOwners) LeafReviewers(path string) sets.String { return o.entriesForFile(path, o.reviewers, true) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tracing/easyjson.go#L918-L922
func (v *EventTracingComplete) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoTracing8(&r, v) return r.Error() }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/status.go#L220-L226
func makeTrustedSubnetsSlice(trustedSubnets []*net.IPNet) []string { trustedSubnetStrs := []string{} for _, trustedSubnet := range trustedSubnets { trustedSubnetStrs = append(trustedSubnetStrs, trustedSubnet.String()) } return trustedSubnetStrs }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/tide/tide.go#L460-L472
func filterSubpool(ghc githubClient, sp *subpool) *subpool { var toKeep []PullRequest for _, pr := range sp.prs { if !filterPR(ghc, sp, &pr) { toKeep = append(toKeep, pr) } } if len(toKeep) == 0 { return nil } sp.prs = toKeep return sp }
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/discovery/discovery.go#L38-L58
func DiscoverDNS(address string) ([]string, error) { _, addresses, err := net.LookupSRV("mnemosyned", "grpc", address) if err != nil { return nil, err } if len(addresses) == 0 { return nil, errors.New("discovery: srv lookup retured nothing") } var ( tmp []service services []string ) for _, addr := range addresses { tmp = append(tmp, service{Address: addr.Target, Port: int(addr.Port)}) } for _, s := range tmp { services = append(services, fmt.Sprintf("%s:%d", s.Address, s.Port)) } return services, nil }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/export.go#L193-L202
func FrameSet_FrameRangePadded(id FrameSetId, pad int) (ret *C.char) { fs, ok := sFrameSets.Get(id) if !ok { ret = C.CString("") } else { ret = C.CString(fs.FrameRangePadded(pad)) } // caller must free the string return ret }
https://github.com/coreos/go-semver/blob/e214231b295a8ea9479f11b70b35d5acf3556d9b/semver/semver.go#L280-L284
func (v *Version) BumpPatch() { v.Patch += 1 v.PreRelease = PreRelease("") v.Metadata = "" }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/util.go#L999-L1008
func WriteTempFile(dir string, prefix string, content string) (string, error) { f, err := ioutil.TempFile(dir, prefix) if err != nil { return "", err } defer f.Close() _, err = f.WriteString(content) return f.Name(), err }
https://github.com/reiver/go-telnet/blob/9ff0b2ab096ebe42bf8e2ffd1366e7ed2223b04c/conn.go#L69-L92
func DialToTLS(addr string, tlsConfig *tls.Config) (*Conn, error) { const network = "tcp" if "" == addr { addr = "127.0.0.1:telnets" } conn, err := tls.Dial(network, addr, tlsConfig) if nil != err { return nil, err } dataReader := newDataReader(conn) dataWriter := newDataWriter(conn) clientConn := Conn{ conn:conn, dataReader:dataReader, dataWriter:dataWriter, } return &clientConn, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L1417-L1427
func (c *Client) UpdateBranchProtection(org, repo, branch string, config BranchProtectionRequest) error { c.log("UpdateBranchProtection", org, repo, branch, config) _, err := c.request(&request{ accept: "application/vnd.github.luke-cage-preview+json", // for required_approving_review_count method: http.MethodPut, path: fmt.Sprintf("/repos/%s/%s/branches/%s/protection", org, repo, branch), requestBody: config, exitCodes: []int{200}, }, nil) return err }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/examples/increment-only-counter/peer.go#L94-L107
func (p *peer) OnGossip(buf []byte) (delta mesh.GossipData, err error) { var set map[mesh.PeerName]int if err := gob.NewDecoder(bytes.NewReader(buf)).Decode(&set); err != nil { return nil, err } delta = p.st.mergeDelta(set) if delta == nil { p.logger.Printf("OnGossip %v => delta %v", set, delta) } else { p.logger.Printf("OnGossip %v => delta %v", set, delta.(*state).set) } return delta, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/images.go#L156-L314
func imgPostContInfo(d *Daemon, r *http.Request, req api.ImagesPost, op *operation, builddir string) (*api.Image, error) { info := api.Image{} info.Properties = map[string]string{} project := projectParam(r) name := req.Source.Name ctype := req.Source.Type if ctype == "" || name == "" { return nil, fmt.Errorf("No source provided") } switch ctype { case "snapshot": if !shared.IsSnapshot(name) { return nil, fmt.Errorf("Not a snapshot") } case "container": if shared.IsSnapshot(name) { return nil, fmt.Errorf("This is a snapshot") } default: return nil, fmt.Errorf("Bad type") } info.Filename = req.Filename switch req.Public { case true: info.Public = true case false: info.Public = false } c, err := containerLoadByProjectAndName(d.State(), project, name) if err != nil { return nil, err } // Build the actual image file imageFile, err := ioutil.TempFile(builddir, "lxd_build_image_") if err != nil { return nil, err } defer os.Remove(imageFile.Name()) // Calculate (close estimate of) total size of input to image totalSize := int64(0) sumSize := func(path string, fi os.FileInfo, err error) error { if err == nil { totalSize += fi.Size() } return nil } err = filepath.Walk(c.RootfsPath(), sumSize) if err != nil { return nil, err } // Track progress creating image. metadata := make(map[string]interface{}) imageProgressWriter := &ioprogress.ProgressWriter{ Tracker: &ioprogress.ProgressTracker{ Handler: func(value, speed int64) { percent := int64(0) processed := int64(0) if totalSize > 0 { percent = value processed = totalSize * (percent / 100.0) } else { processed = value } shared.SetProgressMetadata(metadata, "create_image_from_container_pack", "Image pack", percent, processed, speed) op.UpdateMetadata(metadata) }, Length: totalSize, }, } sha256 := sha256.New() var compress string var writer io.Writer if req.CompressionAlgorithm != "" { compress = req.CompressionAlgorithm } else { compress, err = cluster.ConfigGetString(d.cluster, "images.compression_algorithm") if err != nil { return nil, err } } // Setup tar, optional compress and sha256 to happen in one pass. wg := sync.WaitGroup{} var compressErr error if compress != "none" { wg.Add(1) tarReader, tarWriter := io.Pipe() imageProgressWriter.WriteCloser = tarWriter writer = imageProgressWriter compressWriter := io.MultiWriter(imageFile, sha256) go func() { defer wg.Done() compressErr = compressFile(compress, tarReader, compressWriter) }() } else { imageProgressWriter.WriteCloser = imageFile writer = io.MultiWriter(imageProgressWriter, sha256) } err = c.Export(writer, req.Properties) // When compression is used, Close on imageProgressWriter/tarWriter // is required for compressFile/gzip to know it is finished. // Otherwise It is equivalent to imageFile.Close. imageProgressWriter.Close() wg.Wait() if err != nil { return nil, err } if compressErr != nil { return nil, err } imageFile.Close() fi, err := os.Stat(imageFile.Name()) if err != nil { return nil, err } info.Size = fi.Size() info.Fingerprint = fmt.Sprintf("%x", sha256.Sum(nil)) _, _, err = d.cluster.ImageGet(project, info.Fingerprint, false, true) if err != db.ErrNoSuchObject { if err != nil { return nil, err } return &info, fmt.Errorf("The image already exists: %s", info.Fingerprint) } /* rename the the file to the expected name so our caller can use it */ finalName := shared.VarPath("images", info.Fingerprint) err = shared.FileMove(imageFile.Name(), finalName) if err != nil { return nil, err } info.Architecture, _ = osarch.ArchitectureName(c.Architecture()) info.Properties = req.Properties // Create the database entry err = d.cluster.ImageInsert(c.Project(), info.Fingerprint, info.Filename, info.Size, info.Public, info.AutoUpdate, info.Architecture, info.CreatedAt, info.ExpiresAt, info.Properties) if err != nil { return nil, err } return &info, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/jenkins/jenkins.go#L423-L433
func getJobName(spec *prowapi.ProwJobSpec) string { if spec.JenkinsSpec != nil && spec.JenkinsSpec.GitHubBranchSourceJob && spec.Refs != nil { if len(spec.Refs.Pulls) > 0 { return fmt.Sprintf("%s/view/change-requests/job/PR-%d", spec.Job, spec.Refs.Pulls[0].Number) } return fmt.Sprintf("%s/job/%s", spec.Job, spec.Refs.BaseRef) } return spec.Job }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/overlay.go#L227-L229
func (p *HighlightQuadParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandHighlightQuad, p, nil) }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gbytes/buffer.go#L48-L53
func BufferWithBytes(bytes []byte) *Buffer { return &Buffer{ lock: &sync.Mutex{}, contents: bytes, } }