_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4002-L4010
|
func (u OperationResultTr) MustPaymentResult() PaymentResult {
val, ok := u.GetPaymentResult()
if !ok {
panic("arm PaymentResult is not set")
}
return val
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peers.go#L308-L316
|
func (peers *Peers) fetchAndAddRef(name PeerName) *Peer {
peers.Lock()
defer peers.Unlock()
peer := peers.byName[name]
if peer != nil {
peer.localRefCount++
}
return peer
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/node.go#L481-L508
|
func nodeHealingUpdate(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
poolName := InputValue(r, "pool")
var ctxs []permTypes.PermissionContext
if poolName != "" {
ctxs = append(ctxs, permission.Context(permTypes.CtxPool, poolName))
}
if !permission.Check(t, permission.PermHealingUpdate, ctxs...) {
return permission.ErrUnauthorized
}
evt, err := event.New(&event.Opts{
Target: event.Target{Type: event.TargetTypePool, Value: poolName},
Kind: permission.PermHealingUpdate,
Owner: t,
CustomData: event.FormToCustomData(InputFields(r)),
DisableLock: true,
Allowed: event.Allowed(permission.PermPoolReadEvents, ctxs...),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
var config healer.NodeHealerConfig
err = ParseInput(r, &config)
if err != nil {
return err
}
return healer.UpdateConfig(poolName, config)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L945-L970
|
func (c *ClusterTx) ContainerPool(project, containerName string) (string, error) {
// Get container storage volume. Since container names are globally
// unique, and their storage volumes carry the same name, their storage
// volumes are unique too.
poolName := ""
query := `
SELECT storage_pools.name FROM storage_pools
JOIN storage_volumes ON storage_pools.id=storage_volumes.storage_pool_id
JOIN containers ON containers.name=storage_volumes.name
JOIN projects ON projects.id=containers.project_id
WHERE projects.name=? AND storage_volumes.node_id=? AND storage_volumes.name=? AND storage_volumes.type=?
`
inargs := []interface{}{project, c.nodeID, containerName, StoragePoolVolumeTypeContainer}
outargs := []interface{}{&poolName}
err := c.tx.QueryRow(query, inargs...).Scan(outargs...)
if err != nil {
if err == sql.ErrNoRows {
return "", ErrNoSuchObject
}
return "", err
}
return poolName, nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/uuid/uuid.go#L14-L28
|
func New() string {
var result string
backoff.RetryNotify(func() error {
uuid, err := uuid.NewV4()
if err != nil {
return err
}
result = uuid.String()
return nil
}, backoff.NewInfiniteBackOff(), func(err error, d time.Duration) error {
fmt.Printf("error from uuid.NewV4: %v", err)
return nil
})
return result
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/auth.go#L170-L177
|
func (s *cookieSigner) refresh(resp *http.Response) error {
if resp.StatusCode != 204 {
return fmt.Errorf("Authentication failed: %s", resp.Status)
}
s.cookies = resp.Cookies()
s.refreshAt = time.Now().Add(time.Duration(2) * time.Hour)
return nil
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer_heap.go#L66-L73
|
func (ph *peerHeap) Pop() interface{} {
old := *ph
n := len(old.peerScores)
item := old.peerScores[n-1]
item.index = -1 // for safety
ph.peerScores = old.peerScores[:n-1]
return item
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L367-L376
|
func (c APIClient) DeleteBranch(repoName string, branch string, force bool) error {
_, err := c.PfsAPIClient.DeleteBranch(
c.Ctx(),
&pfs.DeleteBranchRequest{
Branch: NewBranch(repoName, branch),
Force: force,
},
)
return grpcutil.ScrubGRPC(err)
}
|
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/apis/cluster/cluster.go#L254-L265
|
func NewCluster(name string) *Cluster {
return &Cluster{
Name: name,
ClusterAPI: &clusterv1.Cluster{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Spec: clusterv1.ClusterSpec{},
},
ControlPlane: &clusterv1.MachineSet{},
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/overlay.go#L274-L276
|
func (p *HighlightRectParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandHighlightRect, p, nil)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/accessibility/types.go#L134-L136
|
func (t ValueSourceType) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/fossapps/pushy/blob/4c6045d7a1d3c310d61168ff1ccd5421d5c162f6/pushy.go#L84-L94
|
func (p *Pushy) SubscribeToTopic(deviceID string, topics ...string) (*SimpleSuccess, *Error, error) {
url := fmt.Sprintf("%s/devices/subscribe?api_key=%s", p.APIEndpoint, p.APIToken)
request := DeviceSubscriptionRequest{
Token: deviceID,
Topics: topics,
}
var success *SimpleSuccess
var pushyErr *Error
err := post(p.httpClient, url, request, &success, &pushyErr)
return success, pushyErr, err
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L1979-L1987
|
func (u OperationBody) MustChangeTrustOp() ChangeTrustOp {
val, ok := u.GetChangeTrustOp()
if !ok {
panic("arm ChangeTrustOp is not set")
}
return val
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/capabilities.go#L80-L83
|
func (c Capabilities) Without(feature string) Capabilities {
c[feature] = false
return c
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L127-L130
|
func (p CallFunctionOnParams) WithReturnByValue(returnByValue bool) *CallFunctionOnParams {
p.ReturnByValue = returnByValue
return &p
}
|
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/log_adapter.go#L210-L212
|
func (la *LogAdapter) Errf(msg string, a ...interface{}) error {
return la.Errorf(msg, a...)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/pfsdb/pfsdb.go#L28-L37
|
func Repos(etcdClient *etcd.Client, etcdPrefix string) col.Collection {
return col.NewCollection(
etcdClient,
path.Join(etcdPrefix, reposPrefix),
nil,
&pfs.RepoInfo{},
nil,
nil,
)
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/xmpp/xmpp.go#L86-L94
|
func Handle(f func(c context.Context, m *Message)) {
http.HandleFunc("/_ah/xmpp/message/chat/", func(_ http.ResponseWriter, r *http.Request) {
f(appengine.NewContext(r), &Message{
Sender: r.FormValue("from"),
To: []string{r.FormValue("to")},
Body: r.FormValue("body"),
})
})
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/jenkins/jenkins.go#L340-L346
|
func (c *Client) Get(path string) ([]byte, error) {
resp, err := c.request(http.MethodGet, path, nil, true)
if err != nil {
return nil, err
}
return readResp(resp)
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L482-L486
|
func (mat *SparseMat) Clone() *SparseMat {
mat_c := (*C.CvSparseMat)(mat)
mat_ret := C.cvCloneSparseMat(mat_c)
return (*SparseMat)(mat_ret)
}
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/api.go#L23-L25
|
func (api *Api) Use(middlewares ...Middleware) {
api.stack = append(api.stack, middlewares...)
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/manage_offer.go#L27-L29
|
func DeleteOffer(rate Rate, offerID OfferID) (result ManageOfferBuilder) {
return ManageOffer(false, rate, Amount("0"), offerID)
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cv.go#L183-L192
|
func CreateStructuringElement(cols, rows, anchor_x, anchor_y, shape int) *IplConvKernel {
return (*IplConvKernel)(C.cvCreateStructuringElementEx(
C.int(cols),
C.int(rows),
C.int(anchor_x),
C.int(anchor_y),
C.int(shape),
nil, // TODO: currently we don't support a fully custom kernel
))
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/praxisgen/api_analyzer.go#L29-L37
|
func NewAPIAnalyzer(version, clientName string, resources, types map[string]map[string]interface{}) *APIAnalyzer {
return &APIAnalyzer{
RawResources: resources,
RawTypes: types,
Version: version,
ClientName: clientName,
Registry: NewTypeRegistry(),
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logger/log.go#L48-L52
|
func Warn(msg string, ctx ...interface{}) {
if Log != nil {
Log.Warn(msg, ctx...)
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/layertree/layertree.go#L194-L197
|
func (p ProfileSnapshotParams) WithClipRect(clipRect *dom.Rect) *ProfileSnapshotParams {
p.ClipRect = clipRect
return &p
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/raft.go#L1394-L1397
|
func (r *raft) promotable() bool {
_, ok := r.prs[r.id]
return ok
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/pfs.go#L121-L126
|
func IsCommitDeletedErr(err error) bool {
if err == nil {
return false
}
return commitDeletedRe.MatchString(grpcutil.ScrubGRPC(err).Error())
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L5168-L5172
|
func (v EventWebSocketWillSendHandshakeRequest) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork40(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/checkconfig/main.go#L653-L693
|
func (c *orgRepoConfig) union(c2 *orgRepoConfig) *orgRepoConfig {
res := &orgRepoConfig{
orgExceptions: make(map[string]sets.String),
repos: sets.NewString(),
}
for org, excepts1 := range c.orgExceptions {
// keep only items in both blacklists that are not in the
// explicit repo whitelists for the other configuration;
// we know from how the orgRepoConfigs are constructed that
// a org blacklist won't intersect it's own repo whitelist
pruned := excepts1.Difference(c2.repos)
if excepts2, ok := c2.orgExceptions[org]; ok {
res.orgExceptions[org] = pruned.Intersection(excepts2.Difference(c.repos))
} else {
res.orgExceptions[org] = pruned
}
}
for org, excepts2 := range c2.orgExceptions {
// update any blacklists not previously updated
if _, exists := res.orgExceptions[org]; !exists {
res.orgExceptions[org] = excepts2.Difference(c.repos)
}
}
// we need to prune out repos in the whitelists which are
// covered by an org already; we know from above that no
// org blacklist in the result will contain a repo whitelist
for _, repo := range c.repos.Union(c2.repos).UnsortedList() {
parts := strings.SplitN(repo, "/", 2)
if len(parts) != 2 {
logrus.Warnf("org/repo %q is formatted incorrectly", repo)
continue
}
if _, exists := res.orgExceptions[parts[0]]; !exists {
res.repos.Insert(repo)
}
}
return res
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer_heap.go#L111-L117
|
func (ph *peerHeap) addPeer(peerScore *peerScore) {
ph.pushPeer(peerScore)
// Pick a random element, and swap the order with that peerScore.
r := ph.rng.Intn(ph.Len())
ph.swapOrder(peerScore.index, r)
}
|
https://github.com/geoffgarside/ber/blob/27a1aff36ce64dbe5d93c08cc5f161983134ddc5/ber.go#L34-L53
|
func parseBool(bytes []byte) (ret bool, err error) {
if len(bytes) != 1 {
err = asn1.SyntaxError{Msg: "invalid boolean"}
return
}
// DER demands that "If the encoding represents the boolean value TRUE,
// its single contents octet shall have all eight bits set to one."
// Thus only 0 and 255 are valid encoded values.
switch bytes[0] {
case 0:
ret = false
case 0xff:
ret = true
default:
err = asn1.SyntaxError{Msg: "invalid boolean"}
}
return
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peers.go#L409-L415
|
func (peers *Peers) GarbageCollect() {
peers.Lock()
var pending peersPendingNotifications
defer peers.unlockAndNotify(&pending)
peers.garbageCollect(&pending)
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L425-L436
|
func (kt *sbKeyType) UnmarshalJSON(data []byte) error {
*kt = sbKeyType("")
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
if !sbKeyType(s).IsValid() {
return InvalidPolicyFormatError(fmt.Sprintf("Unrecognized keyType value \"%s\"", s))
}
*kt = sbKeyType(s)
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L595-L599
|
func (v *StyleDeclarationEdit) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss4(&r, v)
return r.Error()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/buildifier/buildifier.go#L127-L150
|
func problemsInFiles(r *git.Repo, files map[string]string) (map[string][]string, error) {
problems := make(map[string][]string)
for f := range files {
src, err := ioutil.ReadFile(filepath.Join(r.Dir, f))
if err != nil {
return nil, err
}
// This is modeled after the logic from buildifier:
// https://github.com/bazelbuild/buildtools/blob/8818289/buildifier/buildifier.go#L261
content, err := build.Parse(f, src)
if err != nil {
return nil, fmt.Errorf("parsing as Bazel file %v", err)
}
beforeRewrite := build.Format(content)
var info build.RewriteInfo
build.Rewrite(content, &info)
ndata := build.Format(content)
if !bytes.Equal(src, ndata) && !bytes.Equal(src, beforeRewrite) {
// TODO(mattmoor): This always seems to be empty?
problems[f] = uniqProblems(info.Log)
}
}
return problems, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/cluster_util.go#L151-L176
|
func getVersions(lg *zap.Logger, cl *membership.RaftCluster, local types.ID, rt http.RoundTripper) map[string]*version.Versions {
members := cl.Members()
vers := make(map[string]*version.Versions)
for _, m := range members {
if m.ID == local {
cv := "not_decided"
if cl.Version() != nil {
cv = cl.Version().String()
}
vers[m.ID.String()] = &version.Versions{Server: version.Version, Cluster: cv}
continue
}
ver, err := getVersion(lg, m, rt)
if err != nil {
if lg != nil {
lg.Warn("failed to get version", zap.String("remote-member-id", m.ID.String()), zap.Error(err))
} else {
plog.Warningf("cannot get the version of member %s (%v)", m.ID, err)
}
vers[m.ID.String()] = nil
} else {
vers[m.ID.String()] = ver
}
}
return vers
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/genfiles/genfiles.go#L174-L198
|
func (g *Group) Match(path string) bool {
if g.Paths[path] {
return true
}
for prefix := range g.PathPrefixes {
if strings.HasPrefix(path, prefix) {
return true
}
}
base := filepath.Base(path)
if g.FileNames[base] {
return true
}
for prefix := range g.FilePrefixes {
if strings.HasPrefix(base, prefix) {
return true
}
}
return false
}
|
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/string.go#L26-L31
|
func StringFromPtr(s *string) String {
if s == nil {
return NewString("", false)
}
return NewString(*s, true)
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/raw/handler.go#L87-L106
|
func Wrap(handler Handler) tchannel.Handler {
return tchannel.HandlerFunc(func(ctx context.Context, call *tchannel.InboundCall) {
args, err := ReadArgs(call)
if err != nil {
handler.OnError(ctx, err)
return
}
resp, err := handler.Handle(ctx, args)
response := call.Response()
if err != nil {
resp = &Res{
SystemErr: err,
}
}
if err := WriteResponse(response, resp); err != nil {
handler.OnError(ctx, err)
}
})
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cachestorage/cachestorage.go#L33-L35
|
func (p *DeleteCacheParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandDeleteCache, p, nil)
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nitro.go#L485-L499
|
func (m *Nitro) NewWriter() *Writer {
w := m.newWriter()
w.next = m.wlist
m.wlist = w
w.dwrCtx.Init()
m.shutdownWg1.Add(1)
go m.collectionWorker(w)
if m.useMemoryMgmt {
m.shutdownWg2.Add(1)
go m.freeWorker(w)
}
return w
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/fetcher/client.go#L130-L132
|
func (client *Client) RepositoryName() string {
return fmt.Sprintf("%s/%s", client.Org, client.Project)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/database/easyjson.go#L345-L349
|
func (v *ExecuteSQLReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDatabase2(&r, v)
return r.Error()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/kube/dry_run_client.go#L65-L67
|
func (c *dryRunProwJobClient) Delete(name string, options *metav1.DeleteOptions) error {
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/expect/expect.go#L134-L136
|
func (ep *ExpectProcess) Signal(sig os.Signal) error {
return ep.cmd.Process.Signal(sig)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/proxy/grpcproxy/cache/store.go#L74-L109
|
func (c *cache) Add(req *pb.RangeRequest, resp *pb.RangeResponse) {
key := keyFunc(req)
c.mu.Lock()
defer c.mu.Unlock()
if req.Revision > c.compactedRev {
c.lru.Add(key, resp)
}
// we do not need to invalidate a request with a revision specified.
// so we do not need to add it into the reverse index.
if req.Revision != 0 {
return
}
var (
iv *adt.IntervalValue
ivl adt.Interval
)
if len(req.RangeEnd) != 0 {
ivl = adt.NewStringAffineInterval(string(req.Key), string(req.RangeEnd))
} else {
ivl = adt.NewStringAffinePoint(string(req.Key))
}
iv = c.cachedRanges.Find(ivl)
if iv == nil {
val := map[string]struct{}{key: {}}
c.cachedRanges.Insert(ivl, val)
} else {
val := iv.Val.(map[string]struct{})
val[key] = struct{}{}
iv.Val = val
}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pps/server/api_server.go#L377-L468
|
func (a *apiServer) authorizePipelineOp(pachClient *client.APIClient, operation pipelineOperation, input *pps.Input, output string) error {
ctx := pachClient.Ctx()
me, err := pachClient.WhoAmI(ctx, &auth.WhoAmIRequest{})
if auth.IsErrNotActivated(err) {
return nil // Auth isn't activated, skip authorization completely
} else if err != nil {
return err
}
if input != nil {
// Check that the user is authorized to read all input repos, and write to the
// output repo (which the pipeline needs to be able to do on the user's
// behalf)
var eg errgroup.Group
done := make(map[string]struct{}) // don't double-authorize repos
pps.VisitInput(input, func(in *pps.Input) {
var repo string
if in.Pfs != nil {
repo = in.Pfs.Repo
} else {
return
}
if _, ok := done[repo]; ok {
return
}
done[repo] = struct{}{}
eg.Go(func() error {
resp, err := pachClient.Authorize(ctx, &auth.AuthorizeRequest{
Repo: repo,
Scope: auth.Scope_READER,
})
if err != nil {
return err
}
if !resp.Authorized {
return &auth.ErrNotAuthorized{
Subject: me.Username,
Repo: repo,
Required: auth.Scope_READER,
}
}
return nil
})
})
if err := eg.Wait(); err != nil {
return err
}
}
// Check that the user is authorized to write to the output repo.
// Note: authorizePipelineOp is called before CreateRepo creates a
// PipelineInfo proto in etcd, so PipelineManager won't have created an output
// repo yet, and it's possible to check that the output repo doesn't exist
// (if it did exist, we'd have to check that the user has permission to write
// to it, and this is simpler)
var required auth.Scope
switch operation {
case pipelineOpCreate:
if _, err := pachClient.InspectRepo(output); err == nil {
return fmt.Errorf("cannot overwrite repo \"%s\" with new output repo", output)
} else if !isNotFoundErr(err) {
return err
}
case pipelineOpListDatum, pipelineOpGetLogs:
required = auth.Scope_READER
case pipelineOpUpdate:
required = auth.Scope_WRITER
case pipelineOpDelete:
required = auth.Scope_OWNER
default:
return fmt.Errorf("internal error, unrecognized operation %v", operation)
}
if required != auth.Scope_NONE {
resp, err := pachClient.Authorize(ctx, &auth.AuthorizeRequest{
Repo: output,
Scope: required,
})
if err != nil {
return err
}
if !resp.Authorized {
return &auth.ErrNotAuthorized{
Subject: me.Username,
Repo: output,
Required: required,
}
}
}
return nil
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/internal/mail/message.go#L247-L251
|
func SetPartEncoding(e Encoding) PartSetting {
return PartSetting(func(p *part) {
p.encoding = e
})
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2stats/queue.go#L52-L59
|
func (q *statsQueue) frontAndBack() (*RequestStats, *RequestStats) {
q.rwl.RLock()
defer q.rwl.RUnlock()
if q.size != 0 {
return q.items[q.front], q.items[q.back]
}
return nil, nil
}
|
https://github.com/Knetic/govaluate/blob/9aa49832a739dcd78a5542ff189fb82c3e423116/stagePlanner.go#L666-L724
|
func elideStage(root *evaluationStage) *evaluationStage {
var leftValue, rightValue, result interface{}
var err error
// right side must be a non-nil value. Left side must be nil or a value.
if root.rightStage == nil ||
root.rightStage.symbol != LITERAL ||
root.leftStage == nil ||
root.leftStage.symbol != LITERAL {
return root
}
// don't elide some operators
switch root.symbol {
case SEPARATE:
fallthrough
case IN:
return root
}
// both sides are values, get their actual values.
// errors should be near-impossible here. If we encounter them, just abort this optimization.
leftValue, err = root.leftStage.operator(nil, nil, nil)
if err != nil {
return root
}
rightValue, err = root.rightStage.operator(nil, nil, nil)
if err != nil {
return root
}
// typcheck, since the grammar checker is a bit loose with which operator symbols go together.
err = typeCheck(root.leftTypeCheck, leftValue, root.symbol, root.typeErrorFormat)
if err != nil {
return root
}
err = typeCheck(root.rightTypeCheck, rightValue, root.symbol, root.typeErrorFormat)
if err != nil {
return root
}
if root.typeCheck != nil && !root.typeCheck(leftValue, rightValue) {
return root
}
// pre-calculate, and return a new stage representing the result.
result, err = root.operator(leftValue, rightValue, nil)
if err != nil {
return root
}
return &evaluationStage{
symbol: LITERAL,
operator: makeLiteralStage(result),
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cdp/types.go#L654-L656
|
func (t *FrameID) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/sysregistriesv2/system_registries_v2.go#L415-L425
|
func loadRegistryConf(configPath string) (*tomlConfig, error) {
config := &tomlConfig{}
configBytes, err := readConf(configPath)
if err != nil {
return nil, err
}
err = toml.Unmarshal(configBytes, &config)
return config, err
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcec2manager/tcec2manager.go#L92-L96
|
func (eC2Manager *EC2Manager) ListWorkerTypes() (*ListOfWorkerTypes, error) {
cd := tcclient.Client(*eC2Manager)
responseObject, _, err := (&cd).APICall(nil, "GET", "/worker-types", new(ListOfWorkerTypes), nil)
return responseObject.(*ListOfWorkerTypes), err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domsnapshot/easyjson.go#L2794-L2798
|
func (v DOMNode) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDomsnapshot12(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_image_src.go#L60-L115
|
func newImageSource(ctx context.Context, sys *types.SystemContext, ref dockerReference) (*dockerImageSource, error) {
registry, err := sysregistriesv2.FindRegistry(sys, ref.ref.Name())
if err != nil {
return nil, errors.Wrapf(err, "error loading registries configuration")
}
if registry == nil {
// No configuration was found for the provided reference, so we create
// a fallback registry by hand to make the client creation below work
// as intended.
registry = &sysregistriesv2.Registry{
Endpoint: sysregistriesv2.Endpoint{
Location: ref.ref.String(),
},
}
}
// Found the registry within the sysregistriesv2 configuration. Now we test
// all endpoints for the manifest availability. If a working image source
// was found, it will be used for all future pull actions.
var (
imageSource *dockerImageSource
manifestLoadErr error
)
for _, endpoint := range append(registry.Mirrors, registry.Endpoint) {
logrus.Debugf("Trying to pull %q from endpoint %q", ref.ref, endpoint.Location)
newRef, err := endpoint.RewriteReference(ref.ref, registry.Prefix)
if err != nil {
return nil, err
}
dockerRef, err := newReference(newRef)
if err != nil {
return nil, err
}
client, err := newDockerClientFromRef(sys, dockerRef, false, "pull")
if err != nil {
return nil, err
}
client.tlsClientConfig.InsecureSkipVerify = endpoint.Insecure
testImageSource := &dockerImageSource{
ref: dockerRef,
c: client,
}
manifestLoadErr = testImageSource.ensureManifestIsLoaded(ctx)
if manifestLoadErr == nil {
imageSource = testImageSource
break
}
}
return imageSource, manifestLoadErr
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/core/read.go#L78-L93
|
func (p *Process) ReadUint64(a Address) uint64 {
m := p.findMapping(a)
if m == nil {
panic(fmt.Errorf("address %x is not mapped in the core file", a))
}
b := m.contents[a.Sub(m.min):]
if len(b) < 8 {
var buf [8]byte
b = buf[:]
p.ReadAt(b, a)
}
if p.littleEndian {
return binary.LittleEndian.Uint64(b)
}
return binary.BigEndian.Uint64(b)
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/main.go#L182-L185
|
func (pathSend PayWithPath) Through(asset Asset) PayWithPath {
pathSend.Path = append(pathSend.Path, asset)
return pathSend
}
|
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/consumer.go#L539-L557
|
func (c *Consumer) heartbeat() error {
broker, err := c.client.Coordinator(c.groupID)
if err != nil {
c.closeCoordinator(broker, err)
return err
}
memberID, generationID := c.membership()
resp, err := broker.Heartbeat(&sarama.HeartbeatRequest{
GroupId: c.groupID,
MemberId: memberID,
GenerationId: generationID,
})
if err != nil {
c.closeCoordinator(broker, err)
return err
}
return resp.Err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/easyjson.go#L1077-L1081
|
func (v EventWorkerRegistrationUpdated) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoServiceworker11(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/emulation.go#L394-L397
|
func (p SetGeolocationOverrideParams) WithLongitude(longitude float64) *SetGeolocationOverrideParams {
p.Longitude = longitude
return &p
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/jenkins/jenkins.go#L569-L593
|
func (c *Client) LaunchBuild(spec *prowapi.ProwJobSpec, params url.Values) error {
var path string
if params != nil {
path = getBuildWithParametersPath(spec)
} else {
path = getBuildPath(spec)
}
c.logger.Debugf("getBuildPath/getBuildWithParametersPath: %s", path)
resp, err := c.request(http.MethodPost, path, params, true)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 201 {
return fmt.Errorf("response not 201: %s", resp.Status)
}
return nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/logrusutil/logrusutil.go#L50-L65
|
func (d *DefaultFieldsFormatter) Format(entry *logrus.Entry) ([]byte, error) {
data := make(logrus.Fields, len(entry.Data)+len(d.DefaultFields))
for k, v := range d.DefaultFields {
data[k] = v
}
for k, v := range entry.Data {
data[k] = v
}
return d.WrappedFormatter.Format(&logrus.Entry{
Logger: entry.Logger,
Data: data,
Time: entry.Time,
Level: entry.Level,
Message: entry.Message,
})
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/apps/delete_apps_app_parameters.go#L77-L80
|
func (o *DeleteAppsAppParams) WithTimeout(timeout time.Duration) *DeleteAppsAppParams {
o.SetTimeout(timeout)
return o
}
|
https://github.com/armon/go-radix/blob/1a2de0c21c94309923825da3df33a4381872c795/radix.go#L147-L233
|
func (t *Tree) Insert(s string, v interface{}) (interface{}, bool) {
var parent *node
n := t.root
search := s
for {
// Handle key exhaution
if len(search) == 0 {
if n.isLeaf() {
old := n.leaf.val
n.leaf.val = v
return old, true
}
n.leaf = &leafNode{
key: s,
val: v,
}
t.size++
return nil, false
}
// Look for the edge
parent = n
n = n.getEdge(search[0])
// No edge, create one
if n == nil {
e := edge{
label: search[0],
node: &node{
leaf: &leafNode{
key: s,
val: v,
},
prefix: search,
},
}
parent.addEdge(e)
t.size++
return nil, false
}
// Determine longest prefix of the search key on match
commonPrefix := longestPrefix(search, n.prefix)
if commonPrefix == len(n.prefix) {
search = search[commonPrefix:]
continue
}
// Split the node
t.size++
child := &node{
prefix: search[:commonPrefix],
}
parent.updateEdge(search[0], child)
// Restore the existing node
child.addEdge(edge{
label: n.prefix[commonPrefix],
node: n,
})
n.prefix = n.prefix[commonPrefix:]
// Create a new leaf node
leaf := &leafNode{
key: s,
val: v,
}
// If the new key is a subset, add to to this node
search = search[commonPrefix:]
if len(search) == 0 {
child.leaf = leaf
return nil, false
}
// Create a new edge for the node
child.addEdge(edge{
label: search[0],
node: &node{
leaf: leaf,
prefix: search,
},
})
return nil, false
}
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L266-L276
|
func (g *Glg) SetMode(mode MODE) *Glg {
g.logger.Range(func(key, val interface{}) bool {
l := val.(*logger)
l.mode = mode
l.updateMode()
g.logger.Store(key.(LEVEL), l)
return true
})
return g
}
|
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/fakes/fake.go#L377-L379
|
func (s *FakeCollection) UpsertID(id interface{}, result interface{}) (changInfo *mgo.ChangeInfo, err error) {
return
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/file.go#L19-L31
|
func NewFileTemplateFetcher(paths []string) (*FileTemplateFetcher, error) {
l := &FileTemplateFetcher{
Paths: make([]string, len(paths)),
}
for k, v := range paths {
abs, err := filepath.Abs(v)
if err != nil {
return nil, err
}
l.Paths[k] = abs
}
return l, nil
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/core/process.go#L91-L97
|
func (p *Process) Writeable(a Address) bool {
m := p.findMapping(a)
if m == nil {
return false
}
return m.perm&Write != 0
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/multiselection.go#L27-L29
|
func (s *MultiSelection) At(index int) *Selection {
return newSelection(s.session, s.selectors.At(index))
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/commands.go#L392-L422
|
func (a *API) findParamAndValue(action *metadata.Action, flag string) (*metadata.ActionParam, string, error) {
elems := strings.SplitN(flag, "=", 2)
if len(elems) != 2 {
return nil, "", fmt.Errorf("Arguments must be of the form NAME=VALUE, value provided was '%s'", flag)
}
name := elems[0]
value := elems[1]
var param *metadata.ActionParam
for _, ap := range action.CommandFlags {
if ap.Name == name {
param = ap
break
}
}
if param == nil && strings.Contains(name, "[") {
// Handle enumerable case
name = name[:strings.LastIndex(name, "[")]
for _, ap := range action.CommandFlags {
if ap.Name == name {
param = ap
es := captureEnumRegex.FindStringSubmatch(elems[0])
if es == nil {
return nil, "", fmt.Errorf("Key/value arguments must be of the form NAME[KEY]=VALUE, value provided was '%s'", flag)
}
value = es[1] + "=" + value
break
}
}
}
return param, value, nil
}
|
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/xmltree/xmltree.go#L34-L42
|
func MustParseXML(r io.Reader, op ...ParseSettings) tree.Node {
ret, err := ParseXML(r, op...)
if err != nil {
panic(err)
}
return ret
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/module.go#L103-L107
|
func (t *funcTab) sort() {
sort.Slice(t.entries, func(i, j int) bool {
return t.entries[i].min < t.entries[j].min
})
}
|
https://github.com/go-audio/transforms/blob/51830ccc35a5ce4be9d09b1d1f3f82dad376c240/stereo.go#L8-L23
|
func MonoToStereoF32(buf *audio.Float32Buffer) error {
if buf == nil || buf.Format == nil || buf.Format.NumChannels != 1 {
return audio.ErrInvalidBuffer
}
stereoData := make([]float32, len(buf.Data)*2)
var j int
for i := 0; i < len(buf.Data); i++ {
stereoData[j] = buf.Data[i]
j++
stereoData[j] = buf.Data[i]
j++
}
buf.Data = stereoData
buf.Format.NumChannels = 2
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/easyjson.go#L968-L972
|
func (v *GetSamplingProfileParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoHeapprofiler10(&r, v)
return r.Error()
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/callbacks.go#L155-L181
|
func TimestampValidator() *Callback {
return C("fire/TimestampValidator", Only(Create, Update), func(ctx *Context) error {
// get time
now := time.Now()
// get timestamp fields
ctf := coal.L(ctx.Model, "fire-created-timestamp", false)
utf := coal.L(ctx.Model, "fire-updated-timestamp", false)
// set created timestamp on creation and set missing create timestamps
// to the timestamp inferred from the model id
if ctf != "" {
if ctx.Operation == Create {
ctx.Model.MustSet(ctf, now)
} else if t := ctx.Model.MustGet(ctf).(time.Time); t.IsZero() {
ctx.Model.MustSet(ctf, ctx.Model.ID().Time())
}
}
// always set updated timestamp
if utf != "" {
ctx.Model.MustSet(utf, now)
}
return nil
})
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L1997-L2001
|
func (v *SetMediaTextParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss18(&r, v)
return r.Error()
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5744-L5752
|
func (u LedgerEntryChange) MustCreated() LedgerEntry {
val, ok := u.GetCreated()
if !ok {
panic("arm Created is not set")
}
return val
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L255-L261
|
func (l *PeerList) getPeerScore(hostPort string) (*peerScore, uint64, bool) {
ps, ok := l.peersByHostPort[hostPort]
if !ok {
return nil, 0, false
}
return ps, ps.score, ok
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/skiplist/skiplist.go#L339-L345
|
func (s *Skiplist) DeleteNode(n *Node, cmp CompareFn,
buf *ActionBuffer, sts *Stats) bool {
token := s.barrier.Acquire()
defer s.barrier.Release(token)
return s.deleteNode(n, cmp, buf, sts)
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/iterator.go#L465-L467
|
func (it *Iterator) ValidForPrefix(prefix []byte) bool {
return it.Valid() && bytes.HasPrefix(it.item.key, prefix)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/snap/snapshotter.go#L152-L215
|
func Read(lg *zap.Logger, snapname string) (*raftpb.Snapshot, error) {
b, err := ioutil.ReadFile(snapname)
if err != nil {
if lg != nil {
lg.Warn("failed to read a snap file", zap.String("path", snapname), zap.Error(err))
} else {
plog.Errorf("cannot read file %v: %v", snapname, err)
}
return nil, err
}
if len(b) == 0 {
if lg != nil {
lg.Warn("failed to read empty snapshot file", zap.String("path", snapname))
} else {
plog.Errorf("unexpected empty snapshot")
}
return nil, ErrEmptySnapshot
}
var serializedSnap snappb.Snapshot
if err = serializedSnap.Unmarshal(b); err != nil {
if lg != nil {
lg.Warn("failed to unmarshal snappb.Snapshot", zap.String("path", snapname), zap.Error(err))
} else {
plog.Errorf("corrupted snapshot file %v: %v", snapname, err)
}
return nil, err
}
if len(serializedSnap.Data) == 0 || serializedSnap.Crc == 0 {
if lg != nil {
lg.Warn("failed to read empty snapshot data", zap.String("path", snapname))
} else {
plog.Errorf("unexpected empty snapshot")
}
return nil, ErrEmptySnapshot
}
crc := crc32.Update(0, crcTable, serializedSnap.Data)
if crc != serializedSnap.Crc {
if lg != nil {
lg.Warn("snap file is corrupt",
zap.String("path", snapname),
zap.Uint32("prev-crc", serializedSnap.Crc),
zap.Uint32("new-crc", crc),
)
} else {
plog.Errorf("corrupted snapshot file %v: crc mismatch", snapname)
}
return nil, ErrCRCMismatch
}
var snap raftpb.Snapshot
if err = snap.Unmarshal(serializedSnap.Data); err != nil {
if lg != nil {
lg.Warn("failed to unmarshal raftpb.Snapshot", zap.String("path", snapname), zap.Error(err))
} else {
plog.Errorf("corrupted snapshot file %v: %v", snapname, err)
}
return nil, err
}
return &snap, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/plugins/bundle.go#L67-L77
|
func (b BundledStates) ages(t time.Time) map[string]time.Duration {
ages := map[string]time.Duration{}
for id, state := range b.states {
if !state.Active() {
continue
}
ages[id] = state.Age(t)
}
return ages
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tethering/easyjson.go#L235-L239
|
func (v *BindParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoTethering2(&r, v)
return r.Error()
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/wal/util.go#L41-L57
|
func searchIndex(lg *zap.Logger, names []string, index uint64) (int, bool) {
for i := len(names) - 1; i >= 0; i-- {
name := names[i]
_, curIndex, err := parseWALName(name)
if err != nil {
if lg != nil {
lg.Panic("failed to parse WAL file name", zap.String("path", name), zap.Error(err))
} else {
plog.Panicf("parse correct name should never fail: %v", err)
}
}
if index >= curIndex {
return i, true
}
}
return -1, false
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/fsm.go#L49-L136
|
func (r *Raft) runFSM() {
var lastIndex, lastTerm uint64
commit := func(req *commitTuple) {
// Apply the log if a command
var resp interface{}
if req.log.Type == LogCommand {
start := time.Now()
resp = r.fsm.Apply(req.log)
metrics.MeasureSince([]string{"raft", "fsm", "apply"}, start)
}
// Update the indexes
lastIndex = req.log.Index
lastTerm = req.log.Term
// Invoke the future if given
if req.future != nil {
req.future.response = resp
req.future.respond(nil)
}
}
restore := func(req *restoreFuture) {
// Open the snapshot
meta, source, err := r.snapshots.Open(req.ID)
if err != nil {
req.respond(fmt.Errorf("failed to open snapshot %v: %v", req.ID, err))
return
}
// Attempt to restore
start := time.Now()
if err := r.fsm.Restore(source); err != nil {
req.respond(fmt.Errorf("failed to restore snapshot %v: %v", req.ID, err))
source.Close()
return
}
source.Close()
metrics.MeasureSince([]string{"raft", "fsm", "restore"}, start)
// Update the last index and term
lastIndex = meta.Index
lastTerm = meta.Term
req.respond(nil)
}
snapshot := func(req *reqSnapshotFuture) {
// Is there something to snapshot?
if lastIndex == 0 {
req.respond(ErrNothingNewToSnapshot)
return
}
// Start a snapshot
start := time.Now()
snap, err := r.fsm.Snapshot()
metrics.MeasureSince([]string{"raft", "fsm", "snapshot"}, start)
// Respond to the request
req.index = lastIndex
req.term = lastTerm
req.snapshot = snap
req.respond(err)
}
for {
select {
case ptr := <-r.fsmMutateCh:
switch req := ptr.(type) {
case *commitTuple:
commit(req)
case *restoreFuture:
restore(req)
default:
panic(fmt.Errorf("bad type passed to fsmMutateCh: %#v", ptr))
}
case req := <-r.fsmSnapshotCh:
snapshot(req)
case <-r.shutdownCh:
return
}
}
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/tarball/tarball_src.go#L217-L237
|
func (is *tarballImageSource) GetBlob(ctx context.Context, blobinfo types.BlobInfo, cache types.BlobInfoCache) (io.ReadCloser, int64, error) {
// We should only be asked about things in the manifest. Maybe the configuration blob.
if blobinfo.Digest == is.configID {
return ioutil.NopCloser(bytes.NewBuffer(is.config)), is.configSize, nil
}
// Maybe one of the layer blobs.
for i := range is.blobIDs {
if blobinfo.Digest == is.blobIDs[i] {
// We want to read that layer: open the file or memory block and hand it back.
if is.filenames[i] == "-" {
return ioutil.NopCloser(bytes.NewBuffer(is.reference.stdin)), int64(len(is.reference.stdin)), nil
}
reader, err := os.Open(is.filenames[i])
if err != nil {
return nil, -1, fmt.Errorf("error opening %q: %v", is.filenames[i], err)
}
return reader, is.blobSizes[i], nil
}
}
return nil, -1, fmt.Errorf("no blob with digest %q found", blobinfo.Digest.String())
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/bytecode.go#L11-L18
|
func NewByteCode() *ByteCode {
return &ByteCode{
GeneratedOn: time.Now(),
Name: "",
OpList: nil,
Version: 1.0,
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L363-L391
|
func (c *Client) requestRaw(r *request) (int, []byte, error) {
if c.fake || (c.dry && r.method != http.MethodGet) {
return r.exitCodes[0], nil, nil
}
resp, err := c.requestRetry(r.method, r.path, r.accept, r.requestBody)
if err != nil {
return 0, nil, err
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return 0, nil, err
}
var okCode bool
for _, code := range r.exitCodes {
if code == resp.StatusCode {
okCode = true
break
}
}
if !okCode {
clientError := unmarshalClientError(b)
err = requestError{
ClientError: clientError,
ErrorString: fmt.Sprintf("status code %d not one of %v, body: %s", resp.StatusCode, r.exitCodes, string(b)),
}
}
return resp.StatusCode, b, err
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5437-L5444
|
func NewTransactionHistoryResultEntryExt(v int32, value interface{}) (result TransactionHistoryResultEntryExt, err error) {
result.V = v
switch int32(v) {
case 0:
// void
}
return
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/ghproxy/ghcache/coalesce.go#L53-L135
|
func (r *requestCoalescer) RoundTrip(req *http.Request) (*http.Response, error) {
// Only coalesce GET requests
if req.Method != http.MethodGet {
return r.delegate.RoundTrip(req)
}
var cacheMode = ModeError
resp, err := func() (*http.Response, error) {
key := req.URL.String()
r.Lock()
waiter, ok := r.keys[key]
if ok {
// Earlier request in flight. Wait for it's response.
if req.Body != nil {
defer req.Body.Close() // Since we won't pass the request we must close it.
}
waiter.L.Lock()
r.Unlock()
waiter.waiting = true
// The documentation for Wait() says:
// "Because c.L is not locked when Wait first resumes, the caller typically
// cannot assume that the condition is true when Wait returns. Instead, the
// caller should Wait in a loop."
// This does not apply to this use of Wait() because the condition we are
// waiting for remains true once it becomes true. This lets us avoid the
// normal check to see if the condition has switched back to false between
// the signal being sent and this thread acquiring the lock.
waiter.Wait()
waiter.L.Unlock()
// Earlier request completed.
if waiter.err != nil {
// Don't log the error, it will be logged by requester.
return nil, waiter.err
}
resp, err := http.ReadResponse(bufio.NewReader(bytes.NewBuffer(waiter.resp)), nil)
if err != nil {
logrus.WithField("cache-key", key).WithError(err).Error("Error loading response.")
return nil, err
}
cacheMode = ModeCoalesced
return resp, nil
}
// No earlier request in flight (common case).
// Register a new responseWaiter and make the request ourself.
waiter = &responseWaiter{Cond: sync.NewCond(&sync.Mutex{})}
r.keys[key] = waiter
r.Unlock()
resp, err := r.delegate.RoundTrip(req)
// Real response received. Remove this responseWaiter from the map THEN
// wake any requesters that were waiting on this response.
r.Lock()
delete(r.keys, key)
r.Unlock()
waiter.L.Lock()
if waiter.waiting {
if err != nil {
waiter.resp, waiter.err = nil, err
} else {
// Copy the response before releasing to waiter(s).
waiter.resp, waiter.err = httputil.DumpResponse(resp, true)
}
waiter.Broadcast()
}
waiter.L.Unlock()
if err != nil {
logrus.WithField("cache-key", key).WithError(err).Error("Error from cache transport layer.")
return nil, err
}
cacheMode = cacheResponseMode(resp.Header)
return resp, nil
}()
cacheCounter.WithLabelValues(string(cacheMode)).Inc()
if resp != nil {
resp.Header.Set(CacheModeHeader, string(cacheMode))
}
return resp, err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L2516-L2520
|
func (v *AttachToTargetParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoTarget29(&r, v)
return r.Error()
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pkg/require/require.go#L61-L70
|
func NotEqual(tb testing.TB, expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
tb.Helper()
if reflect.DeepEqual(expected, actual) {
fatal(
tb,
msgAndArgs,
"Equal: %#v (expected)\n"+
" == %#v (actual)", expected, actual)
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/css.go#L548-L557
|
func (p *SetKeyframeKeyParams) Do(ctx context.Context) (keyText *Value, err error) {
// execute
var res SetKeyframeKeyReturns
err = cdp.Execute(ctx, CommandSetKeyframeKey, p, &res)
if err != nil {
return nil, err
}
return res.KeyText, nil
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/service_instance.go#L423-L461
|
func serviceInstance(w http.ResponseWriter, r *http.Request, t auth.Token) error {
instanceName := r.URL.Query().Get(":instance")
serviceName := r.URL.Query().Get(":service")
svc, err := getService(serviceName)
if err != nil {
return err
}
serviceInstance, err := getServiceInstanceOrError(serviceName, instanceName)
if err != nil {
return err
}
allowed := permission.Check(t, permission.PermServiceInstanceRead,
contextsForServiceInstance(serviceInstance, serviceName)...,
)
if !allowed {
return permission.ErrUnauthorized
}
requestID := requestIDHeader(r)
info, err := serviceInstance.Info(requestID)
if err != nil {
return err
}
plan, err := service.GetPlanByServiceAndPlanName(svc, serviceInstance.PlanName, requestID)
if err != nil {
return err
}
sInfo := serviceInstanceInfo{
Apps: serviceInstance.Apps,
Teams: serviceInstance.Teams,
TeamOwner: serviceInstance.TeamOwner,
Description: serviceInstance.Description,
PlanName: plan.Name,
PlanDescription: plan.Description,
CustomInfo: info,
Tags: serviceInstance.Tags,
}
w.Header().Set("Content-Type", "application/json")
return json.NewEncoder(w).Encode(sInfo)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/obj/obj.go#L429-L453
|
func NewClientFromURLAndSecret(url *ObjectStoreURL, reversed ...bool) (c Client, err error) {
switch url.Store {
case "s3":
c, err = NewAmazonClientFromSecret(url.Bucket, reversed...)
case "gcs":
fallthrough
case "gs":
c, err = NewGoogleClientFromSecret(url.Bucket)
case "as":
fallthrough
case "wasb":
// In Azure, the first part of the path is the container name.
c, err = NewMicrosoftClientFromSecret(url.Bucket)
case "local":
c, err = NewLocalClient("/" + url.Bucket)
}
switch {
case err != nil:
return nil, err
case c != nil:
return TracingObjClient(url.Store, c), nil
default:
return nil, fmt.Errorf("unrecognized object store: %s", url.Bucket)
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L641-L649
|
func (c *Cluster) ContainerSetStateful(id int, stateful bool) error {
statefulInt := 0
if stateful {
statefulInt = 1
}
err := exec(c.db, "UPDATE containers SET stateful=? WHERE id=?", statefulInt, id)
return err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/types.go#L379-L419
|
func (t *Subtype) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch Subtype(in.String()) {
case SubtypeArray:
*t = SubtypeArray
case SubtypeNull:
*t = SubtypeNull
case SubtypeNode:
*t = SubtypeNode
case SubtypeRegexp:
*t = SubtypeRegexp
case SubtypeDate:
*t = SubtypeDate
case SubtypeMap:
*t = SubtypeMap
case SubtypeSet:
*t = SubtypeSet
case SubtypeWeakmap:
*t = SubtypeWeakmap
case SubtypeWeakset:
*t = SubtypeWeakset
case SubtypeIterator:
*t = SubtypeIterator
case SubtypeGenerator:
*t = SubtypeGenerator
case SubtypeError:
*t = SubtypeError
case SubtypeProxy:
*t = SubtypeProxy
case SubtypePromise:
*t = SubtypePromise
case SubtypeTypedarray:
*t = SubtypeTypedarray
case SubtypeArraybuffer:
*t = SubtypeArraybuffer
case SubtypeDataview:
*t = SubtypeDataview
default:
in.AddError(errors.New("unknown Subtype value"))
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/quota.go#L74-L135
|
func NewBackendQuota(s *EtcdServer, name string) Quota {
lg := s.getLogger()
quotaBackendBytes.Set(float64(s.Cfg.QuotaBackendBytes))
if s.Cfg.QuotaBackendBytes < 0 {
// disable quotas if negative
quotaLogOnce.Do(func() {
if lg != nil {
lg.Info(
"disabled backend quota",
zap.String("quota-name", name),
zap.Int64("quota-size-bytes", s.Cfg.QuotaBackendBytes),
)
} else {
plog.Warningf("disabling backend quota")
}
})
return &passthroughQuota{}
}
if s.Cfg.QuotaBackendBytes == 0 {
// use default size if no quota size given
quotaLogOnce.Do(func() {
if lg != nil {
lg.Info(
"enabled backend quota with default value",
zap.String("quota-name", name),
zap.Int64("quota-size-bytes", DefaultQuotaBytes),
zap.String("quota-size", DefaultQuotaSize),
)
}
})
quotaBackendBytes.Set(float64(DefaultQuotaBytes))
return &backendQuota{s, DefaultQuotaBytes}
}
quotaLogOnce.Do(func() {
if s.Cfg.QuotaBackendBytes > MaxQuotaBytes {
if lg != nil {
lg.Warn(
"quota exceeds the maximum value",
zap.String("quota-name", name),
zap.Int64("quota-size-bytes", s.Cfg.QuotaBackendBytes),
zap.String("quota-size", humanize.Bytes(uint64(s.Cfg.QuotaBackendBytes))),
zap.Int64("quota-maximum-size-bytes", MaxQuotaBytes),
zap.String("quota-maximum-size", maxQuotaSize),
)
} else {
plog.Warningf("backend quota %v exceeds maximum recommended quota %v", s.Cfg.QuotaBackendBytes, MaxQuotaBytes)
}
}
if lg != nil {
lg.Info(
"enabled backend quota",
zap.String("quota-name", name),
zap.Int64("quota-size-bytes", s.Cfg.QuotaBackendBytes),
zap.String("quota-size", humanize.Bytes(uint64(s.Cfg.QuotaBackendBytes))),
)
}
})
return &backendQuota{s, s.Cfg.QuotaBackendBytes}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/client/util.go#L48-L53
|
func IsUserNotFound(err error) bool {
if ae, ok := err.(authError); ok {
return userNotFoundRegExp.MatchString(ae.Message)
}
return false
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.