_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/sidecar/run.go#L63-L106
func (o Options) Run(ctx context.Context) (int, error) { spec, err := downwardapi.ResolveSpecFromEnv() if err != nil { return 0, fmt.Errorf("could not resolve job spec: %v", err) } ctx, cancel := context.WithCancel(ctx) // If we are being asked to terminate by the kubelet but we have // NOT seen the test process exit cleanly, we need a to start // uploading artifacts to GCS immediately. If we notice the process // exit while doing this best-effort upload, we can race with the // second upload but we can tolerate this as we'd rather get SOME // data into GCS than attempt to cancel these uploads and get none. interrupt := make(chan os.Signal) signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM) go func() { select { case s := <-interrupt: logrus.Errorf("Received an interrupt: %s, cancelling...", s) cancel() case <-ctx.Done(): } }() if o.DeprecatedWrapperOptions != nil { // This only fires if the prowjob controller and sidecar are at different commits logrus.Warnf("Using deprecated wrapper_options instead of entries. Please update prow/pod-utils/decorate before June 2019") } entries := o.entries() passed, aborted, failures := wait(ctx, entries) cancel() // If we are being asked to terminate by the kubelet but we have // seen the test process exit cleanly, we need a chance to upload // artifacts to GCS. The only valid way for this program to exit // after a SIGINT or SIGTERM in this situation is to finish // uploading, so we ignore the signals. signal.Ignore(os.Interrupt, syscall.SIGTERM) buildLog := logReader(entries) metadata := combineMetadata(entries) return failures, o.doUpload(spec, passed, aborted, metadata, buildLog) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/kube/client.go#L271-L300
func NewClientInCluster(namespace string) (*Client, error) { tokenFile := "/var/run/secrets/kubernetes.io/serviceaccount/token" token, err := ioutil.ReadFile(tokenFile) if err != nil { return nil, err } rootCAFile := "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt" certData, err := ioutil.ReadFile(rootCAFile) if err != nil { return nil, err } cp := x509.NewCertPool() cp.AppendCertsFromPEM(certData) tr := &http.Transport{ TLSClientConfig: &tls.Config{ MinVersion: tls.VersionTLS12, RootCAs: cp, }, } return &Client{ logger: logrus.WithField("client", "kube"), baseURL: inClusterBaseURL, client: &http.Client{Transport: tr, Timeout: requestTimeout}, token: string(token), namespace: namespace, }, nil }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/envelope.go#L137-L153
func (e *Envelope) Clone() *Envelope { if e == nil { return nil } newEnvelope := &Envelope{ e.Text, e.HTML, e.Root.Clone(nil), e.Attachments, e.Inlines, e.OtherParts, e.Errors, e.header, } return newEnvelope }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/security/easyjson.go#L437-L441
func (v *EventSecurityStateChanged) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoSecurity2(&r, v) return r.Error() }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peers.go#L101-L107
func (peers *Peers) OnInvalidateShortIDs(callback func()) { peers.Lock() defer peers.Unlock() // Safe, as in OnGC peers.onInvalidateShortIDs = append(peers.onInvalidateShortIDs, callback) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/netutil/routes.go#L31-L33
func GetDefaultInterfaces() (map[string]uint8, error) { return nil, fmt.Errorf("default host not supported on %s_%s", runtime.GOOS, runtime.GOARCH) }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/health.go#L111-L161
func (c *Connection) healthCheck(connID uint32) { defer close(c.healthCheckDone) opts := c.opts.HealthChecks ticker := c.timeTicker(opts.Interval) defer ticker.Stop() consecutiveFailures := 0 for { select { case <-ticker.C: case <-c.healthCheckCtx.Done(): return } ctx, cancel := context.WithTimeout(c.healthCheckCtx, opts.Timeout) err := c.ping(ctx) cancel() c.healthCheckHistory.add(err == nil) if err == nil { if c.log.Enabled(LogLevelDebug) { c.log.Debug("Performed successful active health check.") } consecutiveFailures = 0 continue } // If the health check failed because the connection closed or health // checks were stopped, we don't need to log or close the connection. if GetSystemErrorCode(err) == ErrCodeCancelled || err == ErrInvalidConnectionState { c.log.WithFields(ErrField(err)).Debug("Health checker stopped.") return } consecutiveFailures++ c.log.WithFields(LogFields{ {"consecutiveFailures", consecutiveFailures}, ErrField(err), {"failuresToClose", opts.FailuresToClose}, }...).Warn("Failed active health check.") if consecutiveFailures >= opts.FailuresToClose { c.close(LogFields{ {"reason", "health check failure"}, ErrField(err), }...) return } } }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L1188-L1195
func (r *Backup) Locator(api *API) *BackupLocator { for _, l := range r.Links { if l["rel"] == "self" { return api.BackupLocator(l["href"]) } } return nil }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift-copies.go#L854-L895
func newProxierWithNoProxyCIDR(delegate func(req *http.Request) (*url.URL, error)) func(req *http.Request) (*url.URL, error) { // we wrap the default method, so we only need to perform our check if the NO_PROXY envvar has a CIDR in it noProxyEnv := os.Getenv("NO_PROXY") noProxyRules := strings.Split(noProxyEnv, ",") cidrs := []*net.IPNet{} for _, noProxyRule := range noProxyRules { _, cidr, _ := net.ParseCIDR(noProxyRule) if cidr != nil { cidrs = append(cidrs, cidr) } } if len(cidrs) == 0 { return delegate } return func(req *http.Request) (*url.URL, error) { host := req.URL.Host // for some urls, the Host is already the host, not the host:port if net.ParseIP(host) == nil { var err error host, _, err = net.SplitHostPort(req.URL.Host) if err != nil { return delegate(req) } } ip := net.ParseIP(host) if ip == nil { return delegate(req) } for _, cidr := range cidrs { if cidr.Contains(ip) { return nil, nil } } return delegate(req) } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/rafthttp/util.go#L46-L51
func NewRoundTripper(tlsInfo transport.TLSInfo, dialTimeout time.Duration) (http.RoundTripper, error) { // It uses timeout transport to pair with remote timeout listeners. // It sets no read/write timeout, because message in requests may // take long time to write out before reading out the response. return transport.NewTimeoutTransport(tlsInfo, dialTimeout, 0, 0) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/layout/oci_transport.go#L219-L225
func LoadManifestDescriptor(imgRef types.ImageReference) (imgspecv1.Descriptor, error) { ociRef, ok := imgRef.(ociReference) if !ok { return imgspecv1.Descriptor{}, errors.Errorf("error typecasting, need type ociRef") } return ociRef.getManifestDescriptor() }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/deploy/assets/assets.go#L426-L610
func PachdDeployment(opts *AssetOpts, objectStoreBackend backend, hostPath string) *apps.Deployment { // set port defaults if opts.PachdPort == 0 { opts.PachdPort = 650 } if opts.TracePort == 0 { opts.TracePort = 651 } if opts.HTTPPort == 0 { opts.HTTPPort = 652 } if opts.PeerPort == 0 { opts.PeerPort = 653 } mem := resource.MustParse(opts.BlockCacheSize) mem.Add(resource.MustParse(opts.PachdNonCacheMemRequest)) cpu := resource.MustParse(opts.PachdCPURequest) image := AddRegistry(opts.Registry, versionedPachdImage(opts)) volumes := []v1.Volume{ { Name: "pach-disk", }, } volumeMounts := []v1.VolumeMount{ { Name: "pach-disk", MountPath: "/pach", }, } // Set up storage options var backendEnvVar string var storageHostPath string switch objectStoreBackend { case localBackend: storageHostPath = filepath.Join(hostPath, "pachd") volumes[0].HostPath = &v1.HostPathVolumeSource{ Path: storageHostPath, } backendEnvVar = pfs.LocalBackendEnvVar case minioBackend: backendEnvVar = pfs.MinioBackendEnvVar case amazonBackend: backendEnvVar = pfs.AmazonBackendEnvVar case googleBackend: backendEnvVar = pfs.GoogleBackendEnvVar case microsoftBackend: backendEnvVar = pfs.MicrosoftBackendEnvVar } volume, mount := GetBackendSecretVolumeAndMount(backendEnvVar) volumes = append(volumes, volume) volumeMounts = append(volumeMounts, mount) if opts.TLS != nil { volumes = append(volumes, v1.Volume{ Name: tlsVolumeName, VolumeSource: v1.VolumeSource{ Secret: &v1.SecretVolumeSource{ SecretName: tlsSecretName, }, }, }) volumeMounts = append(volumeMounts, v1.VolumeMount{ Name: tlsVolumeName, MountPath: grpcutil.TLSVolumePath, }) } 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, } } return &apps.Deployment{ TypeMeta: metav1.TypeMeta{ Kind: "Deployment", APIVersion: "apps/v1beta1", }, ObjectMeta: objectMeta(pachdName, labels(pachdName), nil, opts.Namespace), Spec: apps.DeploymentSpec{ Replicas: replicas(1), Selector: &metav1.LabelSelector{ MatchLabels: labels(pachdName), }, Template: v1.PodTemplateSpec{ ObjectMeta: objectMeta(pachdName, labels(pachdName), map[string]string{IAMAnnotation: opts.IAMRole}, opts.Namespace), Spec: v1.PodSpec{ Containers: []v1.Container{ { Name: pachdName, Image: image, Env: append([]v1.EnvVar{ {Name: "PACH_ROOT", Value: "/pach"}, {Name: "ETCD_PREFIX", Value: opts.EtcdPrefix}, {Name: "NUM_SHARDS", Value: fmt.Sprintf("%d", opts.PachdShards)}, {Name: "STORAGE_BACKEND", Value: backendEnvVar}, {Name: "STORAGE_HOST_PATH", Value: storageHostPath}, {Name: "WORKER_IMAGE", Value: AddRegistry(opts.Registry, versionedWorkerImage(opts))}, {Name: "IMAGE_PULL_SECRET", Value: opts.ImagePullSecret}, {Name: "WORKER_SIDECAR_IMAGE", Value: image}, {Name: "WORKER_IMAGE_PULL_POLICY", Value: "IfNotPresent"}, {Name: "PACHD_VERSION", Value: opts.Version}, {Name: "METRICS", Value: strconv.FormatBool(opts.Metrics)}, {Name: "LOG_LEVEL", Value: opts.LogLevel}, {Name: "BLOCK_CACHE_BYTES", Value: opts.BlockCacheSize}, {Name: "IAM_ROLE", Value: opts.IAMRole}, {Name: "NO_EXPOSE_DOCKER_SOCKET", Value: strconv.FormatBool(opts.NoExposeDockerSocket)}, {Name: auth.DisableAuthenticationEnvVar, Value: strconv.FormatBool(opts.DisableAuthentication)}, { Name: "PACHD_POD_NAMESPACE", ValueFrom: &v1.EnvVarSource{ FieldRef: &v1.ObjectFieldSelector{ APIVersion: "v1", FieldPath: "metadata.namespace", }, }, }, { Name: "PACHD_MEMORY_REQUEST", ValueFrom: &v1.EnvVarSource{ ResourceFieldRef: &v1.ResourceFieldSelector{ ContainerName: "pachd", Resource: "requests.memory", }, }, }, {Name: "EXPOSE_OBJECT_API", Value: strconv.FormatBool(opts.ExposeObjectAPI)}, }, GetSecretEnvVars("")...), Ports: []v1.ContainerPort{ { ContainerPort: opts.PachdPort, // also set in cmd/pachd/main.go Protocol: "TCP", Name: "api-grpc-port", }, { ContainerPort: opts.TracePort, // also set in cmd/pachd/main.go Name: "trace-port", }, { ContainerPort: opts.HTTPPort, // also set in cmd/pachd/main.go Protocol: "TCP", Name: "api-http-port", }, { ContainerPort: opts.PeerPort, // also set in cmd/pachd/main.go Protocol: "TCP", Name: "peer-port", }, { ContainerPort: githook.GitHookPort, Protocol: "TCP", Name: "api-git-port", }, { ContainerPort: auth.SamlPort, Protocol: "TCP", Name: "saml-port", }, }, VolumeMounts: volumeMounts, ImagePullPolicy: "IfNotPresent", Resources: resourceRequirements, ReadinessProbe: &v1.Probe{ Handler: v1.Handler{ Exec: &v1.ExecAction{ Command: []string{"/pachd", "--readiness"}, }, }, }, }, }, ServiceAccountName: ServiceAccountName, Volumes: volumes, ImagePullSecrets: imagePullSecrets(opts), }, }, }, } }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L621-L628
func XorWithMask(src1, src2, dst, mask *IplImage) { C.cvXor( unsafe.Pointer(src1), unsafe.Pointer(src2), unsafe.Pointer(dst), unsafe.Pointer(mask), ) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L2170-L2174
func (v *SetCacheDisabledParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork16(&r, v) return r.Error() }
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/message.go#L122-L149
func (m Message) Write(w *bufio.Writer) (err error) { if err = writeFrameHeader(w, FrameTypeMessage, len(m.Body)+26); err != nil { err = errors.WithMessage(err, "writing message") return } if err = binary.Write(w, binary.BigEndian, m.Timestamp.UnixNano()); err != nil { err = errors.Wrap(err, "writing message") return } if err = binary.Write(w, binary.BigEndian, m.Attempts); err != nil { err = errors.Wrap(err, "writing message") return } if _, err = m.ID.WriteTo(w); err != nil { err = errors.Wrap(err, "writing message") return } if _, err = w.Write(m.Body); err != nil { err = errors.Wrap(err, "writing message") return } return }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/export.go#L97-L103
func FrameSet_Len(id FrameSetId) C.size_t { fs, ok := sFrameSets.Get(id) if !ok { return C.size_t(0) } return C.size_t(fs.Len()) }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/state.go#L12-L28
func NewState() *State { st := &State{ opidx: 0, pc: NewByteCode(), stack: stack.New(5), markstack: stack.New(5), framestack: stack.New(5), frames: stack.New(5), vars: make(Vars), warn: os.Stderr, MaxLoopCount: 1000, } st.Pushmark() st.PushFrame() return st }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/css.go#L475-L484
func (p *GetStyleSheetTextParams) Do(ctx context.Context) (text string, err error) { // execute var res GetStyleSheetTextReturns err = cdp.Execute(ctx, CommandGetStyleSheetText, p, &res) if err != nil { return "", err } return res.Text, nil }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vm.go#L2060-L2070
func (v *VM) SetVirtualHwVersion(version string) error { return v.updateVMX(func(model *vmx.VirtualMachine) error { version, err := strconv.ParseInt(version, 10, 32) if err != nil { return err } model.Vhardware.Compat = "hosted" model.Vhardware.Version = int(version) return nil }) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L4352-L4356
func (v GetContentQuadsParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom49(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L1890-L1894
func (v *SetMediaTextReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss17(&r, v) return r.Error() }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L10224-L10226
func (api *API) RunnableBindingLocator(href string) *RunnableBindingLocator { return &RunnableBindingLocator{Href(href), api} }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plank/controller.go#L264-L280
func (c *Controller) terminateDupes(pjs []prowapi.ProwJob, pm map[string]coreapi.Pod) error { log := c.log.WithField("aborter", "pod") return pjutil.TerminateOlderPresubmitJobs(c.kc, log, pjs, func(toCancel prowapi.ProwJob) error { // Allow aborting presubmit jobs for commits that have been superseded by // newer commits in GitHub pull requests. if c.config().Plank.AllowCancellations { if pod, exists := pm[toCancel.ObjectMeta.Name]; exists { if client, ok := c.pkcs[toCancel.ClusterAlias()]; !ok { return fmt.Errorf("unknown cluster alias %q", toCancel.ClusterAlias()) } else if err := client.DeletePod(pod.ObjectMeta.Name); err != nil { return fmt.Errorf("deleting pod: %v", err) } } } return nil }) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_pools.go#L394-L415
func (c *Cluster) StoragePoolsGetDrivers() ([]string, error) { var poolDriver string query := "SELECT DISTINCT driver FROM storage_pools" inargs := []interface{}{} outargs := []interface{}{poolDriver} result, err := queryScan(c.db, query, inargs, outargs) if err != nil { return []string{}, err } if len(result) == 0 { return []string{}, ErrNoSuchObject } drivers := []string{} for _, driver := range result { drivers = append(drivers, driver[0].(string)) } return drivers, nil }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/cluster.go#L201-L238
func deleteCluster(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { allowed := permission.Check(t, permission.PermClusterDelete) if !allowed { return permission.ErrUnauthorized } clusterName := r.URL.Query().Get(":name") evt, err := event.New(&event.Opts{ Target: event.Target{Type: event.TargetTypeCluster, Value: clusterName}, Kind: permission.PermClusterDelete, Owner: t, CustomData: event.FormToCustomData(InputFields(r)), Allowed: event.Allowed(permission.PermClusterReadEvents), }) if err != nil { return err } defer func() { evt.Done(err) }() streamResponse := strings.HasPrefix(r.Header.Get("Accept"), "application/x-json-stream") if streamResponse { w.Header().Set("Content-Type", "application/x-json-stream") keepAliveWriter := tsuruIo.NewKeepAliveWriter(w, 30*time.Second, "") defer keepAliveWriter.Stop() writer := &tsuruIo.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)} evt.SetLogWriter(writer) } err = servicemanager.Cluster.Delete(provTypes.Cluster{Name: clusterName, Writer: evt}) if err != nil { if errors.Cause(err) == provTypes.ErrClusterNotFound { return &tsuruErrors.HTTP{ Code: http.StatusNotFound, Message: err.Error(), } } return err } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/easyjson.go#L196-L200
func (v Version) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoServiceworker(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L103-L106
func (p CaptureScreenshotParams) WithFormat(format CaptureScreenshotFormat) *CaptureScreenshotParams { p.Format = format return &p }
https://github.com/nicholasjackson/bench/blob/2df9635f0ad020b2e82616b0fd87130aaa1ee12e/bench.go#L68-L73
func (b *Bench) RunBenchmarks(r RequestFunc) { b.request = r results := b.internalRun(b.showProgress) b.processResults(results) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L2646-L2650
func (v *AttachToBrowserTargetParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoTarget31(&r, v) return r.Error() }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/table/iterator.go#L532-L539
func (s *ConcatIterator) Close() error { for _, it := range s.iters { if err := it.Close(); err != nil { return errors.Wrap(err, "ConcatIterator") } } return nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv2/command/ls_command.go#L65-L77
func printLs(c *cli.Context, resp *client.Response) { if c.GlobalString("output") == "simple" { if !resp.Node.Dir { fmt.Println(resp.Node.Key) } for _, node := range resp.Node.Nodes { rPrint(c, node) } } else { // user wants JSON or extended output printResponseKey(resp, c.GlobalString("output")) } }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/iterator.go#L183-L191
func (s *MergeIterator) Valid() bool { if s == nil { return false } if len(s.h) == 0 { return false } return s.h[0].itr.Valid() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/types.go#L395-L397
func (t *ResourcePriority) UnmarshalJSON(buf []byte) error { return easyjson.Unmarshal(buf, t) }
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L811-L813
func (g *Glg) Debug(val ...interface{}) error { return g.out(DEBG, blankFormat(len(val)), val...) }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/handlers.go#L81-L90
func (hmap *handlerMap) register(h Handler, method string) { hmap.Lock() defer hmap.Unlock() if hmap.handlers == nil { hmap.handlers = make(map[string]Handler) } hmap.handlers[method] = h }
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/server.go#L84-L89
func (c *Client) UpdateServer(dcid string, srvid string, props ServerProperties) (*Server, error) { url := serverPath(dcid, srvid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty) ret := &Server{} err := c.client.Patch(url, props, ret, http.StatusAccepted) return ret, err }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/artifact-uploader/main.go#L60-L70
func (o *Options) Validate() error { if o.NumWorkers == 0 { return errors.New("number of workers cannot be zero") } if o.ProwJobNamespace == "" { return errors.New("namespace containing ProwJobs not configured") } return o.Options.Validate() }
https://github.com/senseyeio/roger/blob/5a944f2c5ceb5139f926c5ae134202ec2abba71a/client.go#L37-L53
func NewRClientWithAuth(host string, port int64, user, password string) (RClient, error) { addr, err := net.ResolveTCPAddr("tcp", host+":"+strconv.FormatInt(port, 10)) if err != nil { return nil, err } rClient := &roger{ address: addr, user: user, password: password, } if _, err = rClient.Eval("'Test session connection'"); err != nil { return nil, err } return rClient, nil }
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mocktracer.go#L61-L67
func (t *MockTracer) StartSpan(operationName string, opts ...opentracing.StartSpanOption) opentracing.Span { sso := opentracing.StartSpanOptions{} for _, o := range opts { o.Apply(&sso) } return newMockSpan(t, operationName, sso) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L1481-L1483
func (p *UndoParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandUndo, nil, nil) }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/router.go#L28-L75
func listRouters(w http.ResponseWriter, r *http.Request, t auth.Token) error { contexts := permission.ContextsForPermission(t, permission.PermAppCreate) var teams []string var global bool contexts: for _, c := range contexts { switch c.CtxType { case permTypes.CtxGlobal: global = true break contexts case permTypes.CtxTeam: teams = append(teams, c.Value) } } routers, err := router.ListWithInfo() if err != nil { return err } filteredRouters := routers if !global { routersAllowed := make(map[string]struct{}) filteredRouters = []router.PlanRouter{} pools, err := pool.ListPossiblePools(teams) if err != nil { return err } for _, p := range pools { rs, err := p.GetRouters() if err != nil { return err } for _, r := range rs { routersAllowed[r] = struct{}{} } } for _, r := range routers { if _, ok := routersAllowed[r.Name]; ok { filteredRouters = append(filteredRouters, r) } } } if len(filteredRouters) == 0 { w.WriteHeader(http.StatusNoContent) return nil } w.Header().Set("Content-Type", "application/json") return json.NewEncoder(w).Encode(filteredRouters) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tracing/easyjson.go#L1163-L1167
func (v EndParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoTracing11(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/fetcher/client.go#L60-L72
func (client *Client) CheckFlags() error { if client.Org == "" { return fmt.Errorf("organization flag must be set") } client.Org = strings.ToLower(client.Org) if client.Project == "" { return fmt.Errorf("project flag must be set") } client.Project = strings.ToLower(client.Project) return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/log/types.go#L162-L164
func (t *Level) UnmarshalJSON(buf []byte) error { return easyjson.Unmarshal(buf, t) }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/stats/metrickey.go#L31-L33
func DefaultMetricPrefix(name string, tags map[string]string) string { return MetricWithPrefix("tchannel.", name, tags) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L6913-L6916
func (e ScpStatementType) String() string { name, _ := scpStatementTypeMap[int32(e)] return name }
https://github.com/codegangsta/martini-contrib/blob/8ce6181c2609699e4c7cd30994b76a850a9cdadc/binding/binding.go#L240-L285
func setWithProperType(valueKind reflect.Kind, val string, structField reflect.Value, nameInTag string, errors *Errors) { switch valueKind { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: if val == "" { val = "0" } intVal, err := strconv.Atoi(val) if err != nil { errors.Fields[nameInTag] = IntegerTypeError } else { structField.SetInt(int64(intVal)) } case reflect.Bool: if val == "" { val = "false" } boolVal, err := strconv.ParseBool(val) if err != nil { errors.Fields[nameInTag] = BooleanTypeError } else { structField.SetBool(boolVal) } case reflect.Float32: if val == "" { val = "0.0" } floatVal, err := strconv.ParseFloat(val, 32) if err != nil { errors.Fields[nameInTag] = FloatTypeError } else { structField.SetFloat(floatVal) } case reflect.Float64: if val == "" { val = "0.0" } floatVal, err := strconv.ParseFloat(val, 64) if err != nil { errors.Fields[nameInTag] = FloatTypeError } else { structField.SetFloat(floatVal) } case reflect.String: structField.SetString(val) } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/ioutil/reader.go#L22-L27
func NewLimitedBufferReader(r io.Reader, n int) io.Reader { return &limitedBufferReader{ r: r, n: n, } }
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/bool.go#L117-L120
func (b *Bool) SetValid(v bool) { b.Bool = v b.Valid = true }
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/decode.go#L1310-L1315
func (d *StreamDecoder) Err() error { if d.err == End { return nil } return d.err }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/networks.go#L232-L234
func (c *ClusterTx) NetworkErrored(name string) error { return c.networkState(name, networkErrored) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L5025-L5029
func (v GetAllCookiesParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork39(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/stefantalpalaru/pool/blob/df8b849d27751462526089005979b28064c1e08e/pool.go#L184-L197
func (pool *Pool) Run() { if pool.workers_started { panic("trying to start a pool that's already running") } for i := uint(0); i < uint(pool.num_workers); i++ { pool.worker_wg.Add(1) go pool.worker(i) } pool.workers_started = true // handle the supervisor if !pool.supervisor_started { pool.startSupervisor() } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L1390-L1398
func (r *ProtocolLXD) UpdateContainerState(name string, state api.ContainerStatePut, ETag string) (Operation, error) { // Send the request op, _, err := r.queryOperation("PUT", fmt.Sprintf("/containers/%s/state", url.QueryEscape(name)), state, ETag) if err != nil { return nil, err } return op, nil }
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/seekret.go#L55-L92
func (s *Seekret) LoadRulesFromFile(file string, defaulEnabled bool) error { var ruleYamlMap map[string]ruleYaml if file == "" { return nil } filename, _ := filepath.Abs(file) ruleBase := filepath.Base(filename) if filepath.Ext(ruleBase) == ".rule" { ruleBase = ruleBase[0 : len(ruleBase)-5] } yamlData, err := ioutil.ReadFile(filename) if err != nil { return err } err = yaml.Unmarshal(yamlData, &ruleYamlMap) if err != nil { return err } for k, v := range ruleYamlMap { rule, err := models.NewRule(ruleBase+"."+k, v.Match) if err != nil { return err } for _, e := range v.Unmatch { rule.AddUnmatch(e) } s.AddRule(*rule, defaulEnabled) } return nil }
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/outgoing.go#L248-L251
func (ov *OutgoingVenue) SetFoursquareID(to string) *OutgoingVenue { ov.FoursquareID = to return ov }
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/decode.go#L31-L36
func NewDecoder(p Parser) *Decoder { if p == nil { panic("objconv: the parser is nil") } return &Decoder{Parser: p} }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L810-L813
func (p PerformSearchParams) WithIncludeUserAgentShadowDOM(includeUserAgentShadowDOM bool) *PerformSearchParams { p.IncludeUserAgentShadowDOM = includeUserAgentShadowDOM return &p }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/route.go#L78-L85
func (a RouteList) Lookup(name string) (*RouteInfo, error) { for _, ri := range a { if ri.PathName == name { return ri, nil } } return nil, errors.New("path name not found") }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/css.go#L437-L446
func (p *GetPlatformFontsForNodeParams) Do(ctx context.Context) (fonts []*PlatformFontUsage, err error) { // execute var res GetPlatformFontsForNodeReturns err = cdp.Execute(ctx, CommandGetPlatformFontsForNode, p, &res) if err != nil { return nil, err } return res.Fonts, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pluginhelp/hook/hook.go#L335-L348
func orgsInConfig(config *plugins.Configuration) sets.String { orgs := sets.NewString() for repo := range config.Plugins { if !strings.Contains(repo, "/") { orgs.Insert(repo) } } for repo := range config.ExternalPlugins { if !strings.Contains(repo, "/") { orgs.Insert(repo) } } return orgs }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/callback.go#L24-L63
func Callback(force bool, scope ...string) *fire.Callback { return fire.C("flame/Callback", fire.All(), func(ctx *fire.Context) error { // coerce scope s := oauth2.Scope(scope) // get access token accessToken, _ := ctx.HTTPRequest.Context().Value(AccessTokenContextKey).(GenericToken) // check access token if accessToken == nil { // return error if authentication is required if force { return fire.ErrAccessDenied } return nil } // validate scope _, scope, _, _, _ := accessToken.GetTokenData() if !oauth2.Scope(scope).Includes(s) { return fire.ErrAccessDenied } // get client client := ctx.HTTPRequest.Context().Value(ClientContextKey).(Client) // get resource owner resourceOwner, _ := ctx.HTTPRequest.Context().Value(ResourceOwnerContextKey).(ResourceOwner) // store auth info ctx.Data[AuthInfoDataKey] = &AuthInfo{ Client: client, ResourceOwner: resourceOwner, AccessToken: accessToken, } return nil }) }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/service.go#L224-L255
func serviceProxy(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { serviceName := r.URL.Query().Get(":service") s, err := getService(serviceName) if err != nil { return err } allowed := permission.Check(t, permission.PermServiceUpdateProxy, contextsForServiceProvision(&s)..., ) if !allowed { return permission.ErrUnauthorized } var evt *event.Event if r.Method != http.MethodGet && r.Method != http.MethodHead { evt, err = event.New(&event.Opts{ Target: serviceTarget(s.Name), Kind: permission.PermServiceUpdateProxy, Owner: t, CustomData: append(event.FormToCustomData(InputFields(r)), map[string]interface{}{ "name": "method", "value": r.Method, }), Allowed: event.Allowed(permission.PermServiceReadEvents, contextsForServiceProvision(&s)...), }) if err != nil { return err } defer func() { evt.Done(err) }() } path := r.URL.Query().Get("callback") return service.Proxy(&s, path, evt, requestIDHeader(r), w, r) }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/helloworld/helloworld.go#L28-L40
func Draw(gc draw2d.GraphicContext, text string) { // Draw a rounded rectangle using default colors draw2dkit.RoundedRectangle(gc, 5, 5, 135, 95, 10, 10) gc.FillStroke() // Set the font luximbi.ttf gc.SetFontData(draw2d.FontData{Name: "luxi", Family: draw2d.FontFamilyMono, Style: draw2d.FontStyleBold | draw2d.FontStyleItalic}) // Set the fill text color to black gc.SetFillColor(image.Black) gc.SetFontSize(14) // Display Hello World gc.FillStringAt("Hello World", 8, 52) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L4191-L4195
func (v *GetStyleSheetTextParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss36(&r, v) return r.Error() }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/path.go#L49-L54
func clean(p string) string { if !strings.HasPrefix(p, "/") { p = "/" + p } return internalDefault(path.Clean(p)) }
https://github.com/tylerb/gls/blob/e606233f194d6c314156dc6a35f21a42a470c6f6/gls.go#L88-L94
func getValues() Values { gid := curGoroutineID() dataLock.Lock() values := data[gid] dataLock.Unlock() return values }
https://github.com/goware/urlx/blob/4fc201f7f862af2abfaca0c2904be15ea0037a34/urlx.go#L98-L121
func SplitHostPort(u *url.URL) (host, port string, err error) { if u == nil { return "", "", &url.Error{Op: "host", URL: host, Err: errors.New("empty url")} } host = u.Host // Find last colon. if i := strings.LastIndex(host, ":"); i != -1 { // If we're not inside [IPv6] brackets, split host:port. if len(host) > i && !strings.Contains(host[i:], "]") { port = host[i+1:] host = host[:i] } } // Port is optional. But if it's set, is it a number? if port != "" { if _, err := strconv.Atoi(port); err != nil { return "", "", &url.Error{Op: "port", URL: host, Err: err} } } return host, port, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/connection.go#L75-L123
func ConnectLXDUnix(path string, args *ConnectionArgs) (ContainerServer, error) { logger.Debugf("Connecting to a local LXD over a Unix socket") // Use empty args if not specified if args == nil { args = &ConnectionArgs{} } // Initialize the client struct server := ProtocolLXD{ httpHost: "http://unix.socket", httpUnixPath: path, httpProtocol: "unix", httpUserAgent: args.UserAgent, } // Determine the socket path if path == "" { path = os.Getenv("LXD_SOCKET") if path == "" { lxdDir := os.Getenv("LXD_DIR") if lxdDir == "" { lxdDir = "/var/lib/lxd" } path = filepath.Join(lxdDir, "unix.socket") } } // Setup the HTTP client httpClient, err := unixHTTPClient(args.HTTPClient, path) if err != nil { return nil, err } server.http = httpClient // Test the connection and seed the server information if !args.SkipGetServer { serverStatus, _, err := server.GetServer() if err != nil { return nil, err } // Record the server certificate server.httpCertificate = serverStatus.Environment.Certificate } return &server, nil }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dsvg/gc.go#L158-L181
func (gc *GraphicContext) CreateStringPath(s string, x, y float64) (cursor float64) { f, err := gc.loadCurrentFont() if err != nil { log.Println(err) return 0.0 } startx := x prev, hasPrev := truetype.Index(0), false for _, rune := range s { index := f.Index(rune) if hasPrev { x += fUnitsToFloat64(f.Kern(fixed.Int26_6(gc.Current.Scale), prev, index)) } err := gc.drawGlyph(index, x, y) if err != nil { log.Println(err) return startx - x } x += fUnitsToFloat64(f.HMetric(fixed.Int26_6(gc.Current.Scale), index).AdvanceWidth) prev, hasPrev = index, true } return x - startx }
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/producer.go#L93-L101
func StartProducer(config ProducerConfig) (p *Producer, err error) { p, err = NewProducer(config) if err != nil { return } p.Start() return }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L873-L885
func (c *Client) CreateComment(org, repo string, number int, comment string) error { c.log("CreateComment", org, repo, number, comment) ic := IssueComment{ Body: comment, } _, err := c.request(&request{ method: http.MethodPost, path: fmt.Sprintf("/repos/%s/%s/issues/%d/comments", org, repo, number), requestBody: &ic, exitCodes: []int{201}, }, nil) return err }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/urlfetch/urlfetch.go#L112-L119
func urlString(u *url.URL) string { if u.Opaque == "" || strings.HasPrefix(u.Opaque, "//") { return u.String() } aux := *u aux.Opaque = "//" + aux.Host + aux.Opaque return aux.String() }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/auth/cmds/cmds.go#L54-L108
func ActivateCmd(noMetrics, noPortForwarding *bool) *cobra.Command { var initialAdmin string activate := &cobra.Command{ Short: "Activate Pachyderm's auth system", Long: ` Activate Pachyderm's auth system, and restrict access to existing data to the user running the command (or the argument to --initial-admin), who will be the first cluster admin`[1:], Run: cmdutil.Run(func(args []string) error { var token string var err error if !strings.HasPrefix(initialAdmin, auth.RobotPrefix) { token, err = githubLogin() if err != nil { return err } } fmt.Println("Retrieving Pachyderm token...") // Exchange GitHub token for Pachyderm token c, err := client.NewOnUserMachine(!*noMetrics, !*noPortForwarding, "user") if err != nil { return fmt.Errorf("could not connect: %v", err) } defer c.Close() resp, err := c.Activate(c.Ctx(), &auth.ActivateRequest{ GitHubToken: token, Subject: initialAdmin, }) if err != nil { return fmt.Errorf("error activating Pachyderm auth: %v", grpcutil.ScrubGRPC(err)) } if err := writePachTokenToCfg(resp.PachToken); err != nil { return err } if strings.HasPrefix(initialAdmin, auth.RobotPrefix) { fmt.Println("WARNING: DO NOT LOSE THE ROBOT TOKEN BELOW WITHOUT " + "ADDING OTHER ADMINS.\nIF YOU DO, YOU WILL BE PERMANENTLY LOCKED OUT " + "OF YOUR CLUSTER!") fmt.Printf("Pachyderm token for \"%s\":\n%s\n", initialAdmin, resp.PachToken) } return nil }), } activate.PersistentFlags().StringVar(&initialAdmin, "initial-admin", "", ` The subject (robot user or github user) who will be the first cluster admin; the user running 'activate' will identify as this user once auth is active. If you set 'initial-admin' to a robot user, pachctl will print that robot user's Pachyderm token; this token is effectively a root token, and if it's lost you will be locked out of your cluster`[1:]) return cmdutil.CreateAlias(activate, "auth activate") }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L204-L208
func (q *Query) Distinct() *Query { q = q.clone() q.distinct = true return q }
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/french/step6.go#L9-L42
func step6(word *snowballword.SnowballWord) bool { // If the words ends é or è (unicode code points 233 and 232) // followed by at least one non-vowel, remove the accent from the e. // Note, this step is oddly articulated on Porter's Snowball website: // http://snowball.tartarus.org/algorithms/french/stemmer.html // More clearly stated, we should replace é or è with e in the // case where the suffix of the word is é or è followed by // one-or-more non-vowels. numNonVowels := 0 for i := len(word.RS) - 1; i >= 0; i-- { r := word.RS[i] if isLowerVowel(r) == false { numNonVowels += 1 } else { // `r` is a vowel if (r == 233 || r == 232) && numNonVowels > 0 { // Replace with "e", or unicode code point 101 word.RS[i] = 101 return true } return false } } return false }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/blobstore/blobstore.go#L101-L121
func UploadURL(c context.Context, successPath string, opts *UploadURLOptions) (*url.URL, error) { req := &blobpb.CreateUploadURLRequest{ SuccessPath: proto.String(successPath), } if opts != nil { if n := opts.MaxUploadBytes; n != 0 { req.MaxUploadSizeBytes = &n } if n := opts.MaxUploadBytesPerBlob; n != 0 { req.MaxUploadSizePerBlobBytes = &n } if s := opts.StorageBucket; s != "" { req.GsBucketName = &s } } res := &blobpb.CreateUploadURLResponse{} if err := internal.Call(c, "blobstore", "CreateUploadURL", req, res); err != nil { return nil, err } return url.Parse(*res.Url) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/webaudio/types.go#L50-L60
func (t *ContextType) UnmarshalEasyJSON(in *jlexer.Lexer) { switch ContextType(in.String()) { case ContextTypeRealtime: *t = ContextTypeRealtime case ContextTypeOffline: *t = ContextTypeOffline default: in.AddError(errors.New("unknown ContextType value")) } }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/auth/auth.go#L87-L94
func IsErrPartiallyActivated(err error) bool { if err == nil { return false } // TODO(msteffen) This is unstructured because we have no way to propagate // structured errors across GRPC boundaries. Fix return strings.Contains(err.Error(), status.Convert(ErrPartiallyActivated).Message()) }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/retry.go#L262-L269
func getHost(hostPort string) string { for i := 0; i < len(hostPort); i++ { if hostPort[i] == ':' { return hostPort[:i] } } return hostPort }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/routes.go#L50-L54
func (r *routes) OnChange(callback func()) { r.Lock() defer r.Unlock() r.onChange = append(r.onChange, callback) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/cert/logging_conn.go#L50-L54
func (p *loggingPipe) Close() error { p.clientWriter.Close() p.serverWriter.Close() return nil }
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/item.go#L79-L93
func (m *Nitro) DecodeItem(buf []byte, r io.Reader) (*Item, error) { if _, err := io.ReadFull(r, buf[0:2]); err != nil { return nil, err } l := binary.BigEndian.Uint16(buf[0:2]) if l > 0 { itm := m.allocItem(int(l), m.useMemoryMgmt) data := itm.Bytes() _, err := io.ReadFull(r, data) return itm, err } return nil, nil }
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/router.go#L73-L102
func escapedPathExp(pathExp string) (string, error) { // PathExp validation if pathExp == "" { return "", errors.New("empty PathExp") } if pathExp[0] != '/' { return "", errors.New("PathExp must start with /") } if strings.Contains(pathExp, "?") { return "", errors.New("PathExp must not contain the query string") } // Get the right escaping // XXX a bit hacky pathExp = preEscape.Replace(pathExp) urlObj, err := url.Parse(pathExp) if err != nil { return "", err } // get the same escaping as find requests pathExp = urlObj.RequestURI() pathExp = postEscape.Replace(pathExp) return pathExp, nil }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/walk/walk.go#L209-L211
func shouldCall(rel string, mode Mode, updateRels map[string]bool) bool { return mode != UpdateDirsMode || updateRels[rel] }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/easyjson.go#L903-L907
func (v *ObjectStore) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoIndexeddb7(&r, v) return r.Error() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node/sqlite.go#L15-L24
func sqliteOpen(path string) (*sql.DB, error) { timeout := 5 // TODO - make this command-line configurable? // These are used to tune the transaction BEGIN behavior instead of using the // similar "locking_mode" pragma (locking for the whole database connection). openPath := fmt.Sprintf("%s?_busy_timeout=%d&_txlock=exclusive", path, timeout*1000) // Open the database. If the file doesn't exist it is created. return sql.Open("sqlite3_with_fk", openPath) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L570-L574
func (v SetNodeNameParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom5(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/election.go#L49-L57
func ResumeElection(s *Session, pfx string, leaderKey string, leaderRev int64) *Election { return &Election{ keyPrefix: pfx, session: s, leaderKey: leaderKey, leaderRev: leaderRev, leaderSession: s, } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L3832-L3836
func (v *GetFlattenedDocumentParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom43(&r, v) return r.Error() }
https://github.com/olorin/nagiosplugin/blob/893f9702af4ea1e2dc4cd6528cbdcdb3dc7ca064/result.go#L70-L82
func (s Status) String() string { switch s { case OK: return "OK" case WARNING: return "WARNING" case CRITICAL: return "CRITICAL" case UNKNOWN: return "UNKNOWN" } panic("Invalid nagiosplugin.Status.") }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_volumes.go#L194-L250
func (c *Cluster) StorageVolumeIsAvailable(pool, volume string) (bool, error) { isAvailable := false err := c.Transaction(func(tx *ClusterTx) error { id, err := tx.StoragePoolID(pool) if err != nil { return errors.Wrapf(err, "Fetch storage pool ID for %q", pool) } driver, err := tx.StoragePoolDriver(id) if err != nil { return errors.Wrapf(err, "Fetch storage pool driver for %q", pool) } if driver != "ceph" { isAvailable = true return nil } node, err := tx.NodeName() if err != nil { return errors.Wrapf(err, "Fetch node name") } containers, err := tx.ContainerListExpanded() if err != nil { return errors.Wrapf(err, "Fetch containers") } for _, container := range containers { for _, device := range container.Devices { if device["type"] != "disk" { continue } if device["pool"] != pool { continue } if device["source"] != volume { continue } if container.Node != node { // This ceph volume is already attached // to a container on a different node. return nil } } } isAvailable = true return nil }) if err != nil { return false, err } return isAvailable, nil }
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/page.go#L126-L133
func (f Font) Width(code int) float64 { first := f.FirstChar() last := f.LastChar() if code < first || last < code { return 0 } return f.V.Key("Widths").Index(code - first).Float64() }
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/concourse.go#L42-L44
func (s *ConcoursePipeline) AddRawJob(job atc.JobConfig) { s.Jobs = append(s.Jobs, job) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/copy/manifest.go#L45-L112
func (ic *imageCopier) determineManifestConversion(ctx context.Context, destSupportedManifestMIMETypes []string, forceManifestMIMEType string) (string, []string, error) { _, srcType, err := ic.src.Manifest(ctx) if err != nil { // This should have been cached?! return "", nil, errors.Wrap(err, "Error reading manifest") } normalizedSrcType := manifest.NormalizedMIMEType(srcType) if srcType != normalizedSrcType { logrus.Debugf("Source manifest MIME type %s, treating it as %s", srcType, normalizedSrcType) srcType = normalizedSrcType } if forceManifestMIMEType != "" { destSupportedManifestMIMETypes = []string{forceManifestMIMEType} } if len(destSupportedManifestMIMETypes) == 0 { return srcType, []string{}, nil // Anything goes; just use the original as is, do not try any conversions. } supportedByDest := map[string]struct{}{} for _, t := range destSupportedManifestMIMETypes { supportedByDest[t] = struct{}{} } // destSupportedManifestMIMETypes is a static guess; a particular registry may still only support a subset of the types. // So, build a list of types to try in order of decreasing preference. // FIXME? This treats manifest.DockerV2Schema1SignedMediaType and manifest.DockerV2Schema1MediaType as distinct, // although we are not really making any conversion, and it is very unlikely that a destination would support one but not the other. // In practice, schema1 is probably the lowest common denominator, so we would expect to try the first one of the MIME types // and never attempt the other one. prioritizedTypes := newOrderedSet() // First of all, prefer to keep the original manifest unmodified. if _, ok := supportedByDest[srcType]; ok { prioritizedTypes.append(srcType) } if !ic.canModifyManifest { // We could also drop the !ic.canModifyManifest check and have the caller // make the choice; it is already doing that to an extent, to improve error // messages. But it is nice to hide the “if !ic.canModifyManifest, do no conversion” // special case in here; the caller can then worry (or not) only about a good UI. logrus.Debugf("We can't modify the manifest, hoping for the best...") return srcType, []string{}, nil // Take our chances - FIXME? Or should we fail without trying? } // Then use our list of preferred types. for _, t := range preferredManifestMIMETypes { if _, ok := supportedByDest[t]; ok { prioritizedTypes.append(t) } } // Finally, try anything else the destination supports. for _, t := range destSupportedManifestMIMETypes { prioritizedTypes.append(t) } logrus.Debugf("Manifest has MIME type %s, ordered candidate list [%s]", srcType, strings.Join(prioritizedTypes.list, ", ")) if len(prioritizedTypes.list) == 0 { // Coverage: destSupportedManifestMIMETypes is not empty (or we would have exited in the “Anything goes” case above), so this should never happen. return "", nil, errors.New("Internal error: no candidate MIME types") } preferredType := prioritizedTypes.list[0] if preferredType != srcType { ic.manifestUpdates.ManifestMIMEType = preferredType } else { logrus.Debugf("... will first try using the original manifest unmodified") } return preferredType, prioritizedTypes.list[1:], nil }
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/harness/api_checkers.go#L100-L106
func CheckEverything() APICheckOption { return func(s *APICheckSuite) { s.opts.CheckBaggageValues = true s.opts.CheckExtract = true s.opts.CheckInject = true } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/log/easyjson.go#L352-L356
func (v *EventEntryAdded) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoLog3(&r, v) return r.Error() }
https://github.com/gopistolet/gospf/blob/a58dd1fcbf509d558a6809c54defbce6872c40c5/parser.go#L192-L254
func (d *Directive) getArguments() map[string]string { arguments := make(map[string]string) index := -1 ip := false term := d.term index = strings.Index(term, ":") if index != -1 { // "a" [ ":" domain-spec ] // "ip4" ":" ip4-network // ... term := term[index+1 : len(term)] spec := "" index = strings.Index(term, "/") if index == -1 { spec = term } else { spec = term[0:index] term = term[index+1 : len(term)] } if net.ParseIP(spec) != nil { arguments["ip"] = spec ip = true } else { arguments["domain"] = spec } } index = strings.Index(term, "/") if index == -1 { arguments["ip4-cidr"] = "" arguments["ip6-cidr"] = "" return arguments } if term[index:index+2] != "//" { term = term[index+1 : len(term)] } else { term = term[index:len(term)] } cidrs := strings.Split(term, "//") if ip { if !strings.Contains(arguments["ip"], ":") { arguments["ip4-cidr"] = cidrs[0] } else { arguments["ip6-cidr"] = cidrs[0] } } else { if len(cidrs) == 2 { // ip4-cidr + "/" + ip6-cidr arguments["ip4-cidr"] = cidrs[0] arguments["ip6-cidr"] = cidrs[1] } if len(cidrs) == 1 { // ip4 arguments["ip4-cidr"] = cidrs[0] arguments["ip6-cidr"] = "" } } return arguments }
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/token.go#L34-L47
func RandomAccessToken() (string, error) { buf, err := generateRandomBytes(128) if err != nil { return "", err } // A hash needs to be 64 bytes long to have 256-bit collision resistance. hash := make([]byte, 64) // Compute a 64-byte hash of buf and put it in h. sha3.ShakeSum256(hash, buf) hash2 := make([]byte, hex.EncodedLen(len(hash))) hex.Encode(hash2, hash) return string(hash2), nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/requiresig/requiresig.go#L146-L179
func handle(log *logrus.Entry, ghc githubClient, cp commentPruner, ie *github.IssueEvent, mentionRe *regexp.Regexp) error { // Ignore PRs, closed issues, and events that aren't new issues or sig label // changes. if !shouldReact(mentionRe, ie) { return nil } org := ie.Repo.Owner.Login repo := ie.Repo.Name number := ie.Issue.Number hasSigLabel := hasSigLabel(ie.Issue.Labels) hasNeedsSigLabel := github.HasLabel(labels.NeedsSig, ie.Issue.Labels) if hasSigLabel && hasNeedsSigLabel { if err := ghc.RemoveLabel(org, repo, number, labels.NeedsSig); err != nil { log.WithError(err).Errorf("Failed to remove %s label.", labels.NeedsSig) } botName, err := ghc.BotName() if err != nil { return fmt.Errorf("error getting bot name: %v", err) } cp.PruneComments(shouldPrune(log, botName)) } else if !hasSigLabel && !hasNeedsSigLabel { if err := ghc.AddLabel(org, repo, number, labels.NeedsSig); err != nil { log.WithError(err).Errorf("Failed to add %s label.", labels.NeedsSig) } msg := plugins.FormatResponse(ie.Issue.User.Login, needsSIGMessage, needsSIGDetails) if err := ghc.CreateComment(org, repo, number, msg); err != nil { log.WithError(err).Error("Failed to create comment.") } } return nil }