_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/copy/copy.go#L578-L585
func (c *copier) newProgressPool(ctx context.Context) (*mpb.Progress, func()) { ctx, cancel := context.WithCancel(ctx) pool := mpb.New(mpb.WithWidth(40), mpb.WithOutput(c.progressOutput), mpb.WithContext(ctx)) return pool, func() { cancel() pool.Wait() } }
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsPZ.go#L83-L87
func ReplaceF(old, new string, n int) func(string) string { return func(s string) string { return strings.Replace(s, old, new, n) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/browser.go#L212-L215
func (p GetHistogramsParams) WithQuery(query string) *GetHistogramsParams { p.Query = query return &p }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/guest.go#L53-L82
func (g *Guest) CopyFileToHost(guestpath, hostpath string) error { var jobHandle C.VixHandle = C.VIX_INVALID_HANDLE var err C.VixError = C.VIX_OK gpath := C.CString(guestpath) hpath := C.CString(hostpath) defer C.free(unsafe.Pointer(gpath)) defer C.free(unsafe.Pointer(hpath)) jobHandle = C.VixVM_CopyFileFromGuestToHost(g.handle, gpath, // src name hpath, // dest name 0, // options C.VIX_INVALID_HANDLE, // propertyListHandle nil, // callbackProc nil) // clientData defer C.Vix_ReleaseHandle(jobHandle) err = C.vix_job_wait(jobHandle) if C.VIX_OK != err { return &Error{ Operation: "guest.CopyFileToHost", Code: int(err & 0xFFFF), Text: C.GoString(C.Vix_GetErrorText(err, nil)), } } return nil }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L182-L189
func (r *InclusiveRange) Contains(value int) bool { // If we attempt to find the closest value, given // the start of the range and the step, we can check // if it is still the same number. If it hasn't changed, // then it is in the range. closest := r.closestInRange(value, r.start, r.End(), r.step) return closest == value }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3806-L3809
func (e OperationResultCode) String() string { name, _ := operationResultCodeMap[int32(e)] return name }
https://github.com/marcuswestin/go-errs/blob/b09b17aacd5a8213690bc30f9ccfe7400be7b380/errs.go#L162-L170
func (e *err) LogString() string { return concatArgs("Error", "| Time:", e.time, "| StdError:", e.wrappedErrStr(), "| Info:["+concatArgs(e.info)+"]", "| PublicMsg:", e.publicMsg, "| Stack:", string(e.stack), ) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L476-L480
func (v StyleSheetHeader) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss3(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L2889-L2893
func (v GetSearchResultsReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom32(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/tarfile/src.go#L414-L463
func (s *Source) GetBlob(ctx context.Context, info types.BlobInfo, cache types.BlobInfoCache) (io.ReadCloser, int64, error) { if err := s.ensureCachedDataIsPresent(); err != nil { return nil, 0, err } if info.Digest == s.configDigest { // FIXME? Implement a more general algorithm matching instead of assuming sha256. return ioutil.NopCloser(bytes.NewReader(s.configBytes)), int64(len(s.configBytes)), nil } if li, ok := s.knownLayers[info.Digest]; ok { // diffID is a digest of the uncompressed tarball, underlyingStream, err := s.openTarComponent(li.path) if err != nil { return nil, 0, err } closeUnderlyingStream := true defer func() { if closeUnderlyingStream { underlyingStream.Close() } }() // In order to handle the fact that digests != diffIDs (and thus that a // caller which is trying to verify the blob will run into problems), // we need to decompress blobs. This is a bit ugly, but it's a // consequence of making everything addressable by their DiffID rather // than by their digest... // // In particular, because the v2s2 manifest being generated uses // DiffIDs, any caller of GetBlob is going to be asking for DiffIDs of // layers not their _actual_ digest. The result is that copy/... will // be verifing a "digest" which is not the actual layer's digest (but // is instead the DiffID). uncompressedStream, _, err := compression.AutoDecompress(underlyingStream) if err != nil { return nil, 0, errors.Wrapf(err, "Error auto-decompressing blob %s", info.Digest) } newStream := uncompressedReadCloser{ Reader: uncompressedStream, underlyingCloser: underlyingStream.Close, uncompressedCloser: uncompressedStream.Close, } closeUnderlyingStream = false return newStream, li.size, nil } return nil, 0, errors.Errorf("Unknown blob %s", info.Digest) }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dsvg/gc.go#L228-L245
func (gc *GraphicContext) drawPaths(drawType drawType, paths ...*draw2d.Path) { // create elements svgPath := Path{} group := gc.newGroup(drawType) // set attrs to path element paths = append(paths, gc.Current.Path) svgPathsDesc := make([]string, len(paths)) // multiple pathes has to be joined to single svg path description // because fill-rule wont work for whole group as excepted for i, path := range paths { svgPathsDesc[i] = toSvgPathDesc(path) } svgPath.Desc = strings.Join(svgPathsDesc, " ") // attach to group group.Paths = []*Path{&svgPath} }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv2/command/set_dir_command.go#L23-L36
func NewSetDirCommand() cli.Command { return cli.Command{ Name: "setdir", Usage: "create a new directory or update an existing directory TTL", ArgsUsage: "<key>", Flags: []cli.Flag{ cli.IntFlag{Name: "ttl", Value: 0, Usage: "key time-to-live in seconds"}, }, Action: func(c *cli.Context) error { mkdirCommandFunc(c, mustNewKeyAPI(c), client.PrevIgnore) return nil }, } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/v2_server.go#L141-L160
func (r *RequestV2) Handle(ctx context.Context, v2api RequestV2Handler) (Response, error) { if r.Method == "GET" && r.Quorum { r.Method = "QGET" } switch r.Method { case "POST": return v2api.Post(ctx, r) case "PUT": return v2api.Put(ctx, r) case "DELETE": return v2api.Delete(ctx, r) case "QGET": return v2api.QGet(ctx, r) case "GET": return v2api.Get(ctx, r) case "HEAD": return v2api.Head(ctx, r) } return Response{}, ErrUnknownMethod }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/impl.go#L35-L46
func toImpl(err Error) *impl { if i, ok := err.(*impl); ok { return i } return &impl{ message: err.Error(), code: err.Code(), typ: err.Type(), attributes: err.Attributes(), } }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gexec/session.go#L226-L233
func KillAndWait(timeout ...interface{}) { trackedSessionsMutex.Lock() defer trackedSessionsMutex.Unlock() for _, session := range trackedSessions { session.Kill().Wait(timeout...) } trackedSessions = []*Session{} }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/membership.go#L691-L712
func Purge(cluster *db.Cluster, name string) error { logger.Debugf("Remove node %s from the database", name) return cluster.Transaction(func(tx *db.ClusterTx) error { // Get the node (if it doesn't exists an error is returned). node, err := tx.NodeByName(name) if err != nil { return errors.Wrapf(err, "failed to get node %s", name) } err = tx.NodeClear(node.ID) if err != nil { return errors.Wrapf(err, "failed to clear node %s", name) } err = tx.NodeRemove(node.ID) if err != nil { return errors.Wrapf(err, "failed to remove node %s", name) } return nil }) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L142-L145
func (p DescribeNodeParams) WithBackendNodeID(backendNodeID cdp.BackendNodeID) *DescribeNodeParams { p.BackendNodeID = backendNodeID return &p }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/images.go#L194-L224
func (c *Cluster) ImageExists(project string, fingerprint string) (bool, error) { err := c.Transaction(func(tx *ClusterTx) error { enabled, err := tx.ProjectHasImages(project) if err != nil { return errors.Wrap(err, "Check if project has images") } if !enabled { project = "default" } return nil }) if err != nil { return false, err } var exists bool query := ` SELECT COUNT(*) > 0 FROM images JOIN projects ON projects.id = images.project_id WHERE projects.name = ? AND fingerprint=? ` inargs := []interface{}{project, fingerprint} outargs := []interface{}{&exists} err = dbQueryRowScan(c.db, query, inargs, outargs) if err == sql.ErrNoRows { return exists, ErrNoSuchObject } return exists, err }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L858-L860
func (c *putFileClient) PutFileWriter(repoName, commitID, path string) (io.WriteCloser, error) { return c.newPutFileWriteCloser(repoName, commitID, path, pfs.Delimiter_NONE, 0, 0, 0, nil) }
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/objutil/limits.go#L90-L95
func CheckUint64Bounds(v uint64, max uint64, t reflect.Type) (err error) { if v > max { err = fmt.Errorf("objconv: %d overflows the maximum value of %d for %s", v, max, t) } return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L7107-L7111
func (v *CaptureSnapshotParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage78(&r, v) return r.Error() }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/example/models.go#L36-L44
func EnsureIndexes(store *coal.Store) error { // ensure model indexes err := indexer.Ensure(store) if err != nil { return err } return nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/deploy/assets/assets.go#L949-L1108
func EtcdStatefulSet(opts *AssetOpts, backend backend, diskSpace int) interface{} { mem := resource.MustParse(opts.EtcdMemRequest) cpu := resource.MustParse(opts.EtcdCPURequest) initialCluster := make([]string, 0, opts.EtcdNodes) for i := 0; i < opts.EtcdNodes; i++ { url := fmt.Sprintf("http://etcd-%d.etcd-headless.${NAMESPACE}.svc.cluster.local:2380", i) initialCluster = append(initialCluster, fmt.Sprintf("etcd-%d=%s", i, url)) } // Because we need to refer to some environment variables set the by the // k8s downward API, we define the command for running etcd here, and then // actually run it below via '/bin/sh -c ${CMD}' etcdCmd := append(etcdCmd, "--listen-peer-urls=http://0.0.0.0:2380", "--initial-cluster-token=pach-cluster", // unique ID "--initial-advertise-peer-urls=http://${ETCD_NAME}.etcd-headless.${NAMESPACE}.svc.cluster.local:2380", "--initial-cluster="+strings.Join(initialCluster, ","), ) for i, str := range etcdCmd { etcdCmd[i] = fmt.Sprintf("\"%s\"", str) // quote all arguments, for shell } var pvcTemplates []interface{} switch backend { case googleBackend, amazonBackend: storageClassName := opts.EtcdStorageClassName if storageClassName == "" { storageClassName = defaultEtcdStorageClassName } pvcTemplates = []interface{}{ map[string]interface{}{ "metadata": map[string]interface{}{ "name": etcdVolumeClaimName, "labels": labels(etcdName), "annotations": map[string]string{ "volume.beta.kubernetes.io/storage-class": storageClassName, }, "namespace": opts.Namespace, }, "spec": map[string]interface{}{ "resources": map[string]interface{}{ "requests": map[string]interface{}{ "storage": resource.MustParse(fmt.Sprintf("%vGi", diskSpace)), }, }, "accessModes": []string{"ReadWriteOnce"}, }, }, } default: pvcTemplates = []interface{}{ map[string]interface{}{ "metadata": map[string]interface{}{ "name": etcdVolumeClaimName, "labels": labels(etcdName), "namespace": opts.Namespace, }, "spec": map[string]interface{}{ "resources": map[string]interface{}{ "requests": map[string]interface{}{ "storage": resource.MustParse(fmt.Sprintf("%vGi", diskSpace)), }, }, "accessModes": []string{"ReadWriteOnce"}, }, }, } } var imagePullSecrets []map[string]string if opts.ImagePullSecret != "" { imagePullSecrets = append(imagePullSecrets, map[string]string{"name": opts.ImagePullSecret}) } // As of March 17, 2017, the Kubernetes client does not include structs for // Stateful Set, so we generate the kubernetes manifest using raw json. // TODO(msteffen): we're now upgrading our kubernetes client, so we should be // abe to rewrite this spec using k8s client structs image := etcdImage if opts.Registry != "" { image = AddRegistry(opts.Registry, etcdImage) } return map[string]interface{}{ "apiVersion": "apps/v1beta1", "kind": "StatefulSet", "metadata": map[string]interface{}{ "name": etcdName, "labels": labels(etcdName), "namespace": opts.Namespace, }, "spec": map[string]interface{}{ // Effectively configures a RC "serviceName": etcdHeadlessServiceName, "replicas": int(opts.EtcdNodes), "selector": map[string]interface{}{ "matchLabels": labels(etcdName), }, // pod template "template": map[string]interface{}{ "metadata": map[string]interface{}{ "name": etcdName, "labels": labels(etcdName), "namespace": opts.Namespace, }, "spec": map[string]interface{}{ "imagePullSecrets": imagePullSecrets, "containers": []interface{}{ map[string]interface{}{ "name": etcdName, "image": image, "command": []string{"/bin/sh", "-c"}, "args": []string{strings.Join(etcdCmd, " ")}, // Use the downward API to pass the pod name to etcd. This sets // the etcd-internal name of each node to its pod name. "env": []map[string]interface{}{{ "name": "ETCD_NAME", "valueFrom": map[string]interface{}{ "fieldRef": map[string]interface{}{ "apiVersion": "v1", "fieldPath": "metadata.name", }, }, }, { "name": "NAMESPACE", "valueFrom": map[string]interface{}{ "fieldRef": map[string]interface{}{ "apiVersion": "v1", "fieldPath": "metadata.namespace", }, }, }}, "ports": []interface{}{ map[string]interface{}{ "containerPort": 2379, "name": "client-port", }, map[string]interface{}{ "containerPort": 2380, "name": "peer-port", }, }, "volumeMounts": []interface{}{ map[string]interface{}{ "name": etcdVolumeClaimName, "mountPath": "/var/data/etcd", }, }, "imagePullPolicy": "IfNotPresent", "resources": map[string]interface{}{ "requests": map[string]interface{}{ string(v1.ResourceCPU): cpu.String(), string(v1.ResourceMemory): mem.String(), }, }, }, }, }, }, "volumeClaimTemplates": pvcTemplates, }, } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cachestorage/easyjson.go#L1183-L1187
func (v CachedResponse) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoCachestorage10(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L3990-L3994
func (v *GetAppManifestParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage43(&r, v) return r.Error() }
https://github.com/kr/s3/blob/c070c8f9a8f0032d48f0d2a77d4e382788bd8a1d/s3util/uploader.go#L77-L115
func newUploader(url string, h http.Header, c *Config) (u *uploader, err error) { u = new(uploader) u.s3 = *c.Service u.url = url u.keys = *c.Keys u.client = c.Client if u.client == nil { u.client = http.DefaultClient } u.bufsz = minPartSize r, err := http.NewRequest("POST", url+"?uploads", nil) if err != nil { return nil, err } r.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat)) for k := range h { for _, v := range h[k] { r.Header.Add(k, v) } } u.s3.Sign(r, u.keys) resp, err := u.client.Do(r) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != 200 { return nil, newRespError(resp) } err = xml.NewDecoder(resp.Body).Decode(u) if err != nil { return nil, err } u.ch = make(chan *part) for i := 0; i < concurrency; i++ { go u.worker() } return u, nil }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/auth.go#L420-L460
func teamList(w http.ResponseWriter, r *http.Request, t auth.Token) error { permsForTeam := permission.PermissionRegistry.PermissionsWithContextType(permTypes.CtxTeam) teams, err := servicemanager.Team.List() if err != nil { return err } teamsMap := map[string]authTypes.Team{} permsMap := map[string][]string{} perms, err := t.Permissions() if err != nil { return err } for _, team := range teams { teamsMap[team.Name] = team teamCtx := permission.Context(permTypes.CtxTeam, team.Name) var parent *permission.PermissionScheme for _, p := range permsForTeam { if parent != nil && parent.IsParent(p) { continue } if permission.CheckFromPermList(perms, p, teamCtx) { parent = p permsMap[team.Name] = append(permsMap[team.Name], p.FullName()) } } } if len(permsMap) == 0 { w.WriteHeader(http.StatusNoContent) return nil } var result []map[string]interface{} for name, permissions := range permsMap { result = append(result, map[string]interface{}{ "name": name, "tags": teamsMap[name].Tags, "permissions": permissions, }) } w.Header().Set("Content-Type", "application/json") return json.NewEncoder(w).Encode(result) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_networks.go#L104-L116
func (r *ProtocolLXD) CreateNetwork(network api.NetworksPost) error { if !r.HasExtension("network") { return fmt.Errorf("The server is missing the required \"network\" API extension") } // Send the request _, _, err := r.query("POST", "/networks", network, "") if err != nil { return err } return nil }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/cmd/utils.go#L36-L38
func (md *markdown) Printf(format string, args ...interface{}) { fmt.Fprintf(md, format, args...) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L4687-L4691
func (v *CompileScriptReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime44(&r, v) return r.Error() }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/rafthttp/transport.go#L239-L251
func (t *Transport) CutPeer(id types.ID) { t.mu.RLock() p, pok := t.peers[id] g, gok := t.remotes[id] t.mu.RUnlock() if pok { p.(Pausable).Pause() } if gok { g.Pause() } }
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/cmpopts/ignore.go#L156-L178
func IgnoreSliceElements(discardFunc interface{}) cmp.Option { vf := reflect.ValueOf(discardFunc) if !function.IsType(vf.Type(), function.ValuePredicate) || vf.IsNil() { panic(fmt.Sprintf("invalid discard function: %T", discardFunc)) } return cmp.FilterPath(func(p cmp.Path) bool { si, ok := p.Index(-1).(cmp.SliceIndex) if !ok { return false } if !si.Type().AssignableTo(vf.Type().In(0)) { return false } vx, vy := si.Values() if vx.IsValid() && vf.Call([]reflect.Value{vx})[0].Bool() { return true } if vy.IsValid() && vf.Call([]reflect.Value{vy})[0].Bool() { return true } return false }, cmp.Ignore()) }
https://github.com/alecthomas/mph/blob/cf7b0cd2d9579868ec2a49493fd62b2e28bcb336/chd.go#L70-L96
func Mmap(b []byte) (*CHD, error) { c := &CHD{} bi := &sliceReader{b: b} // Read vector of hash functions. rl := bi.ReadInt() c.r = bi.ReadUint64Array(rl) // Read hash function indices. il := bi.ReadInt() c.indices = bi.ReadUint16Array(il) el := bi.ReadInt() c.keys = make([][]byte, el) c.values = make([][]byte, el) for i := uint64(0); i < el; i++ { kl := bi.ReadInt() vl := bi.ReadInt() c.keys[i] = bi.Read(kl) c.values[i] = bi.Read(vl) } return c, nil }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/authenticator.go#L55-L68
func NewAuthenticator(store *coal.Store, policy *Policy) *Authenticator { // initialize token coal.Init(policy.Token) // initialize clients for _, model := range policy.Clients { coal.Init(model) } return &Authenticator{ store: store, policy: policy, } }
https://github.com/achiku/soapc/blob/cfbdfe6e4caffe57a9cba89996e8b1cedb512be0/client.go#L143-L219
func (s *Client) Call(soapAction string, request, response, header interface{}) error { var envelope Envelope if s.header != nil { envelope = Envelope{ Header: &Header{ Content: s.header, }, Body: Body{ Content: request, }, } } else { envelope = Envelope{ Body: Body{ Content: request, }, } } buffer := new(bytes.Buffer) encoder := xml.NewEncoder(buffer) encoder.Indent(" ", " ") if err := encoder.Encode(envelope); err != nil { return errors.Wrap(err, "failed to encode envelope") } if err := encoder.Flush(); err != nil { return errors.Wrap(err, "failed to flush encoder") } req, err := http.NewRequest("POST", s.url, buffer) if err != nil { return errors.Wrap(err, "failed to create POST request") } req.Header.Add("Content-Type", "text/xml; charset=\"utf-8\"") req.Header.Set("SOAPAction", soapAction) req.Header.Set("User-Agent", s.userAgent) req.Close = true tr := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: s.tls, }, Dial: dialTimeout, } client := &http.Client{Transport: tr} res, err := client.Do(req) if err != nil { return errors.Wrap(err, "failed to send SOAP request") } defer res.Body.Close() if res.StatusCode != http.StatusOK { soapFault, err := ioutil.ReadAll(res.Body) if err != nil { return errors.Wrap(err, "failed to read SOAP fault response body") } msg := fmt.Sprintf("HTTP Status Code: %d, SOAP Fault: \n%s", res.StatusCode, string(soapFault)) return errors.New(msg) } rawbody, err := ioutil.ReadAll(res.Body) if err != nil { return errors.Wrap(err, "failed to read SOAP body") } if len(rawbody) == 0 { return nil } respEnvelope := Envelope{} respEnvelope.Body = Body{Content: response} if header != nil { respEnvelope.Header = &Header{Content: header} } if err = xml.Unmarshal(rawbody, &respEnvelope); err != nil { return errors.Wrap(err, "failed to unmarshal response SOAP Envelope") } return nil }
https://github.com/qor/action_bar/blob/136e5e2c5b8c50976dc39edddf523fcaab0a73b8/controller.go#L27-L29
func (controller) InlineEdit(context *admin.Context) { context.Writer.Write([]byte(context.Render("action_bar/inline_edit"))) }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/thrift/thrift-gen/wrap.go#L239-L244
func (m *Method) ReturnWith(respName string, errName string) string { if !m.HasReturn() { return errName } return fmt.Sprintf("%v, %v", respName, errName) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/backgroundservice/easyjson.go#L225-L229
func (v SetRecordingParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoBackgroundservice2(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/fakes/fake.go#L269-L274
func (s *MockClientDoer) Do(rq *http.Request) (rs *http.Response, e error) { s.Req = rq rs = s.Res e = s.Err return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cdp/types.go#L318-L329
func (n *Node) AttributeValue(name string) string { n.RLock() defer n.RUnlock() for i := 0; i < len(n.Attributes); i += 2 { if n.Attributes[i] == name { return n.Attributes[i+1] } } return "" }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/plugin/vault/pachyderm/helpers.go#L47-L62
func getConfig(ctx context.Context, s logical.Storage) (*config, error) { entry, err := s.Get(ctx, "config") if err != nil { return nil, fmt.Errorf("%v: failed to get config from storage", err) } if entry == nil || len(entry.Value) == 0 { return nil, errors.New("no configuration in storage") } var result config if err := entry.DecodeJSON(&result); err != nil { return nil, fmt.Errorf("%v: failed to decode configuration", err) } return &result, nil }
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/log/field.go#L135-L141
func Object(key string, obj interface{}) Field { return Field{ key: key, fieldType: objectType, interfaceVal: obj, } }
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/base.go#L258-L281
func (b *Base) ShutdownLoggers() error { // Before shutting down we should flush all the messsages b.Flush() for _, logger := range b.loggers { err := logger.ShutdownLogger() if err != nil { return err } } if b.queue != nil { b.queue.stopWorker() b.queue = nil } if b.errorChan != nil { close(b.errorChan) b.errorChan = nil } b.isInitialized = false return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/mapping.go#L58-L66
func (m *Mapping) FieldByName(name string) *Field { for _, field := range m.Fields { if field.Name == name { return field } } return nil }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/tracing.go#L139-L163
func (c *Connection) startOutboundSpan(ctx context.Context, serviceName, methodName string, call *OutboundCall, startTime time.Time) opentracing.Span { var parent opentracing.SpanContext // ok to be nil if s := opentracing.SpanFromContext(ctx); s != nil { parent = s.Context() } span := c.Tracer().StartSpan( methodName, opentracing.ChildOf(parent), opentracing.StartTime(startTime), ) if isTracingDisabled(ctx) { ext.SamplingPriority.Set(span, 0) } ext.SpanKindRPCClient.Set(span) ext.PeerService.Set(span, serviceName) c.setPeerHostPort(span) span.SetTag("as", call.callReq.Headers[ArgScheme]) var injectable injectableSpan if err := injectable.initFromOpenTracing(span); err == nil { call.callReq.Tracing = Span(injectable) } else { call.callReq.Tracing.initRandom() } return span }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/common/mason_config.go#L62-L68
func ItemToResourcesConfig(i Item) (ResourcesConfig, error) { conf, ok := i.(ResourcesConfig) if !ok { return ResourcesConfig{}, fmt.Errorf("cannot construct Resource from received object %v", i) } return conf, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.go#L340-L352
func (c *Cluster) ProfileCleanupLeftover() error { stmt := ` DELETE FROM profiles_config WHERE profile_id NOT IN (SELECT id FROM profiles); DELETE FROM profiles_devices WHERE profile_id NOT IN (SELECT id FROM profiles); DELETE FROM profiles_devices_config WHERE profile_device_id NOT IN (SELECT id FROM profiles_devices); ` err := exec(c.db, stmt) if err != nil { return err } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L7165-L7169
func (v EventEventSourceMessageReceived) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork55(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/raft.go#L903-L928
func (r *Raft) processLogs(index uint64, future *logFuture) { // Reject logs we've applied already lastApplied := r.getLastApplied() if index <= lastApplied { r.logger.Warn(fmt.Sprintf("Skipping application of old log: %d", index)) return } // Apply all the preceding logs for idx := r.getLastApplied() + 1; idx <= index; idx++ { // Get the log, either from the future or from our log store if future != nil && future.log.Index == idx { r.processLog(&future.log, future) } else { l := new(Log) if err := r.logs.GetLog(idx, l); err != nil { r.logger.Error(fmt.Sprintf("Failed to get log at %d: %v", idx, err)) panic(err) } r.processLog(l, nil) } // Update the lastApplied index and term r.setLastApplied(idx) } }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/path.go#L70-L74
func (p *Path) MoveTo(x, y float64) { p.appendToPath(MoveToCmp, x, y) p.x = x p.y = y }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L13902-L13909
func (r *Task) Locator(api *API) *TaskLocator { for _, l := range r.Links { if l["rel"] == "self" { return api.TaskLocator(l["href"]) } } return nil }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/remote_api/client.go#L71-L76
func (c *Client) NewContext(parent context.Context) context.Context { ctx := internal.WithCallOverride(parent, c.call) ctx = internal.WithLogOverride(ctx, c.logf) ctx = internal.WithAppIDOverride(ctx, c.appID) return ctx }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/admin.go#L141-L154
func (c APIClient) RestoreFrom(objects bool, otherC *APIClient) (retErr error) { restoreClient, err := c.AdminAPIClient.Restore(c.Ctx()) if err != nil { return grpcutil.ScrubGRPC(err) } defer func() { if _, err := restoreClient.CloseAndRecv(); err != nil && retErr == nil { retErr = grpcutil.ScrubGRPC(err) } }() return otherC.Extract(objects, func(op *admin.Op) error { return restoreClient.Send(&admin.RestoreRequest{Op: op}) }) }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/expr.go#L225-L303
func extractPlatformStringsExprs(expr bzl.Expr) (platformStringsExprs, error) { var ps platformStringsExprs if expr == nil { return ps, nil } // Break the expression into a sequence of expressions combined with +. var parts []bzl.Expr for { binop, ok := expr.(*bzl.BinaryExpr) if !ok { parts = append(parts, expr) break } parts = append(parts, binop.Y) expr = binop.X } // Process each part. They may be in any order. for _, part := range parts { switch part := part.(type) { case *bzl.ListExpr: if ps.generic != nil { return platformStringsExprs{}, fmt.Errorf("expression could not be matched: multiple list expressions") } ps.generic = part case *bzl.CallExpr: x, ok := part.X.(*bzl.Ident) if !ok || x.Name != "select" || len(part.List) != 1 { return platformStringsExprs{}, fmt.Errorf("expression could not be matched: callee other than select or wrong number of args") } arg, ok := part.List[0].(*bzl.DictExpr) if !ok { return platformStringsExprs{}, fmt.Errorf("expression could not be matched: select argument not dict") } var dict **bzl.DictExpr for _, item := range arg.List { kv := item.(*bzl.KeyValueExpr) // parser guarantees this k, ok := kv.Key.(*bzl.StringExpr) if !ok { return platformStringsExprs{}, fmt.Errorf("expression could not be matched: dict keys are not all strings") } if k.Value == "//conditions:default" { continue } key, err := label.Parse(k.Value) if err != nil { return platformStringsExprs{}, fmt.Errorf("expression could not be matched: dict key is not label: %q", k.Value) } if KnownOSSet[key.Name] { dict = &ps.os break } if KnownArchSet[key.Name] { dict = &ps.arch break } osArch := strings.Split(key.Name, "_") if len(osArch) != 2 || !KnownOSSet[osArch[0]] || !KnownArchSet[osArch[1]] { return platformStringsExprs{}, fmt.Errorf("expression could not be matched: dict key contains unknown platform: %q", k.Value) } dict = &ps.platform break } if dict == nil { // We could not identify the dict because it's empty or only contains // //conditions:default. We'll call it the platform dict to avoid // dropping it. dict = &ps.platform } if *dict != nil { return platformStringsExprs{}, fmt.Errorf("expression could not be matched: multiple selects that are either os-specific, arch-specific, or platform-specific") } *dict = arg } } return ps, nil }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/datastore.go#L141-L158
func referenceValueToKey(r *pb.PropertyValue_ReferenceValue) (k *Key, err error) { appID := r.GetApp() namespace := r.GetNameSpace() for _, e := range r.Pathelement { k = &Key{ kind: e.GetType(), stringID: e.GetName(), intID: e.GetId(), parent: k, appID: appID, namespace: namespace, } if !k.valid() { return nil, ErrInvalidKey } } return }
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/read.go#L643-L649
func (v Value) Name() string { x, ok := v.data.(name) if !ok { return "" } return string(x) }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/highgui.go#L450-L455
func NewFileCapture(filename string) *Capture { filename_c := C.CString(filename) defer C.free(unsafe.Pointer(filename_c)) cap := C.cvCreateFileCapture(filename_c) return (*Capture)(cap) }
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/codec.go#L32-L36
func NewPrefixBytes(prefixBytes []byte) PrefixBytes { pb := PrefixBytes{} copy(pb[:], prefixBytes) return pb }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/mkbuild-cluster/main.go#L157-L164
func getAccount() (string, error) { args, cmd := command("gcloud", "config", "get-value", "core/account") b, err := cmd.Output() if err != nil { return "", fmt.Errorf("%s: %v", strings.Join(args, " "), err) } return strings.TrimSpace(string(b)), nil }
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/usermanagment.go#L238-L243
func (c *Client) DeleteShare(groupid string, resourceid string) (*http.Header, error) { url := umGroupSharePath(groupid, resourceid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty) ret := &http.Header{} err := c.client.Delete(url, ret, http.StatusAccepted) return ret, err }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L186-L188
func (img *IplImage) Set2D(x, y int, value Scalar) { C.cvSet2D(unsafe.Pointer(img), C.int(y), C.int(x), (C.CvScalar)(value)) }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gexec/session.go#L64-L100
func Start(command *exec.Cmd, outWriter io.Writer, errWriter io.Writer) (*Session, error) { exited := make(chan struct{}) session := &Session{ Command: command, Out: gbytes.NewBuffer(), Err: gbytes.NewBuffer(), Exited: exited, lock: &sync.Mutex{}, exitCode: -1, } var commandOut, commandErr io.Writer commandOut, commandErr = session.Out, session.Err if outWriter != nil { commandOut = io.MultiWriter(commandOut, outWriter) } if errWriter != nil { commandErr = io.MultiWriter(commandErr, errWriter) } command.Stdout = commandOut command.Stderr = commandErr err := command.Start() if err == nil { go session.monitorForExit(exited) trackedSessionsMutex.Lock() defer trackedSessionsMutex.Unlock() trackedSessions = append(trackedSessions, session) } return session, err }
https://github.com/codegangsta/martini-contrib/blob/8ce6181c2609699e4c7cd30994b76a850a9cdadc/sessionauth/login.go#L83-L86
func Logout(s sessions.Session, user User) { user.Logout() s.Delete(SessionKey) }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/message.go#L76-L79
func (p *Message) WithMetadata(metadata MapMatcher) *Message { p.Metadata = metadata return p }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pps.go#L442-L447
func (l *LogsIter) Err() error { if l.err == io.EOF { return nil } return grpcutil.ScrubGRPC(l.err) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L324-L327
func (p EmulateTouchFromMouseEventParams) WithTimestamp(timestamp *TimeSinceEpoch) *EmulateTouchFromMouseEventParams { p.Timestamp = timestamp return &p }
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/rand/cryptorand.go#L34-L40
func GenerateRandomBytes(length int) ([]byte, error) { b := make([]byte, length) _, err := rand.Read(b) return b, err }
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/usermanagment.go#L264-L269
func (c *Client) DeleteUserFromGroup(groupid string, userid string) (*http.Header, error) { url := umGroupUsersPath(groupid, userid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty) ret := &http.Header{} err := c.client.Delete(url, ret, http.StatusAccepted) return ret, err }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/git/localgit/localgit.go#L145-L148
func (lg *LocalGit) Checkout(org, repo, commitlike string) error { rdir := filepath.Join(lg.Dir, org, repo) return runCmd(lg.Git, rdir, "checkout", commitlike) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L2248-L2252
func (v *PrintToPDFParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage23(&r, v) return r.Error() }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/op.go#L264-L290
func OpPut(key, val string, opts ...OpOption) Op { ret := Op{t: tPut, key: []byte(key), val: []byte(val)} ret.applyOpts(opts) switch { case ret.end != nil: panic("unexpected range in put") case ret.limit != 0: panic("unexpected limit in put") case ret.rev != 0: panic("unexpected revision in put") case ret.sort != nil: panic("unexpected sort in put") case ret.serializable: panic("unexpected serializable in put") case ret.countOnly: panic("unexpected countOnly in put") case ret.minModRev != 0, ret.maxModRev != 0: panic("unexpected mod revision filter in put") case ret.minCreateRev != 0, ret.maxCreateRev != 0: panic("unexpected create revision filter in put") case ret.filterDelete, ret.filterPut: panic("unexpected filter in put") case ret.createdNotify: panic("unexpected createdNotify in put") } return ret }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/allow_trust.go#L30-L47
func (b *AllowTrustBuilder) Mutate(muts ...interface{}) { for _, m := range muts { var err error switch mut := m.(type) { case AllowTrustMutator: err = mut.MutateAllowTrust(&b.AT) case OperationMutator: err = mut.MutateOperation(&b.O) default: err = errors.New("Mutator type not allowed") } if err != nil { b.Err = err return } } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L7177-L7181
func (v *EventEventSourceMessageReceived) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork55(&r, v) return r.Error() }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/routes/get_apps_app_routes_parameters.go#L88-L91
func (o *GetAppsAppRoutesParams) WithContext(ctx context.Context) *GetAppsAppRoutesParams { o.SetContext(ctx) return o }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selectable.go#L156-L158
func (s *selectable) AllByLink(text string) *MultiSelection { return newMultiSelection(s.session, s.selectors.Append(target.Link, text)) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/naming/grpc.go#L71-L109
func (gw *gRPCWatcher) Next() ([]*naming.Update, error) { if gw.wch == nil { // first Next() returns all addresses return gw.firstNext() } if gw.err != nil { return nil, gw.err } // process new events on target/* wr, ok := <-gw.wch if !ok { gw.err = status.Error(codes.Unavailable, ErrWatcherClosed.Error()) return nil, gw.err } if gw.err = wr.Err(); gw.err != nil { return nil, gw.err } updates := make([]*naming.Update, 0, len(wr.Events)) for _, e := range wr.Events { var jupdate naming.Update var err error switch e.Type { case etcd.EventTypePut: err = json.Unmarshal(e.Kv.Value, &jupdate) jupdate.Op = naming.Add case etcd.EventTypeDelete: err = json.Unmarshal(e.PrevKv.Value, &jupdate) jupdate.Op = naming.Delete default: continue } if err == nil { updates = append(updates, &jupdate) } } return updates, nil }
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L321-L323
func (l *Logger) Errorf(format string, args ...interface{}) { l.Output(2, LevelError, fmt.Sprintf(format, args...)) }
https://github.com/blacklabeldata/namedtuple/blob/c341f1db44f30b8164294aa8605ede42be604aba/strings.go#L10-L87
func (b *TupleBuilder) PutString(field string, value string) (wrote int, err error) { // field type should be if err = b.typeCheck(field, StringField); err != nil { return 0, err } size := len(value) if size < math.MaxUint8 { if b.available() < size+2 { return 0, xbinary.ErrOutOfRange } // write length xbinary.LittleEndian.PutString(b.buffer, b.pos+2, value) // write type code b.buffer[b.pos] = byte(String8Code.OpCode) // write length b.buffer[b.pos+1] = byte(size) wrote += size + 2 } else if size < math.MaxUint16 { if b.available() < size+3 { return 0, xbinary.ErrOutOfRange } // write length xbinary.LittleEndian.PutUint16(b.buffer, b.pos+1, uint16(size)) // write value xbinary.LittleEndian.PutString(b.buffer, b.pos+3, value) // write type code b.buffer[b.pos] = byte(String16Code.OpCode) wrote += 3 + size } else if size < math.MaxUint32 { if b.available() < size+5 { return 0, xbinary.ErrOutOfRange } // write length xbinary.LittleEndian.PutUint32(b.buffer, b.pos+1, uint32(size)) // write value xbinary.LittleEndian.PutString(b.buffer, b.pos+5, value) // write type code b.buffer[b.pos] = byte(String32Code.OpCode) wrote += 5 + size } else { if b.available() < size+9 { return 0, xbinary.ErrOutOfRange } // write length xbinary.LittleEndian.PutUint64(b.buffer, b.pos+1, uint64(size)) // write value xbinary.LittleEndian.PutString(b.buffer, b.pos+9, value) // write type code b.buffer[b.pos] = byte(String64Code.OpCode) wrote += 9 + size } b.offsets[field] = b.pos b.pos += wrote return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/browser.go#L49-L51
func (p *GrantPermissionsParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandGrantPermissions, p, nil) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L5832-L5836
func (v EventFrameStartedLoading) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage61(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.mapper.go#L691-L707
func (c *ClusterTx) ProfileDelete(project string, name string) error { stmt := c.stmt(profileDelete) result, err := stmt.Exec(project, name) if err != nil { return errors.Wrap(err, "Delete profile") } n, err := result.RowsAffected() if err != nil { return errors.Wrap(err, "Fetch affected rows") } if n != 1 { return fmt.Errorf("Query deleted %d rows instead of 1", n) } return nil }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/highgui.go#L265-L285
func (win *Window) SetMouseCallback(on_mouse MouseFunc, param ...interface{}) { switch f := on_mouse.(type) { case MouseFuncA: win.mouseHandle = MouseFunc(f) case MouseFuncB: win.mouseHandle = MouseFunc(f) case func(event, x, y, flags int): win.mouseHandle = MouseFunc(f) case func(event, x, y, flags int, param ...interface{}): win.mouseHandle = MouseFunc(f) default: panic("unknow func type!") } if len(param) > 0 { win.param = param } else { win.param = nil } }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/badger/cmd/bank.go#L213-L245
func findFirstInvalidTxn(db *badger.DB, lowTs, highTs uint64) uint64 { checkAt := func(ts uint64) error { txn := db.NewTransactionAt(ts, false) _, err := seekTotal(txn) txn.Discard() return err } if highTs-lowTs < 1 { log.Printf("Checking at lowTs: %d\n", lowTs) err := checkAt(lowTs) if err == errFailure { fmt.Printf("Violation at ts: %d\n", lowTs) return lowTs } else if err != nil { log.Printf("Error at lowTs: %d. Err=%v\n", lowTs, err) return 0 } fmt.Printf("No violation found at ts: %d\n", lowTs) return 0 } midTs := (lowTs + highTs) / 2 log.Println() log.Printf("Checking. low=%d. high=%d. mid=%d\n", lowTs, highTs, midTs) err := checkAt(midTs) if err == badger.ErrKeyNotFound || err == nil { // If no failure, move to higher ts. return findFirstInvalidTxn(db, midTs+1, highTs) } // Found an error. return findFirstInvalidTxn(db, lowTs, midTs) }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/socket/socket_classic.go#L40-L104
func DialTimeout(ctx context.Context, protocol, addr string, timeout time.Duration) (*Conn, error) { dialCtx := ctx // Used for dialing and name resolution, but not stored in the *Conn. if timeout > 0 { var cancel context.CancelFunc dialCtx, cancel = context.WithTimeout(ctx, timeout) defer cancel() } host, portStr, err := net.SplitHostPort(addr) if err != nil { return nil, err } port, err := strconv.Atoi(portStr) if err != nil { return nil, fmt.Errorf("socket: bad port %q: %v", portStr, err) } var prot pb.CreateSocketRequest_SocketProtocol switch protocol { case "tcp": prot = pb.CreateSocketRequest_TCP case "udp": prot = pb.CreateSocketRequest_UDP default: return nil, fmt.Errorf("socket: unknown protocol %q", protocol) } packedAddrs, resolved, err := resolve(dialCtx, ipFamilies, host) if err != nil { return nil, fmt.Errorf("socket: failed resolving %q: %v", host, err) } if len(packedAddrs) == 0 { return nil, fmt.Errorf("no addresses for %q", host) } packedAddr := packedAddrs[0] // use first address fam := pb.CreateSocketRequest_IPv4 if len(packedAddr) == net.IPv6len { fam = pb.CreateSocketRequest_IPv6 } req := &pb.CreateSocketRequest{ Family: fam.Enum(), Protocol: prot.Enum(), RemoteIp: &pb.AddressPort{ Port: proto.Int32(int32(port)), PackedAddress: packedAddr, }, } if resolved { req.RemoteIp.HostnameHint = &host } res := &pb.CreateSocketReply{} if err := internal.Call(dialCtx, "remote_socket", "CreateSocket", req, res); err != nil { return nil, err } return &Conn{ ctx: ctx, desc: res.GetSocketDescriptor(), prot: prot, local: res.ProxyExternalIp, remote: req.RemoteIp, }, nil }
https://github.com/urandom/handler/blob/61508044a5569d1609521d81e81f6737567fd104/security/nonce.go#L113-L165
func Nonce(h http.Handler, opts ...Option) http.Handler { headerStorage := nonceHeaderStorage{} o := options{ logger: handler.OutLogger(), generator: timeRandomGenerator, getter: headerStorage, setter: headerStorage, age: 45 * time.Second, } o.apply(opts) store := nonceStore{} opChan := make(chan func(nonceStore)) go func() { for op := range opChan { op(store) } }() go func() { for { select { case <-time.After(5 * time.Minute): cleanup(o.age, opChan) } } }() setter := func(w http.ResponseWriter, r *http.Request) error { nonce, err := generateAndStore(o.age, o.generator, opChan) if err != nil { return err } return o.setter.SetNonce(nonce, w, r) } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() nonce := o.getter.GetNonce(r) if nonce != "" { if validateAndRemoveNonce(nonce, o.age, opChan) { ctx = context.WithValue(ctx, nonceValueKey, NonceStatus{NonceValid}) } else { ctx = context.WithValue(ctx, nonceValueKey, NonceStatus{NonceInvalid}) } } h.ServeHTTP(w, r.WithContext(context.WithValue(ctx, nonceSetterKey, setter))) }) }
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/logger.go#L104-L107
func (l *Logger) SetBackend(backend LeveledBackend) { l.backend = backend l.haveBackend = true }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L324-L333
func (p *GetStackTraceParams) Do(ctx context.Context) (stackTrace *runtime.StackTrace, err error) { // execute var res GetStackTraceReturns err = cdp.Execute(ctx, CommandGetStackTrace, p, &res) if err != nil { return nil, err } return res.StackTrace, nil }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/http.go#L233-L246
func (a *API) PerformRequestWithContext(ctx context.Context, req *http.Request) (*http.Response, error) { // Sign last so auth headers don't get printed or logged if a.Auth != nil { if err := a.Auth.Sign(req); err != nil { return nil, err } } resp, err := a.Client.DoWithContext(ctx, req) if err != nil { return nil, err } return resp, err }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/maintenance/maintenance.go#L74-L84
func (s *MemoryStore) On() (changed bool, err error) { s.mu.Lock() defer s.mu.Unlock() if s.on { return } s.on = true changed = true return }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/agouti.go#L114-L123
func GeckoDriver(options ...Option) *WebDriver { var binaryName string if runtime.GOOS == "windows" { binaryName = "geckodriver.exe" } else { binaryName = "geckodriver" } command := []string{binaryName, "--port={{.Port}}"} return NewWebDriver("http://{{.Address}}", command, options...) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/proxy/grpcproxy/watcher.go#L55-L118
func (w *watcher) send(wr clientv3.WatchResponse) { if wr.IsProgressNotify() && !w.progress { return } if w.nextrev > wr.Header.Revision && len(wr.Events) > 0 { return } if w.nextrev == 0 { // current watch; expect updates following this revision w.nextrev = wr.Header.Revision + 1 } events := make([]*mvccpb.Event, 0, len(wr.Events)) var lastRev int64 for i := range wr.Events { ev := (*mvccpb.Event)(wr.Events[i]) if ev.Kv.ModRevision < w.nextrev { continue } else { // We cannot update w.rev here. // txn can have multiple events with the same rev. // If w.nextrev updates here, it would skip events in the same txn. lastRev = ev.Kv.ModRevision } filtered := false for _, filter := range w.filters { if filter(*ev) { filtered = true break } } if filtered { continue } if !w.prevKV { evCopy := *ev evCopy.PrevKv = nil ev = &evCopy } events = append(events, ev) } if lastRev >= w.nextrev { w.nextrev = lastRev + 1 } // all events are filtered out? if !wr.IsProgressNotify() && !wr.Created && len(events) == 0 && wr.CompactRevision == 0 { return } w.lastHeader = wr.Header w.post(&pb.WatchResponse{ Header: &wr.Header, Created: wr.Created, CompactRevision: wr.CompactRevision, Canceled: wr.Canceled, WatchId: w.id, Events: events, }) }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/future.go#L177-L188
func (u *userSnapshotFuture) Open() (*SnapshotMeta, io.ReadCloser, error) { if u.opener == nil { return nil, nil, fmt.Errorf("no snapshot available") } else { // Invalidate the opener so it can't get called multiple times, // which isn't generally safe. defer func() { u.opener = nil }() return u.opener() } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L1888-L1892
func (v DetachFromTargetParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoTarget21(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/google/subcommands/blob/d47216cd17848d55a33e6f651cbe408243ed55b8/subcommands.go#L232-L238
func explain(w io.Writer, cmd Command) { fmt.Fprintf(w, "%s", cmd.Usage()) subflags := flag.NewFlagSet(cmd.Name(), flag.PanicOnError) subflags.SetOutput(w) cmd.SetFlags(subflags) subflags.PrintDefaults() }
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L259-L262
func (l *Logger) Fatalln(args ...interface{}) { l.Output(2, LevelFatal, fmt.Sprintln(args...)) os.Exit(1) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/server/driver.go#L162-L180
func (d *driver) checkIsAuthorized(pachClient *client.APIClient, r *pfs.Repo, s auth.Scope) error { ctx := pachClient.Ctx() me, err := pachClient.WhoAmI(ctx, &auth.WhoAmIRequest{}) if auth.IsErrNotActivated(err) { return nil } resp, err := pachClient.AuthAPIClient.Authorize(ctx, &auth.AuthorizeRequest{ Repo: r.Name, Scope: s, }) if err != nil { return fmt.Errorf("error during authorization check for operation on \"%s\": %v", r.Name, grpcutil.ScrubGRPC(err)) } if !resp.Authorized { return &auth.ErrNotAuthorized{Subject: me.Username, Repo: r.Name, Required: s} } return nil }
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mocklogrecord.go#L29-L33
func (m *MockKeyValue) EmitString(key, value string) { m.Key = key m.ValueKind = reflect.TypeOf(value).Kind() m.ValueString = fmt.Sprint(value) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/tarball/tarball_src.go#L254-L259
func (*tarballImageSource) GetSignatures(ctx context.Context, instanceDigest *digest.Digest) ([][]byte, error) { if instanceDigest != nil { return nil, fmt.Errorf("manifest lists are not supported by the %q transport", transportName) } return nil, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/pkg/ghclient/wrappers.go#L145-L169
func (c *Client) GetCollaborators(org, repo string) ([]*github.User, error) { opts := &github.ListCollaboratorsOptions{} collaborators, err := c.depaginate( fmt.Sprintf("getting collaborators for '%s/%s'", org, repo), &opts.ListOptions, func() ([]interface{}, *github.Response, error) { page, resp, err := c.repoService.ListCollaborators(context.Background(), org, repo, opts) var interfaceList []interface{} if err == nil { interfaceList = make([]interface{}, 0, len(page)) for _, user := range page { interfaceList = append(interfaceList, user) } } return interfaceList, resp, err }, ) result := make([]*github.User, 0, len(collaborators)) for _, user := range collaborators { result = append(result, user.(*github.User)) } return result, err }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/blobinfocache/boltdb/boltdb.go#L54-L68
func lockPath(path string) { pl := func() *pathLock { // A scope for defer pathLocksMutex.Lock() defer pathLocksMutex.Unlock() pl, ok := pathLocks[path] if ok { pl.refCount++ } else { pl = &pathLock{refCount: 1, mutex: sync.Mutex{}} pathLocks[path] = pl } return pl }() pl.mutex.Lock() }