_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/service_instance.go#L382-L402
|
func serviceInstanceStatus(w http.ResponseWriter, r *http.Request, t auth.Token) error {
instanceName := r.URL.Query().Get(":instance")
serviceName := r.URL.Query().Get(":service")
serviceInstance, err := getServiceInstanceOrError(serviceName, instanceName)
if err != nil {
return err
}
allowed := permission.Check(t, permission.PermServiceInstanceReadStatus,
contextsForServiceInstance(serviceInstance, serviceName)...,
)
if !allowed {
return permission.ErrUnauthorized
}
var b string
requestID := requestIDHeader(r)
if b, err = serviceInstance.Status(requestID); err != nil {
return errors.Wrap(err, "Could not retrieve status of service instance, error")
}
_, err = fmt.Fprintf(w, `Service instance "%s" is %s`, instanceName, b)
return err
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/repoowners/repoowners.go#L176-L206
|
func (c *Client) LoadRepoAliases(org, repo, base string) (RepoAliases, error) {
log := c.logger.WithFields(logrus.Fields{"org": org, "repo": repo, "base": base})
cloneRef := fmt.Sprintf("%s/%s", org, repo)
fullName := fmt.Sprintf("%s:%s", cloneRef, base)
sha, err := c.ghc.GetRef(org, repo, fmt.Sprintf("heads/%s", base))
if err != nil {
return nil, fmt.Errorf("failed to get current SHA for %s: %v", fullName, err)
}
c.lock.Lock()
defer c.lock.Unlock()
entry, ok := c.cache[fullName]
if !ok || entry.sha != sha {
// entry is non-existent or stale.
gitRepo, err := c.git.Clone(cloneRef)
if err != nil {
return nil, fmt.Errorf("failed to clone %s: %v", cloneRef, err)
}
defer gitRepo.Clean()
if err := gitRepo.Checkout(base); err != nil {
return nil, err
}
entry.aliases = loadAliasesFrom(gitRepo.Dir, log)
entry.sha = sha
c.cache[fullName] = entry
}
return entry.aliases, nil
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peer.go#L193-L195
|
func (lop listOfPeers) Swap(i, j int) {
lop[i], lop[j] = lop[j], lop[i]
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/debugutil/pprof.go#L26-L47
|
func PProfHandlers() map[string]http.Handler {
// set only when there's no existing setting
if runtime.SetMutexProfileFraction(-1) == 0 {
// 1 out of 5 mutex events are reported, on average
runtime.SetMutexProfileFraction(5)
}
m := make(map[string]http.Handler)
m[HTTPPrefixPProf+"/"] = http.HandlerFunc(pprof.Index)
m[HTTPPrefixPProf+"/profile"] = http.HandlerFunc(pprof.Profile)
m[HTTPPrefixPProf+"/symbol"] = http.HandlerFunc(pprof.Symbol)
m[HTTPPrefixPProf+"/cmdline"] = http.HandlerFunc(pprof.Cmdline)
m[HTTPPrefixPProf+"/trace "] = http.HandlerFunc(pprof.Trace)
m[HTTPPrefixPProf+"/heap"] = pprof.Handler("heap")
m[HTTPPrefixPProf+"/goroutine"] = pprof.Handler("goroutine")
m[HTTPPrefixPProf+"/threadcreate"] = pprof.Handler("threadcreate")
m[HTTPPrefixPProf+"/block"] = pprof.Handler("block")
m[HTTPPrefixPProf+"/mutex"] = pprof.Handler("mutex")
return m
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/config.go#L641-L659
|
func (c *Configuration) EnabledReposForExternalPlugin(plugin string) (orgs, repos []string) {
for repo, plugins := range c.ExternalPlugins {
found := false
for _, candidate := range plugins {
if candidate.Name == plugin {
found = true
break
}
}
if found {
if strings.Contains(repo, "/") {
repos = append(repos, repo)
} else {
orgs = append(orgs, repo)
}
}
}
return
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L463-L472
|
func (c APIClient) FlushCommitAll(commits []*pfs.Commit, toRepos []*pfs.Repo) ([]*pfs.CommitInfo, error) {
var result []*pfs.CommitInfo
if err := c.FlushCommitF(commits, toRepos, func(ci *pfs.CommitInfo) error {
result = append(result, ci)
return nil
}); err != nil {
return nil, err
}
return result, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L1879-L1883
|
func (v *QuerySelectorParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom20(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/audits/easyjson.go#L201-L205
|
func (v GetEncodedResponseParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoAudits1(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/cmpopts/xform.go#L32-L35
|
func AcyclicTransformer(name string, xformFunc interface{}) cmp.Option {
xf := xformFilter{cmp.Transformer(name, xformFunc)}
return cmp.FilterPath(xf.filter, xf.xform)
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/routes/put_apps_app_routes_route_parameters.go#L76-L79
|
func (o *PutAppsAppRoutesRouteParams) WithTimeout(timeout time.Duration) *PutAppsAppRoutesRouteParams {
o.SetTimeout(timeout)
return o
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/overlay.go#L449-L451
|
func (p *SetShowScrollBottleneckRectsParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandSetShowScrollBottleneckRects, p, nil)
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/module.go#L110-L118
|
func (t *funcTab) find(pc core.Address) *Func {
n := sort.Search(len(t.entries), func(i int) bool {
return t.entries[i].max > pc
})
if n == len(t.entries) || pc < t.entries[n].min || pc >= t.entries[n].max {
return nil
}
return t.entries[n].f
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L5370-L5374
|
func (v EventLifecycleEvent) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage55(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.mapper.go#L293-L303
|
func (c *ClusterTx) ProfileExists(project string, name string) (bool, error) {
_, err := c.ProfileID(project, name)
if err != nil {
if err == ErrNoSuchObject {
return false, nil
}
return false, err
}
return true, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/session.go#L126-L130
|
func WithLease(leaseID v3.LeaseID) SessionOption {
return func(so *sessionOptions) {
so.leaseID = leaseID
}
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/tcp_transport.go#L38-L48
|
func NewTCPTransportWithLogger(
bindAddr string,
advertise net.Addr,
maxPool int,
timeout time.Duration,
logger *log.Logger,
) (*NetworkTransport, error) {
return newTCPTransport(bindAddr, advertise, func(stream StreamLayer) *NetworkTransport {
return NewNetworkTransportWithLogger(stream, maxPool, timeout, logger)
})
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L729-L732
|
func (p RunScriptParams) WithObjectGroup(objectGroup string) *RunScriptParams {
p.ObjectGroup = objectGroup
return &p
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/log_unstable.go#L96-L109
|
func (u *unstable) shrinkEntriesArray() {
// We replace the array if we're using less than half of the space in
// it. This number is fairly arbitrary, chosen as an attempt to balance
// memory usage vs number of allocations. It could probably be improved
// with some focused tuning.
const lenMultiple = 2
if len(u.entries) == 0 {
u.entries = nil
} else if len(u.entries)*lenMultiple < cap(u.entries) {
newEntries := make([]pb.Entry, len(u.entries))
copy(newEntries, u.entries)
u.entries = newEntries
}
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/deploy.go#L261-L304
|
func Deploy(opts DeployOptions) (string, error) {
if opts.Event == nil {
return "", errors.Errorf("missing event in deploy opts")
}
if opts.Rollback && !regexp.MustCompile(":v[0-9]+$").MatchString(opts.Image) {
imageName, err := image.GetAppImageBySuffix(opts.App.Name, opts.Image)
if err != nil {
return "", err
}
opts.Image = imageName
}
logWriter := LogWriter{App: opts.App}
logWriter.Async()
defer logWriter.Close()
opts.Event.SetLogWriter(io.MultiWriter(&tsuruIo.NoErrorWriter{Writer: opts.OutputStream}, &logWriter))
imageID, err := deployToProvisioner(&opts, opts.Event)
rebuild.RoutesRebuildOrEnqueue(opts.App.Name)
quotaErr := opts.App.fixQuota()
if quotaErr != nil {
log.Errorf("WARNING: unable to ensure quota is up-to-date after deploy: %v", quotaErr)
}
if err != nil {
var logLines []Applog
if provision.IsStartupError(err) {
logLines, _ = opts.App.lastLogs(10, Applog{
Source: "tsuru",
}, true)
}
err = &errorWithLog{err: err, logs: logLines}
return "", err
}
err = incrementDeploy(opts.App)
if err != nil {
log.Errorf("WARNING: couldn't increment deploy count, deploy opts: %#v", opts)
}
if opts.Kind == DeployImage || opts.Kind == DeployRollback {
if !opts.App.UpdatePlatform {
opts.App.SetUpdatePlatform(true)
}
} else if opts.App.UpdatePlatform {
opts.App.SetUpdatePlatform(false)
}
return imageID, nil
}
|
https://github.com/Jeffail/tunny/blob/4921fff29480bad359ad2fb3271fb461c8ffe1fc/tunny.go#L175-L215
|
func (p *Pool) ProcessTimed(
payload interface{},
timeout time.Duration,
) (interface{}, error) {
atomic.AddInt64(&p.queuedJobs, 1)
defer atomic.AddInt64(&p.queuedJobs, -1)
tout := time.NewTimer(timeout)
var request workRequest
var open bool
select {
case request, open = <-p.reqChan:
if !open {
return nil, ErrPoolNotRunning
}
case <-tout.C:
return nil, ErrJobTimedOut
}
select {
case request.jobChan <- payload:
case <-tout.C:
request.interruptFunc()
return nil, ErrJobTimedOut
}
select {
case payload, open = <-request.retChan:
if !open {
return nil, ErrWorkerClosed
}
case <-tout.C:
request.interruptFunc()
return nil, ErrJobTimedOut
}
tout.Stop()
return payload, nil
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/_metcd/server.go#L61-L97
|
func NewDefaultServer(
minPeerCount int,
terminatec <-chan struct{},
terminatedc chan<- error,
logger mesh.Logger,
) Server {
var (
peerName = mustPeerName()
nickName = mustHostname()
host = "0.0.0.0"
port = 6379
password = ""
channel = "metcd"
)
router := mesh.NewRouter(mesh.Config{
Host: host,
Port: port,
ProtocolMinVersion: mesh.ProtocolMinVersion,
Password: []byte(password),
ConnLimit: 64,
PeerDiscovery: true,
TrustedSubnets: []*net.IPNet{},
}, peerName, nickName, mesh.NullOverlay{}, logger)
// Create a meshconn.Peer and connect it to a channel.
peer := meshconn.NewPeer(router.Ourself.Peer.Name, router.Ourself.UID, logger)
gossip := router.NewGossip(channel, peer)
peer.Register(gossip)
// Start the router and join the mesh.
// Note that we don't ever stop the router.
// This may or may not be a problem.
// TODO(pb): determine if this is a super huge problem
router.Start()
return NewServer(router, peer, minPeerCount, terminatec, terminatedc, logger)
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L197-L243
|
func (app *App) MarshalJSON() ([]byte, error) {
repo, _ := repository.Manager().GetRepository(app.Name)
result := make(map[string]interface{})
result["name"] = app.Name
result["platform"] = app.Platform
if version := app.GetPlatformVersion(); version != "latest" {
result["platform"] = fmt.Sprintf("%s:%s", app.Platform, version)
}
result["teams"] = app.Teams
units, err := app.Units()
result["units"] = units
var errMsgs []string
if err != nil {
errMsgs = append(errMsgs, fmt.Sprintf("unable to list app units: %+v", err))
}
result["repository"] = repo.ReadWriteURL
plan := map[string]interface{}{
"name": app.Plan.Name,
"memory": app.Plan.Memory,
"swap": app.Plan.Swap,
"cpushare": app.Plan.CpuShare,
}
routers, err := app.GetRoutersWithAddr()
if err != nil {
errMsgs = append(errMsgs, fmt.Sprintf("unable to get app addresses: %+v", err))
}
if len(routers) > 0 {
result["ip"] = routers[0].Address
plan["router"] = routers[0].Name
result["router"] = routers[0].Name
result["routeropts"] = routers[0].Opts
}
result["cname"] = app.CName
result["owner"] = app.Owner
result["pool"] = app.Pool
result["description"] = app.Description
result["deploys"] = app.Deploys
result["teamowner"] = app.TeamOwner
result["plan"] = plan
result["lock"] = app.Lock
result["tags"] = app.Tags
result["routers"] = routers
if len(errMsgs) > 0 {
result["error"] = strings.Join(errMsgs, "\n")
}
return json.Marshal(&result)
}
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/seekret.go#L219-L221
|
func (s *Seekret) GroupObjectsByMetadata(k string) map[string][]models.Object {
return models.GroupObjectsByMetadata(s.objectList, k)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/target.go#L184-L187
|
func (p ExposeDevToolsProtocolParams) WithBindingName(bindingName string) *ExposeDevToolsProtocolParams {
p.BindingName = bindingName
return &p
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L888-L890
|
func (g *Glg) CustomLogf(level string, format string, val ...interface{}) error {
return g.out(g.TagStringToLevel(level), format, val...)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/worker/api_server.go#L1086-L1092
|
func (a *APIServer) GetChunk(request *GetChunkRequest, server Worker_GetChunkServer) error {
filter := hashtree.NewFilter(a.numShards, request.Shard)
if request.Stats {
return a.chunkStatsCache.Get(request.Id, grpcutil.NewStreamingBytesWriter(server), filter)
}
return a.chunkCache.Get(request.Id, grpcutil.NewStreamingBytesWriter(server), filter)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L459-L496
|
func (c *ClusterTx) NodeWithLeastContainers() (string, error) {
threshold, err := c.NodeOfflineThreshold()
if err != nil {
return "", errors.Wrap(err, "failed to get offline threshold")
}
nodes, err := c.Nodes()
if err != nil {
return "", errors.Wrap(err, "failed to get current nodes")
}
name := ""
containers := -1
for _, node := range nodes {
if node.IsOffline(threshold) {
continue
}
// Fetch the number of containers already created on this node.
created, err := query.Count(c.tx, "containers", "node_id=?", node.ID)
if err != nil {
return "", errors.Wrap(err, "Failed to get containers count")
}
// Fetch the number of containers currently being created on this node.
pending, err := query.Count(
c.tx, "operations", "node_id=? AND type=?", node.ID, OperationContainerCreate)
if err != nil {
return "", errors.Wrap(err, "Failed to get pending containers count")
}
count := created + pending
if containers == -1 || count < containers {
containers = count
name = node.Name
}
}
return name, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/rafthttp/util.go#L155-L168
|
func checkVersionCompatibility(name string, server, minCluster *semver.Version) (
localServer *semver.Version,
localMinCluster *semver.Version,
err error) {
localServer = semver.Must(semver.NewVersion(version.Version))
localMinCluster = semver.Must(semver.NewVersion(version.MinClusterVersion))
if compareMajorMinorVersion(server, localMinCluster) == -1 {
return localServer, localMinCluster, fmt.Errorf("remote version is too low: remote[%s]=%s, local=%s", name, server, localServer)
}
if compareMajorMinorVersion(minCluster, localServer) == 1 {
return localServer, localMinCluster, fmt.Errorf("local version is too low: remote[%s]=%s, local=%s", name, server, localServer)
}
return localServer, localMinCluster, nil
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/benchmark/internal_client.go#L47-L56
|
func NewClient(hosts []string, optFns ...Option) Client {
opts := getOptions(optFns)
if opts.external {
return newExternalClient(hosts, opts)
}
if opts.numClients > 1 {
return newInternalMultiClient(hosts, opts)
}
return newClient(hosts, opts)
}
|
https://github.com/fossapps/pushy/blob/4c6045d7a1d3c310d61168ff1ccd5421d5c162f6/pushy.go#L110-L116
|
func (p *Pushy) NotifyDevice(request SendNotificationRequest) (*NotificationResponse, *Error, error) {
url := fmt.Sprintf("%s/push?api_key=%s", p.APIEndpoint, p.APIToken)
var success *NotificationResponse
var pushyErr *Error
err := post(p.httpClient, url, request, &success, &pushyErr)
return success, pushyErr, err
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/dag/dag.go#L69-L75
|
func (d *DAG) Descendants(id string, to []string) []string {
seen := make(map[string]bool)
for _, toID := range to {
seen[toID] = true
}
return bfs(id, d.children, seen)
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/internal/frame/frame.go#L57-L59
|
func (f *Frame) SetLvar(i int, v interface{}) {
f.stack.Set(i, v)
}
|
https://github.com/antlinker/go-dirtyfilter/blob/533f538ffaa112776b1258c3db63e6f55648e18b/store/mongo.go#L75-L92
|
func (ms *MongoStore) Write(words ...string) error {
if len(words) == 0 {
return nil
}
var err error
ms.c(func(c *mgo.Collection) {
for i, l := 0, len(words); i < l; i++ {
_, err = c.Upsert(_Dirties{Value: words[i]}, _Dirties{Value: words[i]})
}
})
if err != nil {
return err
}
atomic.AddUint64(&ms.version, 1)
return nil
}
|
https://github.com/blacksails/cgp/blob/570ac705cf2d7a9235d911d00b6f976ab3386c2f/forwarder.go#L55-L62
|
func (dom *Domain) GetForwarder(name string) (*Forwarder, error) {
var f string
err := dom.cgp.request(getForwarder{Param: fmt.Sprintf("%s@%s", name, dom.Name)}, &f)
if err != nil {
return &Forwarder{}, err
}
return &Forwarder{Domain: dom, Name: name, To: f}, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plank/controller.go#L255-L259
|
func (c *Controller) SyncMetrics() {
c.pjLock.RLock()
defer c.pjLock.RUnlock()
kube.GatherProwJobMetrics(c.pjs)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/easyjson.go#L1607-L1611
|
func (v AuthChallengeResponse) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoFetch14(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/cert/logging_conn.go#L89-L91
|
func (l *loggingConn) Read(b []byte) (n int, err error) {
return l.r.Read(b)
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/skl/skl.go#L90-L100
|
func (s *Skiplist) DecrRef() {
newRef := atomic.AddInt32(&s.ref, -1)
if newRef > 0 {
return
}
s.arena.reset()
// Indicate we are closed. Good for testing. Also, lets GC reclaim memory. Race condition
// here would suggest we are accessing skiplist when we are supposed to have no reference!
s.arena = nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/runner/lease_renewer_command.go#L36-L44
|
func NewLeaseRenewerCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "lease-renewer",
Short: "Performs lease renew operation",
Run: runLeaseRenewerFunc,
}
cmd.Flags().Int64Var(&leaseTTL, "ttl", 5, "lease's ttl")
return cmd
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/stm.go#L380-L382
|
func NewSTMSerializable(ctx context.Context, c *v3.Client, apply func(STM) error) (*v3.TxnResponse, error) {
return NewSTM(c, apply, WithAbortContext(ctx), WithIsolation(Serializable))
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/types.go#L62-L78
|
func (t *InspectMode) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch InspectMode(in.String()) {
case InspectModeSearchForNode:
*t = InspectModeSearchForNode
case InspectModeSearchForUAShadowDOM:
*t = InspectModeSearchForUAShadowDOM
case InspectModeCaptureAreaScreenshot:
*t = InspectModeCaptureAreaScreenshot
case InspectModeShowDistances:
*t = InspectModeShowDistances
case InspectModeNone:
*t = InspectModeNone
default:
in.AddError(errors.New("unknown InspectMode value"))
}
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/channel.go#L611-L623
|
func (ch *Channel) exchangeUpdated(c *Connection) {
if c.remotePeerInfo.HostPort == "" {
// Hostport is unknown until we get init resp.
return
}
p, ok := ch.RootPeers().Get(c.remotePeerInfo.HostPort)
if !ok {
return
}
ch.updatePeer(p)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L334-L342
|
func (c APIClient) InspectBranch(repoName string, branch string) (*pfs.BranchInfo, error) {
branchInfo, err := c.PfsAPIClient.InspectBranch(
c.Ctx(),
&pfs.InspectBranchRequest{
Branch: NewBranch(repoName, branch),
},
)
return branchInfo, grpcutil.ScrubGRPC(err)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/pipeline/controller.go#L196-L215
|
func (c *controller) Run(threads int, stop <-chan struct{}) error {
defer runtime.HandleCrash()
defer c.workqueue.ShutDown()
logrus.Info("Starting Pipeline controller")
logrus.Info("Waiting for informer caches to sync")
if ok := cache.WaitForCacheSync(stop, c.hasSynced); !ok {
return fmt.Errorf("failed to wait for caches to sync")
}
logrus.Info("Starting workers")
for i := 0; i < threads; i++ {
go wait.Until(c.runWorker, time.Second, stop)
}
logrus.Info("Started workers")
<-stop
logrus.Info("Shutting down workers")
return nil
}
|
https://github.com/r3labs/sse/blob/2f90368216802092e9ed520c43e974e11d50438d/event_log.go#L16-L20
|
func (e *EventLog) Add(ev *Event) {
ev.ID = []byte(e.currentindex())
ev.timestamp = time.Now()
(*e) = append((*e), ev)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/deploy/assets/assets.go#L1583-L1592
|
func AddRegistry(registry string, imageName string) string {
if registry == "" {
return imageName
}
parts := strings.Split(imageName, "/")
if len(parts) == 3 {
parts = parts[1:]
}
return path.Join(registry, parts[0], parts[1])
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/member_command.go#L29-L41
|
func NewMemberCommand() *cobra.Command {
mc := &cobra.Command{
Use: "member <subcommand>",
Short: "Membership related commands",
}
mc.AddCommand(NewMemberAddCommand())
mc.AddCommand(NewMemberRemoveCommand())
mc.AddCommand(NewMemberUpdateCommand())
mc.AddCommand(NewMemberListCommand())
return mc
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/tackle/main.go#L304-L363
|
func selectContext(co contextOptions) (string, error) {
fmt.Println("Existing kubernetes contexts:")
// get cluster context
_, cfg, err := contextConfig()
if err != nil {
logrus.WithError(err).Fatal("Failed to load ~/.kube/config from any obvious location")
}
// list contexts and ask to user to choose a context
options := map[int]string{}
var ctxs []string
for ctx := range cfg.Contexts {
ctxs = append(ctxs, ctx)
}
sort.Strings(ctxs)
for idx, ctx := range ctxs {
options[idx] = ctx
if ctx == cfg.CurrentContext {
fmt.Printf("* %d: %s (current)", idx, ctx)
} else {
fmt.Printf(" %d: %s", idx, ctx)
}
fmt.Println()
}
fmt.Println()
choice := co.context
switch {
case choice != "":
fmt.Println("Reuse " + choice + " context...")
case co.create != "" || co.reuse != "":
choice = "create"
fmt.Println("Create new context...")
default:
fmt.Print("Choose context or [create new]: ")
fmt.Scanln(&choice)
}
if choice == "create" || choice == "" || choice == "create new" || choice == "new" {
ctx, err := createContext(co)
if err != nil {
return "", fmt.Errorf("create context: %v", err)
}
return ctx, nil
}
if _, ok := cfg.Contexts[choice]; ok {
return choice, nil
}
idx, err := strconv.Atoi(choice)
if err != nil {
return "", fmt.Errorf("invalid context: %q", choice)
}
if ctx, ok := options[idx]; ok {
return ctx, nil
}
return "", fmt.Errorf("invalid index: %d", idx)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/upgrade.go#L23-L56
|
func NotifyUpgradeCompleted(state *state.State, cert *shared.CertInfo) error {
notifier, err := NewNotifier(state, cert, NotifyAll)
if err != nil {
return err
}
return notifier(func(client lxd.ContainerServer) error {
info, err := client.GetConnectionInfo()
if err != nil {
return errors.Wrap(err, "failed to get connection info")
}
url := fmt.Sprintf("%s%s", info.Addresses[0], databaseEndpoint)
request, err := http.NewRequest("PATCH", url, nil)
if err != nil {
return errors.Wrap(err, "failed to create database notify upgrade request")
}
httpClient, err := client.GetHTTPClient()
if err != nil {
return errors.Wrap(err, "failed to get HTTP client")
}
response, err := httpClient.Do(request)
if err != nil {
return errors.Wrap(err, "failed to notify node about completed upgrade")
}
if response.StatusCode != http.StatusOK {
return fmt.Errorf("database upgrade notification failed: %s", response.Status)
}
return nil
})
}
|
https://github.com/gokyle/fswatch/blob/1dbdf8320a690537582afe0f45c947f501adeaad/watcher.go#L84-L86
|
func (w *Watcher) Active() bool {
return w.paths != nil && len(w.paths) > 0
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L798-L802
|
func (v StopParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoProfiler9(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L195-L199
|
func (q *Query) Project(fieldNames ...string) *Query {
q = q.clone()
q.projection = append([]string(nil), fieldNames...)
return q
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssm/codegen_client.go#L107-L109
|
func (r *Execution) Locator(api *API) *ExecutionLocator {
return api.ExecutionLocator(r.Href)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/operations.go#L304-L312
|
func (op *remoteOperation) Wait() error {
<-op.chDone
if op.chPost != nil {
<-op.chPost
}
return op.err
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/level_handler.go#L230-L257
|
func (s *levelHandler) get(key []byte) (y.ValueStruct, error) {
tables, decr := s.getTableForKey(key)
keyNoTs := y.ParseKey(key)
var maxVs y.ValueStruct
for _, th := range tables {
if th.DoesNotHave(keyNoTs) {
y.NumLSMBloomHits.Add(s.strLevel, 1)
continue
}
it := th.NewIterator(false)
defer it.Close()
y.NumLSMGets.Add(s.strLevel, 1)
it.Seek(key)
if !it.Valid() {
continue
}
if y.SameKey(key, it.Key()) {
if version := y.ParseTs(it.Key()); maxVs.Version < version {
maxVs = it.Value()
maxVs.Version = version
}
}
}
return maxVs, decr()
}
|
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/goxpath.go#L72-L84
|
func (xp XPathExec) ExecNum(t tree.Node, opts ...FuncOpts) (float64, error) {
res, err := xp.Exec(t, opts...)
if err != nil {
return 0, err
}
n, ok := res.(tree.IsNum)
if !ok {
return 0, fmt.Errorf("Cannot convert result to a number")
}
return float64(n.Num()), nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/pkg/ghclient/wrappers.go#L239-L263
|
func (c *Client) GetRepoLabels(org, repo string) ([]*github.Label, error) {
opts := &github.ListOptions{}
labels, err := c.depaginate(
fmt.Sprintf("getting valid labels for '%s/%s'", org, repo),
opts,
func() ([]interface{}, *github.Response, error) {
page, resp, err := c.issueService.ListLabels(context.Background(), org, repo, opts)
var interfaceList []interface{}
if err == nil {
interfaceList = make([]interface{}, 0, len(page))
for _, label := range page {
interfaceList = append(interfaceList, label)
}
}
return interfaceList, resp, err
},
)
result := make([]*github.Label, 0, len(labels))
for _, label := range labels {
result = append(result, label.(*github.Label))
}
return result, err
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aebundler/aebundler.go#L128-L165
|
func (s *app) bundle(tarFile string) (err error) {
var out io.Writer
if tarFile == "-" {
out = os.Stdout
} else {
f, err := os.Create(tarFile)
if err != nil {
return err
}
defer func() {
if cerr := f.Close(); err == nil {
err = cerr
}
}()
out = f
}
tw := tar.NewWriter(out)
for srcDir, importName := range s.imports {
dstDir := "_gopath/src/" + importName
if err = copyTree(tw, dstDir, srcDir); err != nil {
return fmt.Errorf("unable to copy directory %v to %v: %v", srcDir, dstDir, err)
}
}
if err := copyTree(tw, ".", *rootDir); err != nil {
return fmt.Errorf("unable to copy root directory to /app: %v", err)
}
if !s.hasMain {
if err := synthesizeMain(tw, s.appFiles); err != nil {
return fmt.Errorf("unable to synthesize new main func: %v", err)
}
}
if err := tw.Close(); err != nil {
return fmt.Errorf("unable to close tar file %v: %v", tarFile, err)
}
return nil
}
|
https://github.com/kjk/lzmadec/blob/4c61f00ce86f6f11ed9630fa16b771889b08147b/lzmadec.go#L198-L217
|
func newArchive(path string, password *string) (*Archive, error) {
err := detect7zCached()
if err != nil {
return nil, err
}
cmd := exec.Command("7z", "l", "-slt", "-sccUTF-8", path)
out, err := cmd.CombinedOutput()
if err != nil {
return nil, err
}
entries, err := parse7zListOutput(out)
if err != nil {
return nil, err
}
return &Archive{
Path: path,
Entries: entries,
password: password,
}, nil
}
|
https://github.com/qor/roles/blob/d6375609fe3e5da46ad3a574fae244fb633e79c1/permission.go#L103-L136
|
func (permission Permission) HasPermission(mode PermissionMode, roles ...interface{}) bool {
var roleNames []string
for _, role := range roles {
if r, ok := role.(string); ok {
roleNames = append(roleNames, r)
} else if roler, ok := role.(Roler); ok {
roleNames = append(roleNames, roler.GetRoles()...)
} else {
fmt.Printf("invalid role %#v\n", role)
return false
}
}
if len(permission.DeniedRoles) != 0 {
if DeniedRoles := permission.DeniedRoles[mode]; DeniedRoles != nil {
if includeRoles(DeniedRoles, roleNames) {
return false
}
}
}
// return true if haven't define allowed roles
if len(permission.AllowedRoles) == 0 {
return true
}
if AllowedRoles := permission.AllowedRoles[mode]; AllowedRoles != nil {
if includeRoles(AllowedRoles, roleNames) {
return true
}
}
return false
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/thrift/server.go#L51-L66
|
func NewServer(registrar tchannel.Registrar) *Server {
metaHandler := newMetaHandler()
server := &Server{
ch: registrar,
log: registrar.Logger(),
handlers: make(map[string]handler),
metaHandler: metaHandler,
ctxFn: defaultContextFn,
}
server.Register(newTChanMetaServer(metaHandler))
if ch, ok := registrar.(*tchannel.Channel); ok {
// Register the meta endpoints on the "tchannel" service name.
NewServer(ch.GetSubChannel("tchannel"))
}
return server
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_image.go#L54-L107
|
func GetRepositoryTags(ctx context.Context, sys *types.SystemContext, ref types.ImageReference) ([]string, error) {
dr, ok := ref.(dockerReference)
if !ok {
return nil, errors.Errorf("ref must be a dockerReference")
}
path := fmt.Sprintf(tagsPath, reference.Path(dr.ref))
client, err := newDockerClientFromRef(sys, dr, false, "pull")
if err != nil {
return nil, errors.Wrap(err, "failed to create client")
}
tags := make([]string, 0)
for {
res, err := client.makeRequest(ctx, "GET", path, nil, nil, v2Auth, nil)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
// print url also
return nil, errors.Errorf("Invalid status code returned when fetching tags list %d (%s)", res.StatusCode, http.StatusText(res.StatusCode))
}
var tagsHolder struct {
Tags []string
}
if err = json.NewDecoder(res.Body).Decode(&tagsHolder); err != nil {
return nil, err
}
tags = append(tags, tagsHolder.Tags...)
link := res.Header.Get("Link")
if link == "" {
break
}
linkURLStr := strings.Trim(strings.Split(link, ";")[0], "<>")
linkURL, err := url.Parse(linkURLStr)
if err != nil {
return tags, err
}
// can be relative or absolute, but we only want the path (and I
// guess we're in trouble if it forwards to a new place...)
path = linkURL.Path
if linkURL.RawQuery != "" {
path += "?"
path += linkURL.RawQuery
}
}
return tags, nil
}
|
https://github.com/Financial-Times/base-ft-rw-app-go/blob/1ea8a13e1f37b95318cd965796558d932750f407/baseftrwapp/baseftapp.go#L84-L128
|
func router(apiData []byte, services map[string]Service, healthHandler func(http.ResponseWriter, *http.Request)) *mux.Router {
m := mux.NewRouter()
gtgChecker := make([]gtg.StatusChecker, 0)
for path, service := range services {
handlers := httpHandlers{service}
m.HandleFunc(fmt.Sprintf("/%s/__count", path), handlers.countHandler).Methods("GET")
m.HandleFunc(fmt.Sprintf("/%s/__ids", path), handlers.idsHandler).Methods("GET")
m.HandleFunc(fmt.Sprintf("/%s/{uuid}", path), handlers.getHandler).Methods("GET")
m.HandleFunc(fmt.Sprintf("/%s/{uuid}", path), handlers.putHandler).Methods("PUT")
m.HandleFunc(fmt.Sprintf("/%s/{uuid}", path), handlers.deleteHandler).Methods("DELETE")
gtgChecker = append(gtgChecker, func() gtg.Status {
if err := service.Check(); err != nil {
return gtg.Status{GoodToGo: false, Message: err.Error()}
}
return gtg.Status{GoodToGo: true}
})
}
if apiData != nil && len(apiData) != 0 {
endpoint, err := api.NewAPIEndpointForYAML(apiData)
if err != nil {
log.Warn("Failed to serve API endpoint, please check whether the OpenAPI file is valid")
} else {
m.HandleFunc(api.DefaultPath, endpoint.ServeHTTP)
}
}
m.HandleFunc("/__health", healthHandler)
// The top one of these feels more correct, but the lower one matches what we have in Dropwizard,
// so it's what apps expect currently
m.HandleFunc(status.PingPath, status.PingHandler)
m.HandleFunc(status.PingPathDW, status.PingHandler)
// The top one of these feels more correct, but the lower one matches what we have in Dropwizard,
// so it's what apps expect currently same as ping, the content of build-info needs more definition
m.HandleFunc(status.BuildInfoPath, status.BuildInfoHandler)
m.HandleFunc(status.BuildInfoPathDW, status.BuildInfoHandler)
m.HandleFunc(status.GTGPath, status.NewGoodToGoHandler(gtg.FailFastParallelCheck(gtgChecker)))
return m
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L2593-L2597
|
func (v *GetPropertiesParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime22(&r, v)
return r.Error()
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/contrib/raftexample/raft.go#L143-L189
|
func (rc *raftNode) publishEntries(ents []raftpb.Entry) bool {
for i := range ents {
switch ents[i].Type {
case raftpb.EntryNormal:
if len(ents[i].Data) == 0 {
// ignore empty messages
break
}
s := string(ents[i].Data)
select {
case rc.commitC <- &s:
case <-rc.stopc:
return false
}
case raftpb.EntryConfChange:
var cc raftpb.ConfChange
cc.Unmarshal(ents[i].Data)
rc.confState = *rc.node.ApplyConfChange(cc)
switch cc.Type {
case raftpb.ConfChangeAddNode:
if len(cc.Context) > 0 {
rc.transport.AddPeer(types.ID(cc.NodeID), []string{string(cc.Context)})
}
case raftpb.ConfChangeRemoveNode:
if cc.NodeID == uint64(rc.id) {
log.Println("I've been removed from the cluster! Shutting down.")
return false
}
rc.transport.RemovePeer(types.ID(cc.NodeID))
}
}
// after commit, update appliedIndex
rc.appliedIndex = ents[i].Index
// special nil commit to signal replay has finished
if ents[i].Index == rc.lastIndex {
select {
case rc.commitC <- nil:
case <-rc.stopc:
return false
}
}
}
return true
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/internal/version/version.go#L37-L49
|
func (x Version) Compare(y Version) int {
n := len(x)
if len(y) < n {
n = len(y)
}
for i := 0; i < n; i++ {
cmp := x[i] - y[i]
if cmp != 0 {
return cmp
}
}
return len(x) - len(y)
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/util.go#L66-L93
|
func (s *levelHandler) validate() error {
if s.level == 0 {
return nil
}
s.RLock()
defer s.RUnlock()
numTables := len(s.tables)
for j := 1; j < numTables; j++ {
if j >= len(s.tables) {
return errors.Errorf("Level %d, j=%d numTables=%d", s.level, j, numTables)
}
if y.CompareKeys(s.tables[j-1].Biggest(), s.tables[j].Smallest()) >= 0 {
return errors.Errorf(
"Inter: Biggest(j-1) \n%s\n vs Smallest(j): \n%s\n: level=%d j=%d numTables=%d",
hex.Dump(s.tables[j-1].Biggest()), hex.Dump(s.tables[j].Smallest()),
s.level, j, numTables)
}
if y.CompareKeys(s.tables[j].Smallest(), s.tables[j].Biggest()) > 0 {
return errors.Errorf(
"Intra: %q vs %q: level=%d j=%d numTables=%d",
s.tables[j].Smallest(), s.tables[j].Biggest(), s.level, j, numTables)
}
}
return nil
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L2108-L2126
|
func (app *App) Start(w io.Writer, process string) error {
w = app.withLogWriter(w)
msg := fmt.Sprintf("\n ---> Starting the process %q", process)
if process == "" {
msg = fmt.Sprintf("\n ---> Starting the app %q", app.Name)
}
fmt.Fprintf(w, "%s\n", msg)
prov, err := app.getProvisioner()
if err != nil {
return err
}
err = prov.Start(app, process)
if err != nil {
log.Errorf("[start] error on start the app %s - %s", app.Name, err)
return err
}
rebuild.RoutesRebuildOrEnqueue(app.Name)
return err
}
|
https://github.com/codemodus/kace/blob/e3ecf78ee2a5e58652cb2be34d3159ad9c89acf8/ktrie/ktrie.go#L56-L68
|
func (n *KNode) FindAsUpper(rs []rune) bool {
cur := n
for _, v := range rs {
cur = cur.linkByVal(unicode.ToUpper(v))
if cur == nil {
return false
}
}
return cur.end
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv2/command/set_command.go#L27-L48
|
func NewSetCommand() cli.Command {
return cli.Command{
Name: "set",
Usage: "set the value of a key",
ArgsUsage: "<key> <value>",
Description: `Set sets the value of a key.
When <value> begins with '-', <value> is interpreted as a flag.
Insert '--' for workaround:
$ set -- <key> <value>`,
Flags: []cli.Flag{
cli.IntFlag{Name: "ttl", Value: 0, Usage: "key time-to-live in seconds"},
cli.StringFlag{Name: "swap-with-value", Value: "", Usage: "previous value"},
cli.IntFlag{Name: "swap-with-index", Value: 0, Usage: "previous index"},
},
Action: func(c *cli.Context) error {
setCommandFunc(c, mustNewKeyAPI(c))
return nil
},
}
}
|
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/cddvd.go#L128-L150
|
func (v *VM) CDDVDs() ([]*CDDVDDrive, error) {
// Loads VMX file in memory
err := v.vmxfile.Read()
if err != nil {
return nil, err
}
model := v.vmxfile.model
var cddvds []*CDDVDDrive
model.WalkDevices(func(d vmx.Device) {
bus := BusTypeFromID(d.VMXID)
if d.Type == vmx.CDROM_IMAGE || d.Type == vmx.CDROM_RAW {
cddvds = append(cddvds, &CDDVDDrive{
ID: d.VMXID,
Bus: bus,
Filename: d.Filename,
})
}
})
return cddvds, nil
}
|
https://github.com/libp2p/go-libp2p-crypto/blob/9d2fed53443f745e6dc4d02bdcc94d9742a0ca84/secp256k1.go#L41-L48
|
func UnmarshalSecp256k1PublicKey(data []byte) (PubKey, error) {
k, err := btcec.ParsePubKey(data, btcec.S256())
if err != nil {
return nil, err
}
return (*Secp256k1PublicKey)(k), nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/util.go#L389-L440
|
func DirCopy(source string, dest string) error {
// Get info about source.
info, err := os.Stat(source)
if err != nil {
return errors.Wrapf(err, "failed to get source directory info")
}
if !info.IsDir() {
return fmt.Errorf("source is not a directory")
}
// Remove dest if it already exists.
if PathExists(dest) {
err := os.RemoveAll(dest)
if err != nil {
return errors.Wrapf(err, "failed to remove destination directory %s", dest)
}
}
// Create dest.
err = os.MkdirAll(dest, info.Mode())
if err != nil {
return errors.Wrapf(err, "failed to create destination directory %s", dest)
}
// Copy all files.
entries, err := ioutil.ReadDir(source)
if err != nil {
return errors.Wrapf(err, "failed to read source directory %s", source)
}
for _, entry := range entries {
sourcePath := filepath.Join(source, entry.Name())
destPath := filepath.Join(dest, entry.Name())
if entry.IsDir() {
err := DirCopy(sourcePath, destPath)
if err != nil {
return errors.Wrapf(err, "failed to copy sub-directory from %s to %s", sourcePath, destPath)
}
} else {
err := FileCopy(sourcePath, destPath)
if err != nil {
return errors.Wrapf(err, "failed to copy file from %s to %s", sourcePath, destPath)
}
}
}
return nil
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/reader.go#L92-L95
|
func (r *Reader) ReadLen16String() string {
len := r.ReadUint16()
return r.ReadString(int(len))
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_image_src.go#L372-L390
|
func (s *dockerImageSource) getSignaturesFromAPIExtension(ctx context.Context, instanceDigest *digest.Digest) ([][]byte, error) {
manifestDigest, err := s.manifestDigest(ctx, instanceDigest)
if err != nil {
return nil, err
}
parsedBody, err := s.c.getExtensionsSignatures(ctx, s.ref, manifestDigest)
if err != nil {
return nil, err
}
var sigs [][]byte
for _, sig := range parsedBody.Signatures {
if sig.Version == extensionSignatureSchemaVersion && sig.Type == extensionSignatureTypeAtomic {
sigs = append(sigs, sig.Content)
}
}
return sigs, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pod-utils/gcs/upload.go#L75-L87
|
func FileUploadWithMetadata(file string, metadata map[string]string) UploadFunc {
return func(obj *storage.ObjectHandle) error {
reader, err := os.Open(file)
if err != nil {
return err
}
uploadErr := DataUploadWithMetadata(reader, metadata)(obj)
closeErr := reader.Close()
return errorutil.NewAggregate(uploadErr, closeErr)
}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/localcache/cache.go#L78-L86
|
func (c *Cache) Delete(key string) error {
c.mu.Lock()
defer c.mu.Unlock()
if !c.keys[key] {
return nil
}
delete(c.keys, key)
return os.Remove(filepath.Join(c.root, key))
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_reference_match.go#L71-L81
|
func parseDockerReferences(s1, s2 string) (reference.Named, reference.Named, error) {
r1, err := reference.ParseNormalizedNamed(s1)
if err != nil {
return nil, nil, err
}
r2, err := reference.ParseNormalizedNamed(s2)
if err != nil {
return nil, nil, err
}
return r1, r2, nil
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/apps/patch_apps_app_parameters.go#L95-L98
|
func (o *PatchAppsAppParams) WithContext(ctx context.Context) *PatchAppsAppParams {
o.SetContext(ctx)
return o
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/file/buffer.go#L26-L29
|
func (b *Buffer) L(format string, a ...interface{}) {
fmt.Fprintf(b.buf, format, a...)
b.N()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L3919-L3923
|
func (v GetAppManifestReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage42(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/string.go#L12-L14
|
func NewStringByteCodeLoader(p parser.Parser, c compiler.Compiler) *StringByteCodeLoader {
return &StringByteCodeLoader{NewFlags(), p, c}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L7447-L7451
|
func (v AppManifestError) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage82(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/member_command.go#L218-L227
|
func memberListCommandFunc(cmd *cobra.Command, args []string) {
ctx, cancel := commandCtx(cmd)
resp, err := mustClientFromCmd(cmd).MemberList(ctx)
cancel()
if err != nil {
ExitWithError(ExitError, err)
}
display.MemberList(*resp)
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/fuzzy/cluster.go#L50-L52
|
func (a *LoggerAdapter) Logf(s string, v ...interface{}) {
a.log.Printf(s, v...)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L1170-L1174
|
func (v *ReleaseObjectGroupParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime11(&r, v)
return r.Error()
}
|
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/archive15.go#L96-L121
|
func calcAes30Params(pass []uint16, salt []byte) (key, iv []byte) {
p := make([]byte, 0, len(pass)*2+len(salt))
for _, v := range pass {
p = append(p, byte(v), byte(v>>8))
}
p = append(p, salt...)
hash := sha1.New()
iv = make([]byte, 16)
s := make([]byte, 0, hash.Size())
for i := 0; i < hashRounds; i++ {
hash.Write(p)
hash.Write([]byte{byte(i), byte(i >> 8), byte(i >> 16)})
if i%(hashRounds/16) == 0 {
s = hash.Sum(s[:0])
iv[i/(hashRounds/16)] = s[4*4+3]
}
}
key = hash.Sum(s[:0])
key = key[:16]
for k := key; len(k) >= 4; k = k[4:] {
k[0], k[1], k[2], k[3] = k[3], k[2], k[1], k[0]
}
return key, iv
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/benchmark/internal_server.go#L46-L78
|
func NewServer(optFns ...Option) Server {
opts := getOptions(optFns)
if opts.external {
return newExternalServer(opts)
}
ch, err := tchannel.NewChannel(opts.svcName, &tchannel.ChannelOptions{
Logger: tchannel.NewLevelLogger(tchannel.NewLogger(os.Stderr), tchannel.LogLevelWarn),
})
if err != nil {
panic("failed to create channel: " + err.Error())
}
if err := ch.ListenAndServe("127.0.0.1:0"); err != nil {
panic("failed to listen on port 0: " + err.Error())
}
s := &internalServer{
ch: ch,
opts: opts,
}
tServer := thrift.NewServer(ch)
tServer.Register(gen.NewTChanSecondServiceServer(handler{calls: &s.thriftCalls}))
ch.Register(raw.Wrap(rawHandler{calls: &s.rawCalls}), "echo")
if len(opts.advertiseHosts) > 0 {
if err := s.Advertise(opts.advertiseHosts); err != nil {
panic("failed to advertise: " + err.Error())
}
}
return s
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/easyjson.go#L1160-L1164
|
func (v EventWorkerErrorReported) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoServiceworker12(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L7441-L7443
|
func (api *API) PlacementGroupLocator(href string) *PlacementGroupLocator {
return &PlacementGroupLocator{Href(href), api}
}
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/ghttp/handlers.go#L280-L297
|
func RespondWithJSONEncodedPtr(statusCode *int, object interface{}, optionalHeader ...http.Header) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
data, err := json.Marshal(object)
Expect(err).ShouldNot(HaveOccurred())
var headers http.Header
if len(optionalHeader) == 1 {
headers = optionalHeader[0]
} else {
headers = make(http.Header)
}
if _, found := headers["Content-Type"]; !found {
headers["Content-Type"] = []string{"application/json"}
}
copyHeader(headers, w.Header())
w.WriteHeader(*statusCode)
w.Write(data)
}
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3128-L3142
|
func NewManageOfferResult(code ManageOfferResultCode, value interface{}) (result ManageOfferResult, err error) {
result.Code = code
switch ManageOfferResultCode(code) {
case ManageOfferResultCodeManageOfferSuccess:
tv, ok := value.(ManageOfferSuccessResult)
if !ok {
err = fmt.Errorf("invalid value, must be ManageOfferSuccessResult")
return
}
result.Success = &tv
default:
// void
}
return
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/http/http_client.go#L170-L180
|
func (o Options) MarshalYAML() (interface{}, error) {
return optionsJSON{
Timeout: marshal.Duration(o.Timeout),
KeepAlive: marshal.Duration(o.KeepAlive),
TLSHandshakeTimeout: marshal.Duration(o.TLSHandshakeTimeout),
TLSSkipVerify: o.TLSSkipVerify,
RetryTimeMax: marshal.Duration(o.RetryTimeMax),
RetrySleepMax: marshal.Duration(o.RetrySleepMax),
RetrySleepBase: marshal.Duration(o.RetrySleepBase),
}, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/har/easyjson.go#L1247-L1251
|
func (v Page) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoHar6(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pubsub/subscriber/server.go#L165-L195
|
func (s *PullServer) handlePulls(ctx context.Context, projectSubscriptions config.PubsubSubscriptions) (*errgroup.Group, context.Context, error) {
// Since config might change we need be able to cancel the current run
errGroup, derivedCtx := errgroup.WithContext(ctx)
for project, subscriptions := range projectSubscriptions {
client, err := s.Client.new(ctx, project)
if err != nil {
return errGroup, derivedCtx, err
}
for _, subName := range subscriptions {
sub := client.subscription(subName)
errGroup.Go(func() error {
logrus.Infof("Listening for subscription %s on project %s", sub.string(), project)
defer logrus.Warnf("Stopped Listening for subscription %s on project %s", sub.string(), project)
err := sub.receive(derivedCtx, func(ctx context.Context, msg messageInterface) {
if err = s.Subscriber.handleMessage(msg, sub.string()); err != nil {
s.Subscriber.Metrics.ACKMessageCounter.With(prometheus.Labels{subscriptionLabel: sub.string()}).Inc()
} else {
s.Subscriber.Metrics.NACKMessageCounter.With(prometheus.Labels{subscriptionLabel: sub.string()}).Inc()
}
msg.ack()
})
if err != nil {
logrus.WithError(err).Errorf("failed to listen for subscription %s on project %s", sub.string(), project)
return err
}
return nil
})
}
}
return errGroup, derivedCtx, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/overlay.go#L99-L101
|
func (p *HideHighlightParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandHideHighlight, nil, nil)
}
|
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/web/handlers.go#L71-L74
|
func (w *StatusResponseWriter) Write(data []byte) (int, error) {
w.length = len(data)
return w.ResponseWriter.Write(data)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/types.go#L899-L901
|
func (t *ReferrerPolicy) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
|
https://github.com/Knetic/govaluate/blob/9aa49832a739dcd78a5542ff189fb82c3e423116/TokenKind.go#L36-L75
|
func (kind TokenKind) String() string {
switch kind {
case PREFIX:
return "PREFIX"
case NUMERIC:
return "NUMERIC"
case BOOLEAN:
return "BOOLEAN"
case STRING:
return "STRING"
case PATTERN:
return "PATTERN"
case TIME:
return "TIME"
case VARIABLE:
return "VARIABLE"
case FUNCTION:
return "FUNCTION"
case SEPARATOR:
return "SEPARATOR"
case COMPARATOR:
return "COMPARATOR"
case LOGICALOP:
return "LOGICALOP"
case MODIFIER:
return "MODIFIER"
case CLAUSE:
return "CLAUSE"
case CLAUSE_CLOSE:
return "CLAUSE_CLOSE"
case TERNARY:
return "TERNARY"
case ACCESSOR:
return "ACCESSOR"
}
return "UNKNOWN"
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/lease/lessor.go#L586-L609
|
func (le *lessor) revokeExpiredLeases() {
var ls []*Lease
// rate limit
revokeLimit := leaseRevokeRate / 2
le.mu.RLock()
if le.isPrimary() {
ls = le.findExpiredLeases(revokeLimit)
}
le.mu.RUnlock()
if len(ls) != 0 {
select {
case <-le.stopC:
return
case le.expiredC <- ls:
default:
// the receiver of expiredC is probably busy handling
// other stuff
// let's try this next time after 500ms
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.