_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/embed/etcd.go#L803-L808
|
func (e *Etcd) GetLogger() *zap.Logger {
e.cfg.loggerMu.RLock()
l := e.cfg.logger
e.cfg.loggerMu.RUnlock()
return l
}
|
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/xmltree/xmlele/xmlele.go#L97-L106
|
func (x *XMLEle) ResValue() string {
ret := ""
for i := range x.Children {
switch x.Children[i].GetNodeType() {
case tree.NtChd, tree.NtElem, tree.NtRoot:
ret += x.Children[i].ResValue()
}
}
return ret
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage.go#L596-L598
|
func getContainerMountPoint(project string, poolName string, containerName string) string {
return shared.VarPath("storage-pools", poolName, "containers", projectPrefix(project, containerName))
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/transport/keepalive_listener.go#L70-L83
|
func (l *tlsKeepaliveListener) Accept() (c net.Conn, err error) {
c, err = l.Listener.Accept()
if err != nil {
return
}
kac := c.(keepAliveConn)
// detection time: tcp_keepalive_time + tcp_keepalive_probes + tcp_keepalive_intvl
// default on linux: 30 + 8 * 30
// default on osx: 30 + 8 * 75
kac.SetKeepAlive(true)
kac.SetKeepAlivePeriod(30 * time.Second)
c = tls.Server(c, l.config)
return c, nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/cmdutil/cobra.go#L107-L117
|
func ParseBranches(args []string) ([]*pfs.Branch, error) {
var results []*pfs.Branch
for _, arg := range args {
branch, err := ParseBranch(arg)
if err != nil {
return nil, err
}
results = append(results, branch)
}
return results, nil
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/routes/get_apps_app_routes_responses.go#L25-L52
|
func (o *GetAppsAppRoutesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewGetAppsAppRoutesOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
case 404:
result := NewGetAppsAppRoutesNotFound()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
default:
result := NewGetAppsAppRoutesDefault(response.Code())
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
if response.Code()/100 == 2 {
return result, nil
}
return nil, result
}
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L739-L741
|
func (g *Glg) Info(val ...interface{}) error {
return g.out(INFO, blankFormat(len(val)), val...)
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4227-L4235
|
func (u OperationResultTr) MustManageDataResult() ManageDataResult {
val, ok := u.GetManageDataResult()
if !ok {
panic("arm ManageDataResult is not set")
}
return val
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L223-L225
|
func (p *DiscardSearchResultsParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandDiscardSearchResults, p, nil)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/membership/member.go#L78-L83
|
func (m *Member) PickPeerURL() string {
if len(m.PeerURLs) == 0 {
panic("member should always have some peer url")
}
return m.PeerURLs[rand.Intn(len(m.PeerURLs))]
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L931-L933
|
func (g *Glg) Printf(format string, val ...interface{}) error {
return g.out(PRINT, format, val...)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L713-L717
|
func (v *GetTargetsReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoTarget6(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L4983-L4987
|
func (v *EventShadowRootPopped) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom56(&r, v)
return r.Error()
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift-copies.go#L257-L277
|
func getUserIdentificationPartialConfig(configAuthInfo clientcmdAuthInfo) (*restConfig, error) {
mergedConfig := &restConfig{}
// blindly overwrite existing values based on precedence
if len(configAuthInfo.Token) > 0 {
mergedConfig.BearerToken = configAuthInfo.Token
}
if len(configAuthInfo.ClientCertificate) > 0 || len(configAuthInfo.ClientCertificateData) > 0 {
mergedConfig.CertFile = configAuthInfo.ClientCertificate
mergedConfig.CertData = configAuthInfo.ClientCertificateData
mergedConfig.KeyFile = configAuthInfo.ClientKey
mergedConfig.KeyData = configAuthInfo.ClientKeyData
}
if len(configAuthInfo.Username) > 0 || len(configAuthInfo.Password) > 0 {
mergedConfig.Username = configAuthInfo.Username
mergedConfig.Password = configAuthInfo.Password
}
// REMOVED: prompting for missing information.
return mergedConfig, nil
}
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/examples/types/repository.go#L18-L25
|
func (u *UserRepository) ByID(ID int) (*User, error) {
for _, user := range u.Users {
if user.ID == ID {
return user, nil
}
}
return nil, ErrNotFound
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/service/service_instance.go#L92-L110
|
func DeleteInstance(si *ServiceInstance, evt *event.Event, requestID string) error {
if len(si.Apps) > 0 {
return ErrServiceInstanceBound
}
s, err := Get(si.ServiceName)
if err != nil {
return err
}
endpoint, err := s.getClient("production")
if err == nil {
endpoint.Destroy(si, evt, requestID)
}
conn, err := db.Conn()
if err != nil {
return err
}
defer conn.Close()
return conn.ServiceInstances().Remove(bson.M{"name": si.Name, "service_name": si.ServiceName})
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/level_handler.go#L53-L75
|
func (s *levelHandler) initTables(tables []*table.Table) {
s.Lock()
defer s.Unlock()
s.tables = tables
s.totalSize = 0
for _, t := range tables {
s.totalSize += t.Size()
}
if s.level == 0 {
// Key range will overlap. Just sort by fileID in ascending order
// because newer tables are at the end of level 0.
sort.Slice(s.tables, func(i, j int) bool {
return s.tables[i].ID() < s.tables[j].ID()
})
} else {
// Sort tables by keys.
sort.Slice(s.tables, func(i, j int) bool {
return y.CompareKeys(s.tables[i].Smallest(), s.tables[j].Smallest()) < 0
})
}
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/cmd/seqls/manager.go#L103-L163
|
func (w *workManager) processSources() {
var (
ok bool
path string
seq *fileseq.FileSequence
)
fileopts := w.fileOpts
inDirs := w.inDirs
inSeqs := w.inSeqs
outSeqs := w.outSeqs
isDone := func() bool {
return (inDirs == nil && inSeqs == nil)
}
for !isDone() {
select {
// Directory paths will be scanned for contents
case path, ok = <-inDirs:
if !ok {
inDirs = nil
continue
}
seqs, err := fileseq.FindSequencesOnDisk(path, fileopts...)
if err != nil {
fmt.Fprintf(errOut, "%s %q: %s\n", ErrorPath, path, err)
continue
}
outSeqs <- seqs
// Sequence paths will be scanned for a direct match
// against the sequence pattern
case seq, ok = <-inSeqs:
if !ok {
inSeqs = nil
continue
}
path, err := seq.Format("{{dir}}{{base}}{{pad}}{{ext}}")
if err != nil {
fmt.Fprintf(errOut, "%s %q: Not a valid path\n", ErrorPattern, path)
continue
}
seq, err := fileseq.FindSequenceOnDisk(path)
if err != nil {
if !os.IsNotExist(err) {
fmt.Fprintf(errOut, "%s %q: %s\n", ErrorPattern, path, err)
}
continue
}
if seq != nil {
outSeqs <- fileseq.FileSequences{seq}
}
}
}
}
|
https://github.com/gokyle/fswatch/blob/1dbdf8320a690537582afe0f45c947f501adeaad/watcher.go#L90-L111
|
func (w *Watcher) Add(inpaths ...string) {
var paths []string
for _, path := range inpaths {
matches, err := filepath.Glob(path)
if err != nil {
continue
}
paths = append(paths, matches...)
}
if w.auto_watch && w.notify_chan != nil {
for _, path := range paths {
wi := watchPath(path)
w.addPaths(wi)
}
} else if w.auto_watch {
w.syncAddPaths(paths...)
} else {
for _, path := range paths {
w.paths[path] = watchPath(path)
}
}
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/apps/put_apps_app_parameters.go#L71-L74
|
func (o *PutAppsAppParams) WithTimeout(timeout time.Duration) *PutAppsAppParams {
o.SetTimeout(timeout)
return o
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cdp/types.go#L46-L51
|
func Execute(ctx context.Context, method string, params easyjson.Marshaler, res easyjson.Unmarshaler) error {
if executor := ctx.Value(executorKey); executor != nil {
return executor.(Executor).Execute(ctx, method, params, res)
}
return ErrInvalidContext
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/robots/coverage/cmd/downloader/downloader.go#L37-L52
|
func MakeCommand() *cobra.Command {
flags := &flags{}
cmd := &cobra.Command{
Use: "download [bucket] [prowjob]",
Short: "Finds and downloads the coverage profile file from the latest healthy build",
Long: `Finds and downloads the coverage profile file from the latest healthy build
stored in given gcs directory.`,
Run: func(cmd *cobra.Command, args []string) {
run(flags, cmd, args)
},
}
cmd.Flags().StringVarP(&flags.outputFile, "output", "o", "-", "output file")
cmd.Flags().StringVarP(&flags.artifactsDirName, "artifactsDir", "a", "artifacts", "artifact directory name in GCS")
cmd.Flags().StringVarP(&flags.profileName, "profile", "p", "coverage-profile", "code coverage profile file name in GCS")
return cmd
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/inmem_store.go#L58-L60
|
func (i *InmemStore) StoreLog(log *Log) error {
return i.StoreLogs([]*Log{log})
}
|
https://github.com/bluekeyes/hatpear/blob/ffb42d5bb417aa8e12b3b7ff73d028b915dafa10/hatpear.go#L82-L87
|
func Try(h Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err := h.ServeHTTP(w, r)
Store(r, err)
})
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L3055-L3059
|
func (v GetRelayoutBoundaryReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom34(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/tcp_transport.go#L24-L34
|
func NewTCPTransport(
bindAddr string,
advertise net.Addr,
maxPool int,
timeout time.Duration,
logOutput io.Writer,
) (*NetworkTransport, error) {
return newTCPTransport(bindAddr, advertise, func(stream StreamLayer) *NetworkTransport {
return NewNetworkTransport(stream, maxPool, timeout, logOutput)
})
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_pools.go#L484-L500
|
func (c *Cluster) storagePoolNodes(poolID int64) ([]string, error) {
stmt := `
SELECT nodes.name FROM nodes
JOIN storage_pools_nodes ON storage_pools_nodes.node_id = nodes.id
WHERE storage_pools_nodes.storage_pool_id = ?
`
var nodes []string
err := c.Transaction(func(tx *ClusterTx) error {
var err error
nodes, err = query.SelectStrings(tx.tx, stmt, poolID)
return err
})
if err != nil {
return nil, err
}
return nodes, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/server.go#L1737-L1774
|
func (s *EtcdServer) configure(ctx context.Context, cc raftpb.ConfChange) ([]*membership.Member, error) {
cc.ID = s.reqIDGen.Next()
ch := s.w.Register(cc.ID)
start := time.Now()
if err := s.r.ProposeConfChange(ctx, cc); err != nil {
s.w.Trigger(cc.ID, nil)
return nil, err
}
select {
case x := <-ch:
if x == nil {
if lg := s.getLogger(); lg != nil {
lg.Panic("failed to configure")
} else {
plog.Panicf("configure trigger value should never be nil")
}
}
resp := x.(*confChangeResponse)
if lg := s.getLogger(); lg != nil {
lg.Info(
"applied a configuration change through raft",
zap.String("local-member-id", s.ID().String()),
zap.String("raft-conf-change", cc.Type.String()),
zap.String("raft-conf-change-node-id", types.ID(cc.NodeID).String()),
)
}
return resp.membs, resp.err
case <-ctx.Done():
s.w.Trigger(cc.ID, nil) // GC wait
return nil, s.parseProposeCtxErr(ctx.Err(), start)
case <-s.stopping:
return nil, ErrStopped
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/git/git.go#L235-L242
|
func (r *Repo) CheckoutNewBranch(branch string) error {
r.logger.Infof("Create and checkout %s.", branch)
co := r.gitCommand("checkout", "-b", branch)
if b, err := co.CombinedOutput(); err != nil {
return fmt.Errorf("error checking out %s: %v. output: %s", branch, err, string(b))
}
return nil
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/buffer.go#L413-L417
|
func (ref Uint64Ref) Update(n uint64) {
if ref != nil {
binary.BigEndian.PutUint64(ref, n)
}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/metrics/metrics.go#L27-L35
|
func NewReporter(clusterID string, kubeClient *kube.Clientset) *Reporter {
reporter := &Reporter{
segmentClient: newPersistentClient(),
clusterID: clusterID,
kubeClient: kubeClient,
}
go reporter.reportClusterMetrics()
return reporter
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/blobstore/blobstore.go#L144-L157
|
func DeleteMulti(c context.Context, blobKey []appengine.BlobKey) error {
s := make([]string, len(blobKey))
for i, b := range blobKey {
s[i] = string(b)
}
req := &blobpb.DeleteBlobRequest{
BlobKey: s,
}
res := &basepb.VoidProto{}
if err := internal.Call(c, "blobstore", "DeleteBlob", req, res); err != nil {
return err
}
return nil
}
|
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/blacklist.go#L37-L45
|
func NewLRUBlacklist(cap int) (Blacklist, error) {
c, err := lru.New(cap)
if err != nil {
return nil, err
}
b := &LRUBlacklist{lru: c}
return b, nil
}
|
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/service/logger/logger.go#L103-L115
|
func Ctx(ctx context.Context, info *grpc.UnaryServerInfo, code codes.Code) zapcore.Field {
logCtx := Context{
HTTPRequest: HTTPRequest{
Method: info.FullMethod,
ResponseStatusCode: code.String(),
},
}
if p, ok := peer.FromContext(ctx); ok {
logCtx.HTTPRequest.RemoteIP = p.Addr.String()
}
return zap.Object("context", logCtx)
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/app.go#L986-L1030
|
func unsetEnv(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
msg := "You must provide the list of environment variables."
if InputValue(r, "env") == "" {
return &errors.HTTP{Code: http.StatusBadRequest, Message: msg}
}
var variables []string
if envs, ok := InputValues(r, "env"); ok {
variables = envs
} else {
return &errors.HTTP{Code: http.StatusBadRequest, Message: msg}
}
appName := r.URL.Query().Get(":app")
a, err := getAppFromContext(appName, r)
if err != nil {
return err
}
allowed := permission.Check(t, permission.PermAppUpdateEnvUnset,
contextsForApp(&a)...,
)
if !allowed {
return permission.ErrUnauthorized
}
evt, err := event.New(&event.Opts{
Target: appTarget(appName),
Kind: permission.PermAppUpdateEnvUnset,
Owner: t,
CustomData: event.FormToCustomData(InputFields(r)),
Allowed: event.Allowed(permission.PermAppReadEvents, contextsForApp(&a)...),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
w.Header().Set("Content-Type", "application/x-json-stream")
keepAliveWriter := tsuruIo.NewKeepAliveWriter(w, 30*time.Second, "")
defer keepAliveWriter.Stop()
writer := &tsuruIo.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)}
evt.SetLogWriter(writer)
noRestart, _ := strconv.ParseBool(InputValue(r, "noRestart"))
return a.UnsetEnvs(bind.UnsetEnvArgs{
VariableNames: variables,
ShouldRestart: !noRestart,
Writer: evt,
})
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L1491-L1495
|
func (v *SetBreakpointByURLParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger15(&r, v)
return r.Error()
}
|
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/header.go#L90-L148
|
func readHeader(r *bufio.Reader, p *Part) (textproto.MIMEHeader, error) {
// buf holds the massaged output for textproto.Reader.ReadMIMEHeader()
buf := &bytes.Buffer{}
tp := textproto.NewReader(r)
firstHeader := true
for {
// Pull out each line of the headers as a temporary slice s
s, err := tp.ReadLineBytes()
if err != nil {
cause := errors.Cause(err)
if cause == io.ErrUnexpectedEOF && buf.Len() == 0 {
return nil, errors.WithStack(errEmptyHeaderBlock)
} else if cause == io.EOF {
buf.Write([]byte{'\r', '\n'})
break
}
return nil, err
}
firstColon := bytes.IndexByte(s, ':')
firstSpace := bytes.IndexAny(s, " \t\n\r")
if firstSpace == 0 {
// Starts with space: continuation
buf.WriteByte(' ')
buf.Write(textproto.TrimBytes(s))
continue
}
if firstColon == 0 {
// Can't parse line starting with colon: skip
p.addError(ErrorMalformedHeader, "Header line %q started with a colon", s)
continue
}
if firstColon > 0 {
// Contains a colon, treat as a new header line
if !firstHeader {
// New Header line, end the previous
buf.Write([]byte{'\r', '\n'})
}
s = textproto.TrimBytes(s)
buf.Write(s)
firstHeader = false
} else {
// No colon: potential non-indented continuation
if len(s) > 0 {
// Attempt to detect and repair a non-indented continuation of previous line
buf.WriteByte(' ')
buf.Write(s)
p.addWarning(ErrorMalformedHeader, "Continued line %q was not indented", s)
} else {
// Empty line, finish header parsing
buf.Write([]byte{'\r', '\n'})
break
}
}
}
buf.Write([]byte{'\r', '\n'})
tr := textproto.NewReader(bufio.NewReader(buf))
header, err := tr.ReadMIMEHeader()
return header, errors.WithStack(err)
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/ostree/ostree_src.go#L55-L60
|
func (s *ostreeImageSource) Close() error {
if s.repo != nil {
C.g_object_unref(C.gpointer(s.repo))
}
return nil
}
|
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/tree.go#L176-L182
|
func GetAttrValOrEmpty(n Elem, local, space string) string {
val, ok := GetAttributeVal(n, local, space)
if !ok {
return ""
}
return val
}
|
https://github.com/gravitational/roundtrip/blob/e1e0cd6b05a6bb1791b262e63160038828fd7b3a/client.go#L99-L104
|
func SanitizerEnabled(sanitizerEnabled bool) ClientParam {
return func(c *Client) error {
c.sanitizerEnabled = sanitizerEnabled
return nil
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_volumes.go#L594-L607
|
func (r *ProtocolLXD) RenameStoragePoolVolume(pool string, volType string, name string, volume api.StorageVolumePost) error {
if !r.HasExtension("storage_api_volume_rename") {
return fmt.Errorf("The server is missing the required \"storage_api_volume_rename\" API extension")
}
path := fmt.Sprintf("/storage-pools/%s/volumes/%s/%s", url.QueryEscape(pool), url.QueryEscape(volType), url.QueryEscape(name))
// Send the request
_, _, err := r.query("POST", path, volume, "")
if err != nil {
return err
}
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/member_command.go#L70-L81
|
func NewMemberUpdateCommand() *cobra.Command {
cc := &cobra.Command{
Use: "update <memberID> [options]",
Short: "Updates a member in the cluster",
Run: memberUpdateCommandFunc,
}
cc.Flags().StringVar(&memberPeerURLs, "peer-urls", "", "comma separated peer URLs for the updated member.")
return cc
}
|
https://github.com/dailyburn/bigquery/blob/b6f18972580ed8882d195da0e9b7c9b94902a1ea/client/client.go#L83-L110
|
func (c *Client) connect() (*bigquery.Service, error) {
if c.token != nil {
if !c.token.Valid() && c.service != nil {
return c.service, nil
}
}
// generate auth token and create service object
//authScope := bigquery.BigqueryScope
pemKeyBytes, err := ioutil.ReadFile(c.pemPath)
if err != nil {
panic(err)
}
t, err := google.JWTConfigFromJSON(
pemKeyBytes,
"https://www.googleapis.com/auth/bigquery")
//t := jwt.NewToken(c.accountEmailAddress, bigquery.BigqueryScope, pemKeyBytes)
client := t.Client(oauth2.NoContext)
service, err := bigquery.New(client)
if err != nil {
return nil, err
}
c.service = service
return service, nil
}
|
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/offsets.go#L22-L24
|
func (s *OffsetStash) MarkOffset(msg *sarama.ConsumerMessage, metadata string) {
s.MarkPartitionOffset(msg.Topic, msg.Partition, msg.Offset, metadata)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/alarm_command.go#L25-L35
|
func NewAlarmCommand() *cobra.Command {
ac := &cobra.Command{
Use: "alarm <subcommand>",
Short: "Alarm related commands",
}
ac.AddCommand(NewAlarmDisarmCommand())
ac.AddCommand(NewAlarmListCommand())
return ac
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/tide/tide.go#L609-L697
|
func accumulateBatch(presubmits map[int][]config.Presubmit, prs []PullRequest, pjs []prowapi.ProwJob, log *logrus.Entry) ([]PullRequest, []PullRequest) {
log.Debug("accumulating PRs for batch testing")
if len(presubmits) == 0 {
log.Debug("no presubmits configured, no batch can be triggered")
return nil, nil
}
prNums := make(map[int]PullRequest)
for _, pr := range prs {
prNums[int(pr.Number)] = pr
}
type accState struct {
prs []PullRequest
jobStates map[string]simpleState
// Are the pull requests in the ref still acceptable? That is, do they
// still point to the heads of the PRs?
validPulls bool
}
states := make(map[string]*accState)
for _, pj := range pjs {
if pj.Spec.Type != prowapi.BatchJob {
continue
}
// First validate the batch job's refs.
ref := pj.Spec.Refs.String()
if _, ok := states[ref]; !ok {
state := &accState{
jobStates: make(map[string]simpleState),
validPulls: true,
}
for _, pull := range pj.Spec.Refs.Pulls {
if pr, ok := prNums[pull.Number]; ok && string(pr.HeadRefOID) == pull.SHA {
state.prs = append(state.prs, pr)
} else if !ok {
state.validPulls = false
log.WithField("batch", ref).WithFields(pr.logFields()).Debug("batch job invalid, PR left pool")
break
} else {
state.validPulls = false
log.WithField("batch", ref).WithFields(pr.logFields()).Debug("batch job invalid, PR HEAD changed")
break
}
}
states[ref] = state
}
if !states[ref].validPulls {
// The batch contains a PR ref that has changed. Skip it.
continue
}
// Batch job refs are valid. Now accumulate job states by batch ref.
context := pj.Spec.Context
jobState := toSimpleState(pj.Status.State)
// Store the best result for this ref+context.
if s, ok := states[ref].jobStates[context]; !ok || s == failureState || jobState == successState {
states[ref].jobStates[context] = jobState
}
}
var pendingBatch, successBatch []PullRequest
for ref, state := range states {
if !state.validPulls {
continue
}
requiredPresubmits := sets.NewString()
for _, pr := range state.prs {
for _, job := range presubmits[int(pr.Number)] {
requiredPresubmits.Insert(job.Context)
}
}
overallState := successState
for _, p := range requiredPresubmits.List() {
if s, ok := state.jobStates[p]; !ok || s == failureState {
overallState = failureState
log.WithField("batch", ref).Debugf("batch invalid, required presubmit %s is not passing", p)
break
} else if s == pendingState && overallState == successState {
overallState = pendingState
}
}
switch overallState {
// Currently we only consider 1 pending batch and 1 success batch at a time.
// If more are somehow present they will be ignored.
case pendingState:
pendingBatch = state.prs
case successState:
successBatch = state.prs
}
}
return successBatch, pendingBatch
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nitro.go#L1184-L1194
|
func MemoryInUse() (sz int64) {
buf := dbInstances.MakeBuf()
defer dbInstances.FreeBuf(buf)
iter := dbInstances.NewIterator(CompareNitro, buf)
for iter.SeekFirst(); iter.Valid(); iter.Next() {
db := (*Nitro)(iter.Get())
sz += db.MemoryInUse()
}
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/accessibility/types.go#L333-L335
|
func (t PropertyName) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/manage_offer.go#L55-L76
|
func (b *ManageOfferBuilder) Mutate(muts ...interface{}) {
for _, m := range muts {
var err error
switch mut := m.(type) {
case ManageOfferMutator:
if b.PassiveOffer {
err = mut.MutateManageOffer(&b.PO)
} else {
err = mut.MutateManageOffer(&b.MO)
}
case OperationMutator:
err = mut.MutateOperation(&b.O)
default:
err = errors.New("Mutator type not allowed")
}
if err != nil {
b.Err = err
return
}
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/schema.go#L11-L23
|
func UpdateSchema() error {
err := cluster.SchemaDotGo()
if err != nil {
return errors.Wrap(err, "Update cluster database schema")
}
err = node.SchemaDotGo()
if err != nil {
return errors.Wrap(err, "Update node database schema")
}
return nil
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L286-L288
|
func imports(f *ast.File, path string) bool {
return importSpec(f, path) != nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/alarm_command.go#L70-L81
|
func alarmListCommandFunc(cmd *cobra.Command, args []string) {
if len(args) != 0 {
ExitWithError(ExitBadArgs, fmt.Errorf("alarm list command accepts no arguments"))
}
ctx, cancel := commandCtx(cmd)
resp, err := mustClientFromCmd(cmd).AlarmList(ctx)
cancel()
if err != nil {
ExitWithError(ExitError, err)
}
display.Alarm(*resp)
}
|
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/service/lease.go#L29-L46
|
func (s *Lease) Delete(logger *log.Logger, req *http.Request) (statusCode int, response interface{}) {
var (
err error
)
statusCode = http.StatusNotFound
s.taskCollection.Wake()
if err = s.InitFromHTTPRequest(req); err == nil {
logger.Println("restocking inventory...")
s.ReStock()
statusCode = http.StatusAccepted
response = s.Task
} else {
response = map[string]string{"error": err.Error()}
}
return
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L716-L762
|
func (h *dbHashTree) PutDirHeaderFooter(path string, header, footer *pfs.Object, headerSize, footerSize int64) error {
path = clean(path)
return h.Batch(func(tx *bolt.Tx) error {
// validation: 'path' must point to directory (or nothing--may not be
// created yet)
node, err := get(tx, path)
if err != nil && Code(err) != PathNotFound {
return errorf(Internal, "could not get node at %q: %v", path, err)
}
if node != nil && node.nodetype() != directory {
return errorf(PathConflict, "cannot add header to non-directory file "+
"at %q; a file of type %s is already there", path, node.nodetype())
}
// Upsert directory at 'path' with 'Shared' field
var newNode bool
if node == nil {
newNode = true
node = &NodeProto{
Name: base(path),
DirNode: &DirectoryNodeProto{
Shared: &Shared{},
},
// header/footer size are also stored in Shared (for CopyFile) but
// adding it here makes size calculation in canonicalize() work
SubtreeSize: headerSize + footerSize,
}
}
// only write node to db if the node is new, or the header or footer
// changed
headerSame := (node.DirNode.Shared.Header == nil && header == nil) ||
(node.DirNode.Shared.Header != nil && node.DirNode.Shared.Header.Hash == header.Hash)
footerSame := (node.DirNode.Shared.Footer == nil && footer == nil) ||
(node.DirNode.Shared.Footer != nil && node.DirNode.Shared.Footer.Hash == footer.Hash)
if newNode || !headerSame || !footerSame {
node.DirNode.Shared = &Shared{
Header: header,
Footer: footer,
HeaderSize: headerSize,
FooterSize: footerSize,
}
return put(tx, path, node)
}
return nil
})
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift.go#L154-L160
|
func (c *openshiftClient) convertDockerImageReference(ref string) (string, error) {
parts := strings.SplitN(ref, "/", 2)
if len(parts) != 2 {
return "", errors.Errorf("Invalid format of docker reference %s: missing '/'", ref)
}
return reference.Domain(c.ref.dockerReference) + "/" + parts[1], nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L668-L688
|
func (prm *prmExactRepository) UnmarshalJSON(data []byte) error {
*prm = prmExactRepository{}
var tmp prmExactRepository
if err := paranoidUnmarshalJSONObjectExactFields(data, map[string]interface{}{
"type": &tmp.Type,
"dockerRepository": &tmp.DockerRepository,
}); err != nil {
return err
}
if tmp.Type != prmTypeExactRepository {
return InvalidPolicyFormatError(fmt.Sprintf("Unexpected policy requirement type \"%s\"", tmp.Type))
}
res, err := newPRMExactRepository(tmp.DockerRepository)
if err != nil {
return err
}
*prm = *res
return nil
}
|
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/goxpath.go#L87-L99
|
func (xp XPathExec) ExecNode(t tree.Node, opts ...FuncOpts) (tree.NodeSet, error) {
res, err := xp.Exec(t, opts...)
if err != nil {
return nil, err
}
n, ok := res.(tree.NodeSet)
if !ok {
return nil, fmt.Errorf("Cannot convert result to a node-set")
}
return n, nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/obj/obj.go#L272-L277
|
func NewMinioClient(endpoint, bucket, id, secret string, secure, isS3V2 bool) (Client, error) {
if isS3V2 {
return newMinioClientV2(endpoint, bucket, id, secret, secure)
}
return newMinioClient(endpoint, bucket, id, secret, secure)
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/subchannel.go#L35-L40
|
func Isolated(s *SubChannel) {
s.Lock()
s.peers = s.topChannel.peers.newSibling()
s.peers.SetStrategy(newLeastPendingCalculator())
s.Unlock()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domsnapshot/easyjson.go#L677-L681
|
func (v *RareBooleanData) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDomsnapshot3(&r, v)
return r.Error()
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4410-L4413
|
func (e TransactionResultCode) String() string {
name, _ := transactionResultCodeMap[int32(e)]
return name
}
|
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/read.go#L116-L118
|
func NewReader(f io.ReaderAt, size int64) (*Reader, error) {
return NewReaderEncrypted(f, size, nil)
}
|
https://github.com/jpillora/overseer/blob/ce9055846616cf7e1ab91bb8a0bcbb1d7fa3d11a/fetcher/fetcher_s3.go#L63-L89
|
func (s *S3) Fetch() (io.Reader, error) {
//delay fetches after first
if s.delay {
time.Sleep(s.Interval)
}
s.delay = true
//status check using HEAD
head, err := s.client.HeadObject(&s3.HeadObjectInput{Bucket: &s.Bucket, Key: &s.Key})
if err != nil {
return nil, fmt.Errorf("HEAD request failed (%s)", err)
}
if s.lastETag == *head.ETag {
return nil, nil //skip, file match
}
s.lastETag = *head.ETag
//binary fetch using GET
get, err := s.client.GetObject(&s3.GetObjectInput{Bucket: &s.Bucket, Key: &s.Key})
if err != nil {
return nil, fmt.Errorf("GET request failed (%s)", err)
}
//extract gz files
if strings.HasSuffix(s.Key, ".gz") && aws.StringValue(get.ContentEncoding) != "gzip" {
return gzip.NewReader(get.Body)
}
//success!
return get.Body, nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L565-L615
|
func (r *ProtocolLXD) CopyImage(source ImageServer, image api.Image, args *ImageCopyArgs) (RemoteOperation, error) {
// Sanity checks
if r == source {
return nil, fmt.Errorf("The source and target servers must be different")
}
// Get source server connection information
info, err := source.GetConnectionInfo()
if err != nil {
return nil, err
}
// Prepare the copy request
req := api.ImagesPost{
Source: &api.ImagesPostSource{
ImageSource: api.ImageSource{
Certificate: info.Certificate,
Protocol: info.Protocol,
},
Fingerprint: image.Fingerprint,
Mode: "pull",
Type: "image",
},
}
// Generate secret token if needed
if !image.Public {
secret, err := source.GetImageSecret(image.Fingerprint)
if err != nil {
return nil, err
}
req.Source.Secret = secret
}
// Process the arguments
if args != nil {
req.Aliases = args.Aliases
req.AutoUpdate = args.AutoUpdate
req.Public = args.Public
if args.CopyAliases {
req.Aliases = image.Aliases
if args.Aliases != nil {
req.Aliases = append(req.Aliases, args.Aliases...)
}
}
}
return r.tryCopyImage(req, info.Addresses)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container.go#L1427-L1449
|
func containerLoadFromAllProjects(s *state.State) ([]container, error) {
var projects []string
err := s.Cluster.Transaction(func(tx *db.ClusterTx) error {
var err error
projects, err = tx.ProjectNames()
return err
})
if err != nil {
return nil, err
}
containers := []container{}
for _, project := range projects {
projectContainers, err := containerLoadByProject(s, project)
if err != nil {
return nil, errors.Wrapf(nil, "Load containers in project %s", project)
}
containers = append(containers, projectContainers...)
}
return containers, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L704-L706
|
func (p *SetBypassServiceWorkerParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandSetBypassServiceWorker, p, nil)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L4862-L4866
|
func (v *GetMatchedStylesForNodeReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss41(&r, v)
return r.Error()
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/ae.go#L40-L45
|
func mapPackage(s string) string {
if stutterPackage {
s += "/" + path.Base(s)
}
return newPackageBase + s
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L424-L426
|
func (p *SynthesizePinchGestureParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandSynthesizePinchGesture, p, nil)
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5794-L5802
|
func (u LedgerEntryChange) MustRemoved() LedgerKey {
val, ok := u.GetRemoved()
if !ok {
panic("arm Removed is not set")
}
return val
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/flags/flag.go#L70-L72
|
func FlagToEnv(prefix, name string) string {
return prefix + "_" + strings.ToUpper(strings.Replace(name, "-", "_", -1))
}
|
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/xmltree/xmlele/xmlele.go#L77-L85
|
func (x *XMLEle) GetChildren() []tree.Node {
ret := make([]tree.Node, len(x.Children))
for i := range x.Children {
ret[i] = x.Children[i]
}
return ret
}
|
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/decode_reader.go#L236-L249
|
func (d *decodeReader) fill() {
if d.err != nil {
return
}
var fl []*filterBlock
fl, d.err = d.dec.fill(&d.win) // fill window using decoder
for _, f := range fl {
err := d.queueFilter(f)
if err != nil {
d.err = err
return
}
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/mapping.go#L217-L224
|
func FieldArgs(fields []*Field) string {
args := make([]string, len(fields))
for i, field := range fields {
args[i] = fmt.Sprintf("%s %s", lex.Minuscule(field.Name), field.Type.Name)
}
return strings.Join(args, ", ")
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/easyjson.go#L85-L89
|
func (v *SetShowViewportSizeOnResizeParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoOverlay(&r, v)
return r.Error()
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/font.go#L129-L135
|
func NewFolderFontCache(folder string) *FolderFontCache {
return &FolderFontCache{
fonts: make(map[string]*truetype.Font),
folder: folder,
namer: FontFileName,
}
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L329-L331
|
func Add(c context.Context, item *Item) error {
return singleError(set(c, []*Item{item}, nil, pb.MemcacheSetRequest_ADD))
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/jenkins/jenkins.go#L178-L199
|
func (jb *Build) BuildID() string {
var buildID string
hasProwJobID := false
for _, action := range jb.Actions {
for _, p := range action.Parameters {
hasProwJobID = hasProwJobID || p.Name == prowJobID
if p.Name == statusBuildID {
value, ok := p.Value.(string)
if !ok {
logrus.Errorf("Cannot determine %s value for %#v", p.Name, jb)
continue
}
buildID = value
}
}
}
if !hasProwJobID {
return ""
}
return buildID
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L1256-L1260
|
func (v *SignedExchangeError) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork8(&r, v)
return r.Error()
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/types/set.go#L62-L65
|
func (us *unsafeSet) Contains(value string) (exists bool) {
_, exists = us.d[value]
return exists
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/projects.mapper.go#L434-L450
|
func (c *ClusterTx) ProjectDelete(name string) error {
stmt := c.stmt(projectDelete)
result, err := stmt.Exec(name)
if err != nil {
return errors.Wrap(err, "Delete project")
}
n, err := result.RowsAffected()
if err != nil {
return errors.Wrap(err, "Fetch affected rows")
}
if n != 1 {
return fmt.Errorf("Query deleted %d rows instead of 1", n)
}
return nil
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/stats/stats.go#L17-L29
|
func Start(ctx log.Interface, interval time.Duration) {
ctx.WithField("interval", interval).Debug("starting stats loop")
go func() {
memstats := new(runtime.MemStats)
for range time.Tick(interval) {
runtime.ReadMemStats(memstats)
ctx.WithFields(log.Fields{
"goroutines": runtime.NumGoroutine(),
"memory": float64(memstats.Alloc) / megaByte, // MegaBytes allocated and not yet freed
}).Debugf("memory stats")
}
}()
}
|
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/fakes/fake.go#L130-L132
|
func (s *FakeVCDClient) Auth(username, password string) (err error) {
return s.ErrAuthFake
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/greenhouse/diskcache/cache.go#L168-L188
|
func (c *Cache) GetEntries() []EntryInfo {
entries := []EntryInfo{}
// note we swallow errors because we just need to know what keys exist
// some keys missing is OK since this is used for eviction, but not returning
// any of the keys due to some error is NOT
_ = filepath.Walk(c.diskRoot, func(path string, f os.FileInfo, err error) error {
if err != nil {
logrus.WithError(err).Error("error getting some entries")
return nil
}
if !f.IsDir() {
atime := diskutil.GetATime(path, time.Now())
entries = append(entries, EntryInfo{
Path: path,
LastAccess: atime,
})
}
return nil
})
return entries
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L2090-L2094
|
func (v *CreateTargetParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoTarget23(&r, v)
return r.Error()
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_profiles.go#L82-L90
|
func (r *ProtocolLXD) RenameProfile(name string, profile api.ProfilePost) error {
// Send the request
_, _, err := r.query("POST", fmt.Sprintf("/profiles/%s", url.QueryEscape(name)), profile, "")
if err != nil {
return err
}
return nil
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/matchers/page_matchers.go#L10-L12
|
func HaveTitle(title string) types.GomegaMatcher {
return &internal.ValueMatcher{Method: "Title", Property: "title", Expected: title}
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L6267-L6270
|
func (e MessageType) String() string {
name, _ := messageTypeMap[int32(e)]
return name
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/pretty/pretty.go#L37-L49
|
func PrintRepoInfo(w io.Writer, repoInfo *pfs.RepoInfo, fullTimestamps bool) {
fmt.Fprintf(w, "%s\t", repoInfo.Repo.Name)
if fullTimestamps {
fmt.Fprintf(w, "%s\t", repoInfo.Created.String())
} else {
fmt.Fprintf(w, "%s\t", pretty.Ago(repoInfo.Created))
}
fmt.Fprintf(w, "%s\t", units.BytesSize(float64(repoInfo.SizeBytes)))
if repoInfo.AuthInfo != nil {
fmt.Fprintf(w, "%s\t", repoInfo.AuthInfo.AccessLevel.String())
}
fmt.Fprintln(w)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L3914-L3918
|
func (v *KeyframeRule) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss33(&r, v)
return r.Error()
}
|
https://github.com/DeMille/termsize/blob/b7100f0f89ccfa4a591ca92363fe5d434f54666f/termsize.go#L50-L57
|
func Size() (w, h int, err error) {
if !IsInit {
err = errors.New("termsize not yet iniitialied")
return
}
return get_size()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/easyjson.go#L1937-L1941
|
func (v *Bounds) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoBrowser21(&r, v)
return r.Error()
}
|
https://github.com/tylerb/gls/blob/e606233f194d6c314156dc6a35f21a42a470c6f6/gotrack.go#L41-L122
|
func parseUintBytes(s []byte, base int, bitSize int) (n uint64, err error) {
var cutoff, maxVal uint64
if bitSize == 0 {
bitSize = int(strconv.IntSize)
}
s0 := s
switch {
case len(s) < 1:
err = strconv.ErrSyntax
return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err}
case 2 <= base && base <= 36:
// valid base; nothing to do
case base == 0:
// Look for octal, hex prefix.
switch {
case s[0] == '0' && len(s) > 1 && (s[1] == 'x' || s[1] == 'X'):
base = 16
s = s[2:]
if len(s) < 1 {
err = strconv.ErrSyntax
return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err}
}
case s[0] == '0':
base = 8
default:
base = 10
}
default:
err = errors.New("invalid base " + strconv.Itoa(base))
return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err}
}
n = 0
cutoff = cutoff64(base)
maxVal = 1<<uint(bitSize) - 1
for i := 0; i < len(s); i++ {
var v byte
d := s[i]
switch {
case '0' <= d && d <= '9':
v = d - '0'
case 'a' <= d && d <= 'z':
v = d - 'a' + 10
case 'A' <= d && d <= 'Z':
v = d - 'A' + 10
default:
n = 0
err = strconv.ErrSyntax
return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err}
}
if int(v) >= base {
n = 0
err = strconv.ErrSyntax
return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err}
}
if n >= cutoff {
// n*base overflows
n = 1<<64 - 1
err = strconv.ErrRange
return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err}
}
n *= uint64(base)
n1 := n + uint64(v)
if n1 < n || n1 > maxVal {
// n+v overflows
n = 1<<64 - 1
err = strconv.ErrRange
return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err}
}
n = n1
}
return n, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/log.go#L261-L271
|
func (l *raftLog) allEntries() []pb.Entry {
ents, err := l.entries(l.firstIndex(), noLimit)
if err == nil {
return ents
}
if err == ErrCompacted { // try again if there was a racing compaction
return l.allEntries()
}
// TODO (xiangli): handle error?
panic(err)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/auth/server/api_server.go#L2225-L2260
|
func (a *apiServer) canonicalizeSubject(ctx context.Context, subject string) (string, error) {
colonIdx := strings.Index(subject, ":")
if colonIdx < 0 {
subject = authclient.GitHubPrefix + subject
colonIdx = len(authclient.GitHubPrefix) - 1
}
prefix := subject[:colonIdx]
a.configMu.Lock()
defer a.configMu.Unlock()
// check prefix against config cache
if a.configCache != nil {
if prefix == a.configCache.IDP.Name {
return subject, nil
}
if prefix == path.Join("group", a.configCache.IDP.Name) {
return subject, nil // TODO(msteffen): check if this IdP supports groups
}
}
// check against fixed prefixes
prefix += ":" // append ":" to match constants
switch prefix {
case authclient.GitHubPrefix:
var err error
subject, err = canonicalizeGitHubUsername(ctx, subject[len(authclient.GitHubPrefix):])
if err != nil {
return "", err
}
case authclient.PipelinePrefix, authclient.RobotPrefix:
break
default:
return "", fmt.Errorf("subject has unrecognized prefix: %s", subject[:colonIdx+1])
}
return subject, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/webaudio/easyjson.go#L148-L152
|
func (v GetRealtimeDataParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoWebaudio1(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/raft.go#L604-L619
|
func (r *raft) maybeCommit() bool {
// Preserving matchBuf across calls is an optimization
// used to avoid allocating a new slice on each call.
if cap(r.matchBuf) < len(r.prs) {
r.matchBuf = make(uint64Slice, len(r.prs))
}
r.matchBuf = r.matchBuf[:len(r.prs)]
idx := 0
for _, p := range r.prs {
r.matchBuf[idx] = p.Match
idx++
}
sort.Sort(&r.matchBuf)
mci := r.matchBuf[len(r.matchBuf)-r.quorum()]
return r.raftLog.maybeCommit(mci, r.Term)
}
|
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/string.go#L77-L82
|
func (s String) MarshalJSON() ([]byte, error) {
if !s.Valid {
return []byte("null"), nil
}
return json.Marshal(s.String)
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/buffer.go#L281-L292
|
func (w *WriteBuffer) DeferByte() ByteRef {
if len(w.remaining) == 0 {
w.setErr(ErrBufferFull)
return ByteRef(nil)
}
// Always zero out references, since the caller expects the default to be 0.
w.remaining[0] = 0
bufRef := ByteRef(w.remaining[0:])
w.remaining = w.remaining[1:]
return bufRef
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/frameset.go#L162-L171
|
func (s *FrameSet) Frames() []int {
size := s.rangePtr.Len()
frames := make([]int, size, size)
i := 0
for it := s.rangePtr.IterValues(); !it.IsDone(); {
frames[i] = it.Next()
i++
}
return frames
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.