_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L372-L375
|
func (p EvaluateParams) WithAwaitPromise(awaitPromise bool) *EvaluateParams {
p.AwaitPromise = awaitPromise
return &p
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/influx/writer.go#L50-L55
|
func NewSinglePointWriter(log ttnlog.Interface, w BatchPointsWriter) *SinglePointWriter {
return &SinglePointWriter{
log: log,
writer: w,
}
}
|
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/envelope.go#L53-L64
|
func (e *Envelope) GetHeaderValues(name string) []string {
if e.header == nil {
return []string{}
}
rawValues := (*e.header)[textproto.CanonicalMIMEHeaderKey(name)]
var values []string
for _, v := range rawValues {
values = append(values, decodeHeader(v))
}
return values
}
|
https://github.com/codegangsta/martini-contrib/blob/8ce6181c2609699e4c7cd30994b76a850a9cdadc/binding/binding.go#L62-L81
|
func Form(formStruct interface{}, ifacePtr ...interface{}) martini.Handler {
return func(context martini.Context, req *http.Request) {
ensureNotPointer(formStruct)
formStruct := reflect.New(reflect.TypeOf(formStruct))
errors := newErrors()
parseErr := req.ParseForm()
// Format validation of the request body or the URL would add considerable overhead,
// and ParseForm does not complain when URL encoding is off.
// Because an empty request body or url can also mean absence of all needed values,
// it is not in all cases a bad request, so let's return 422.
if parseErr != nil {
errors.Overall[DeserializationError] = parseErr.Error()
}
mapForm(formStruct, req.Form, errors)
validateAndMap(formStruct, context, errors, ifacePtr...)
}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/auth/cmds/cmds.go#L112-L135
|
func DeactivateCmd(noMetrics, noPortForwarding *bool) *cobra.Command {
deactivate := &cobra.Command{
Short: "Delete all ACLs, tokens, and admins, and deactivate Pachyderm auth",
Long: "Deactivate Pachyderm's auth system, which will delete ALL auth " +
"tokens, ACLs and admins, and expose all data in the cluster to any " +
"user with cluster access. Use with caution.",
Run: cmdutil.Run(func(args []string) error {
fmt.Println("Are you sure you want to delete ALL auth information " +
"(ACLs, tokens, and admins) in this cluster, and expose ALL data? yN")
confirm, err := bufio.NewReader(os.Stdin).ReadString('\n')
if !strings.Contains("yY", confirm[:1]) {
return fmt.Errorf("operation aborted")
}
c, err := client.NewOnUserMachine(!*noMetrics, !*noPortForwarding, "user")
if err != nil {
return fmt.Errorf("could not connect: %v", err)
}
defer c.Close()
_, err = c.Deactivate(c.Ctx(), &auth.DeactivateRequest{})
return grpcutil.ScrubGRPC(err)
}),
}
return cmdutil.CreateAlias(deactivate, "auth deactivate")
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L494-L505
|
func (c *ClusterTx) ContainerNodeList() ([]Container, error) {
node, err := c.NodeName()
if err != nil {
return nil, errors.Wrap(err, "Local node name")
}
filter := ContainerFilter{
Node: node,
Type: int(CTypeRegular),
}
return c.ContainerList(filter)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/flags/flag.go#L35-L49
|
func SetFlagsFromEnv(prefix string, fs *flag.FlagSet) error {
var err error
alreadySet := make(map[string]bool)
fs.Visit(func(f *flag.Flag) {
alreadySet[FlagToEnv(prefix, f.Name)] = true
})
usedEnvKey := make(map[string]bool)
fs.VisitAll(func(f *flag.Flag) {
if serr := setFlagFromEnv(fs, prefix, f.Name, usedEnvKey, alreadySet, true); serr != nil {
err = serr
}
})
verifyEnv(prefix, usedEnvKey, alreadySet)
return err
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/images.go#L702-L706
|
func (c *Cluster) ImageLastAccessUpdate(fingerprint string, date time.Time) error {
stmt := `UPDATE images SET last_use_date=? WHERE fingerprint=?`
err := exec(c.db, stmt, date, fingerprint)
return err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/types.go#L160-L172
|
func (t *KeyPathType) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch KeyPathType(in.String()) {
case KeyPathTypeNull:
*t = KeyPathTypeNull
case KeyPathTypeString:
*t = KeyPathTypeString
case KeyPathTypeArray:
*t = KeyPathTypeArray
default:
in.AddError(errors.New("unknown KeyPathType value"))
}
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L1301-L1304
|
func (e EnvelopeType) String() string {
name, _ := envelopeTypeMap[int32(e)]
return name
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/blobstore/blobstore.go#L139-L141
|
func Delete(c context.Context, blobKey appengine.BlobKey) error {
return DeleteMulti(c, []appengine.BlobKey{blobKey})
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/search/search.go#L216-L238
|
func (x *Index) Get(c context.Context, id string, dst interface{}) error {
if id == "" || !validIndexNameOrDocID(id) {
return fmt.Errorf("search: invalid ID %q", id)
}
req := &pb.ListDocumentsRequest{
Params: &pb.ListDocumentsParams{
IndexSpec: &x.spec,
StartDocId: proto.String(id),
Limit: proto.Int32(1),
},
}
res := &pb.ListDocumentsResponse{}
if err := internal.Call(c, "search", "ListDocuments", req, res); err != nil {
return err
}
if res.Status == nil || res.Status.GetCode() != pb.SearchServiceError_OK {
return fmt.Errorf("search: %s: %s", res.Status.GetCode(), res.Status.GetErrorDetail())
}
if len(res.Document) != 1 || res.Document[0].GetId() != id {
return ErrNoSuchDocument
}
return loadDoc(dst, res.Document[0], nil)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/artifact-uploader/main.go#L127-L151
|
func (o *Options) Run() error {
clusterConfig, err := loadClusterConfig()
if err != nil {
return fmt.Errorf("failed to load cluster config: %v", err)
}
client, err := kubernetes.NewForConfig(clusterConfig)
if err != nil {
return err
}
prowJobClient, err := kube.NewClientInCluster(o.ProwJobNamespace)
if err != nil {
return err
}
controller := artifact_uploader.NewController(client.CoreV1(), prowJobClient, o.Options)
stop := make(chan struct{})
defer close(stop)
go controller.Run(o.NumWorkers, stop)
// Wait forever
select {}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L2867-L2871
|
func (v SearchInResponseBodyParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork21(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/table/table.go#L337-L339
|
func NewFilename(id uint64, dir string) string {
return filepath.Join(dir, IDToFilename(id))
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/admin.go#L94-L110
|
func (c APIClient) Restore(ops []*admin.Op) (retErr error) {
restoreClient, err := c.AdminAPIClient.Restore(c.Ctx())
if err != nil {
return grpcutil.ScrubGRPC(err)
}
defer func() {
if _, err := restoreClient.CloseAndRecv(); err != nil && retErr == nil {
retErr = grpcutil.ScrubGRPC(err)
}
}()
for _, op := range ops {
if err := restoreClient.Send(&admin.RestoreRequest{Op: op}); err != nil {
return grpcutil.ScrubGRPC(err)
}
}
return nil
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/taskqueue/taskqueue.go#L463-L479
|
func ModifyLease(c context.Context, task *Task, queueName string, leaseTime int) error {
if queueName == "" {
queueName = "default"
}
req := &pb.TaskQueueModifyTaskLeaseRequest{
QueueName: []byte(queueName),
TaskName: []byte(task.Name),
EtaUsec: proto.Int64(task.ETA.UnixNano() / 1e3), // Used to verify ownership.
LeaseSeconds: proto.Float64(float64(leaseTime)),
}
res := &pb.TaskQueueModifyTaskLeaseResponse{}
if err := internal.Call(c, "taskqueue", "ModifyTaskLease", req, res); err != nil {
return err
}
task.ETA = time.Unix(0, *res.UpdatedEtaUsec*1e3)
return nil
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L530-L562
|
func FileWriter(path string, perm os.FileMode) *os.File {
if path == "" {
return nil
}
var err error
var file *os.File
if _, err = os.Stat(path); err != nil {
if _, err = os.Stat(filepath.Dir(path)); err != nil {
err = os.MkdirAll(filepath.Dir(path), perm)
if err != nil {
return nil
}
}
file, err = os.Create(path)
if err != nil {
return nil
}
err = file.Close()
if err != nil {
return nil
}
}
file, err = os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, perm)
if err != nil {
return nil
}
return file
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/channel.go#L506-L514
|
func (ch *Channel) Ping(ctx context.Context, hostPort string) error {
peer := ch.RootPeers().GetOrAdd(hostPort)
conn, err := peer.GetConnection(ctx)
if err != nil {
return err
}
return conn.ping(ctx)
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/appengine.go#L96-L98
|
func WithContext(parent context.Context, req *http.Request) context.Context {
return internal.WithContext(parent, req)
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/directory/directory_src.go#L59-L69
|
func (s *dirImageSource) GetBlob(ctx context.Context, info types.BlobInfo, cache types.BlobInfoCache) (io.ReadCloser, int64, error) {
r, err := os.Open(s.ref.layerPath(info.Digest))
if err != nil {
return nil, -1, err
}
fi, err := r.Stat()
if err != nil {
return nil, -1, err
}
return r, fi.Size(), nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L620-L644
|
func (h *dbHashTree) Copy() (HashTree, error) {
if err := h.Hash(); err != nil {
return nil, err
}
r, w := io.Pipe()
var eg errgroup.Group
eg.Go(func() (retErr error) {
defer func() {
if err := w.Close(); err != nil && retErr == nil {
retErr = err
}
}()
return h.Serialize(w)
})
var result HashTree
eg.Go(func() error {
var err error
result, err = DeserializeDBHashTree(pathlib.Dir(h.Path()), r)
return err
})
if err := eg.Wait(); err != nil {
return nil, err
}
return result, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/easyjson.go#L1255-L1259
|
func (v GetAllTimeSamplingProfileReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoMemory14(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/page.go#L482-L488
|
func (p *Page) MoveMouseBy(xOffset, yOffset int) error {
if err := p.session.MoveTo(nil, api.XYOffset{X: xOffset, Y: yOffset}); err != nil {
return fmt.Errorf("failed to move mouse: %s", err)
}
return nil
}
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/recover.go#L29-L59
|
func (mw *RecoverMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc {
// set the default Logger
if mw.Logger == nil {
mw.Logger = log.New(os.Stderr, "", 0)
}
return func(w ResponseWriter, r *Request) {
// catch user code's panic, and convert to http response
defer func() {
if reco := recover(); reco != nil {
trace := debug.Stack()
// log the trace
message := fmt.Sprintf("%s\n%s", reco, trace)
mw.logError(message)
// write error response
if mw.EnableResponseStackTrace {
Error(w, message, http.StatusInternalServerError)
} else {
Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}
}()
// call the handler
h(w, r)
}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L1141-L1166
|
func (c APIClient) ListFileF(repoName string, commitID string, path string, history int64, f func(fi *pfs.FileInfo) error) error {
fs, err := c.PfsAPIClient.ListFileStream(
c.Ctx(),
&pfs.ListFileRequest{
File: NewFile(repoName, commitID, path),
History: history,
},
)
if err != nil {
return grpcutil.ScrubGRPC(err)
}
for {
fi, err := fs.Recv()
if err == io.EOF {
return nil
} else if err != nil {
return grpcutil.ScrubGRPC(err)
}
if err := f(fi); err != nil {
if err == errutil.ErrBreak {
return nil
}
return err
}
}
}
|
https://github.com/gin-contrib/location/blob/0462caccbb9cc0b222a2d75a64830c360c603798/location.go#L41-L47
|
func New(config Config) gin.HandlerFunc {
location := newLocation(config)
return func(c *gin.Context) {
location.applyToContext(c)
}
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/prop.go#L168-L172
|
func getStructCodec(t reflect.Type) (*structCodec, error) {
structCodecsMutex.Lock()
defer structCodecsMutex.Unlock()
return getStructCodecLocked(t)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/css.go#L658-L663
|
func SetStyleSheetText(styleSheetID StyleSheetID, text string) *SetStyleSheetTextParams {
return &SetStyleSheetTextParams{
StyleSheetID: styleSheetID,
Text: text,
}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pkg/require/require.go#L13-L22
|
func Matches(tb testing.TB, expectedMatch string, actual string, msgAndArgs ...interface{}) {
tb.Helper()
r, err := regexp.Compile(expectedMatch)
if err != nil {
fatal(tb, msgAndArgs, "Match string provided (%v) is invalid", expectedMatch)
}
if !r.MatchString(actual) {
fatal(tb, msgAndArgs, "Actual string (%v) does not match pattern (%v)", actual, expectedMatch)
}
}
|
https://github.com/stefantalpalaru/pool/blob/df8b849d27751462526089005979b28064c1e08e/pool.go#L234-L238
|
func (pool *Pool) Add(f func(...interface{}) interface{}, args ...interface{}) {
job := &Job{f, args, nil, nil, make(chan bool), 0, pool.getNextJobId()}
pool.add_pipe <- job
<-job.added
}
|
https://github.com/jmank88/nuts/blob/8b28145dffc87104e66d074f62ea8080edfad7c8/key.go#L33-L39
|
func (c Key) Put(x uint64) {
s := uint(8 * (len(c) - 1))
for i := range c {
c[i] = byte(x >> s)
s -= 8
}
}
|
https://github.com/brankas/sentinel/blob/0ff081867c31a45cb71f5976ea6144fd06a557b5/sentinel.go#L137-L151
|
func (s *Sentinel) Register(server, shutdown interface{}, ignore ...func(error) bool) error {
// add server and shutdown funcs
var err error
s.serverFuncs, err = convertAndAppendContextFuncs(s.serverFuncs, server)
if err != nil {
return err
}
s.shutdownFuncs, err = convertAndAppendContextFuncs(s.shutdownFuncs, shutdown)
if err != nil {
return err
}
s.ignoreErrors = append(s.ignoreErrors, ignore...)
return nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L977-L983
|
func (c APIClient) PutFile(repoName string, commitID string, path string, reader io.Reader) (_ int, retErr error) {
pfc, err := c.newOneoffPutFileClient()
if err != nil {
return 0, err
}
return pfc.PutFile(repoName, commitID, path, reader)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/easyjson.go#L2080-L2084
|
func (v *DataEntry) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoIndexeddb18(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/types.go#L291-L293
|
func (t ContinueToLocationTargetCallFrames) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/spanish/step1.go#L10-L103
|
func step1(word *snowballword.SnowballWord) bool {
// Possible suffixes, longest first
suffix, suffixRunes := word.FirstSuffix(
"amientos", "imientos", "aciones", "amiento", "imiento",
"uciones", "logías", "idades", "encias", "ancias", "amente",
"adores", "adoras", "ución", "mente", "logía", "istas",
"ismos", "ibles", "encia", "anzas", "antes", "ancia",
"adora", "ación", "ables", "osos", "osas", "ivos", "ivas",
"ista", "ismo", "idad", "icos", "icas", "ible", "anza",
"ante", "ador", "able", "oso", "osa", "ivo", "iva",
"ico", "ica",
)
isInR1 := (word.R1start <= len(word.RS)-len(suffixRunes))
isInR2 := (word.R2start <= len(word.RS)-len(suffixRunes))
// Deal with special cases first. All of these will
// return if they are hit.
//
switch suffix {
case "":
// Nothing to do
return false
case "amente":
if isInR1 {
// Delete if in R1
word.RemoveLastNRunes(len(suffixRunes))
// if preceded by iv, delete if in R2 (and if further preceded by at,
// delete if in R2), otherwise,
// if preceded by os, ic or ad, delete if in R2
newSuffix, _ := word.RemoveFirstSuffixIfIn(word.R2start, "iv", "os", "ic", "ad")
if newSuffix == "iv" {
word.RemoveFirstSuffixIfIn(word.R2start, "at")
}
return true
}
return false
}
// All the following cases require the found suffix
// to be in R2.
if isInR2 == false {
return false
}
// Compound replacement cases. All these cases return
// if they are hit.
//
compoundReplacement := func(otherSuffixes ...string) bool {
word.RemoveLastNRunes(len(suffixRunes))
word.RemoveFirstSuffixIfIn(word.R2start, otherSuffixes...)
return true
}
switch suffix {
case "adora", "ador", "ación", "adoras", "adores", "aciones", "ante", "antes", "ancia", "ancias":
return compoundReplacement("ic")
case "mente":
return compoundReplacement("ante", "able", "ible")
case "idad", "idades":
return compoundReplacement("abil", "ic", "iv")
case "iva", "ivo", "ivas", "ivos":
return compoundReplacement("at")
}
// Simple replacement & deletion cases are all that remain.
//
simpleReplacement := func(repl string) bool {
word.ReplaceSuffixRunes(suffixRunes, []rune(repl), true)
return true
}
switch suffix {
case "logía", "logías":
return simpleReplacement("log")
case "ución", "uciones":
return simpleReplacement("u")
case "encia", "encias":
return simpleReplacement("ente")
case "anza", "anzas", "ico", "ica", "icos", "icas",
"ismo", "ismos", "able", "ables", "ible", "ibles",
"ista", "istas", "oso", "osa", "osos", "osas",
"amiento", "amientos", "imiento", "imientos":
word.RemoveLastNRunes(len(suffixRunes))
return true
}
log.Panicln("Unhandled suffix:", suffix)
return false
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/transaction.go#L161-L169
|
func (m CreateAccountBuilder) MutateTransaction(o *TransactionBuilder) error {
if m.Err != nil {
return m.Err
}
m.O.Body, m.Err = xdr.NewOperationBody(xdr.OperationTypeCreateAccount, m.CA)
o.TX.Operations = append(o.TX.Operations, m.O)
return m.Err
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peer.go#L198-L200
|
func (lop listOfPeers) Less(i, j int) bool {
return lop[i].Name < lop[j].Name
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/genny/vcs/options.go#L20-L36
|
func (opts *Options) Validate() error {
if opts.App.IsZero() {
opts.App = meta.New(".")
}
var found bool
for _, a := range Available {
if opts.Provider == a {
found = true
break
}
}
if !found {
return fmt.Errorf("unknown provider %q expecting one of %s", opts.Provider, strings.Join(Available, ", "))
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L1186-L1189
|
func (p ResolveNodeParams) WithExecutionContextID(executionContextID runtime.ExecutionContextID) *ResolveNodeParams {
p.ExecutionContextID = executionContextID
return &p
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/archive/transport.go#L146-L148
|
func (ref archiveReference) NewImageSource(ctx context.Context, sys *types.SystemContext) (types.ImageSource, error) {
return newImageSource(ctx, ref)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cdp/types.go#L543-L545
|
func (t *NodeType) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/reqres.go#L281-L296
|
func parseInboundFragment(framePool FramePool, frame *Frame, message message) (*readableFragment, error) {
rbuf := typed.NewReadBuffer(frame.SizedPayload())
fragment := new(readableFragment)
fragment.flags = rbuf.ReadSingleByte()
if err := message.read(rbuf); err != nil {
return nil, err
}
fragment.checksumType = ChecksumType(rbuf.ReadSingleByte())
fragment.checksum = rbuf.ReadBytes(fragment.checksumType.ChecksumSize())
fragment.contents = rbuf
fragment.onDone = func() {
framePool.Release(frame)
}
return fragment, rbuf.Err()
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift-copies.go#L342-L369
|
func validateClusterInfo(clusterName string, clusterInfo clientcmdCluster) []error {
var validationErrors []error
if reflect.DeepEqual(clientcmdCluster{}, clusterInfo) {
return []error{errEmptyCluster}
}
if len(clusterInfo.Server) == 0 {
if len(clusterName) == 0 {
validationErrors = append(validationErrors, errors.Errorf("default cluster has no server defined"))
} else {
validationErrors = append(validationErrors, errors.Errorf("no server found for cluster %q", clusterName))
}
}
// Make sure CA data and CA file aren't both specified
if len(clusterInfo.CertificateAuthority) != 0 && len(clusterInfo.CertificateAuthorityData) != 0 {
validationErrors = append(validationErrors, errors.Errorf("certificate-authority-data and certificate-authority are both specified for %v. certificate-authority-data will override", clusterName))
}
if len(clusterInfo.CertificateAuthority) != 0 {
clientCertCA, err := os.Open(clusterInfo.CertificateAuthority)
defer clientCertCA.Close()
if err != nil {
validationErrors = append(validationErrors, errors.Errorf("unable to read certificate-authority %v for %v due to %v", clusterInfo.CertificateAuthority, clusterName, err))
}
}
return validationErrors
}
|
https://github.com/qor/serializable_meta/blob/5fd8542db4170c6ce0f8d669b521803b87eb0a99/serializable_meta.go#L86-L224
|
func (serialize *SerializableMeta) ConfigureQorResourceBeforeInitialize(res resource.Resourcer) {
if res, ok := res.(*admin.Resource); ok {
res.GetAdmin().RegisterViewPath("github.com/qor/serializable_meta/views")
if _, ok := res.Value.(SerializableMetaInterface); ok {
res.Meta(&admin.Meta{
Name: "Kind",
Type: "hidden",
Valuer: func(value interface{}, context *qor.Context) interface{} {
defer func() {
if r := recover(); r != nil {
utils.ExitWithMsg("SerializableMeta: Can't Get Kind")
}
}()
return value.(SerializableMetaInterface).GetSerializableArgumentKind()
},
Setter: func(value interface{}, metaValue *resource.MetaValue, context *qor.Context) {
value.(SerializableMetaInterface).SetSerializableArgumentKind(utils.ToString(metaValue.Value))
},
})
res.Meta(&admin.Meta{
Name: "SerializableMeta",
Type: "serializable_meta",
Valuer: func(value interface{}, context *qor.Context) interface{} {
if serializeArgument, ok := value.(SerializableMetaInterface); ok {
return struct {
Value interface{}
Resource *admin.Resource
}{
Value: serializeArgument.GetSerializableArgument(serializeArgument),
Resource: serializeArgument.GetSerializableArgumentResource(),
}
}
return nil
},
FormattedValuer: func(value interface{}, context *qor.Context) interface{} {
if serializeArgument, ok := value.(SerializableMetaInterface); ok {
return serializeArgument.GetSerializableArgument(serializeArgument)
}
return nil
},
Setter: func(result interface{}, metaValue *resource.MetaValue, context *qor.Context) {
if serializeArgument, ok := result.(SerializableMetaInterface); ok {
if serializeArgumentResource := serializeArgument.GetSerializableArgumentResource(); serializeArgumentResource != nil {
var clearUpRecord, fillUpRecord func(record interface{}, metaors []resource.Metaor, metaValues []*resource.MetaValue)
// Keep original value, so if user don't have permission to update some fields, we won't lost the data
value := serializeArgument.GetSerializableArgument(serializeArgument)
for _, v := range serializeArgumentResource.Validators {
context.AddError(v.Handler(value, metaValue.MetaValues, context))
}
// Clear all nested slices if has related form data
clearUpRecord = func(record interface{}, metaors []resource.Metaor, metaValues []*resource.MetaValue) {
for _, meta := range metaors {
for _, metaValue := range metaValues {
if meta.GetName() == metaValue.Name {
if metaResource, ok := meta.GetResource().(*admin.Resource); ok && metaResource != nil && metaValue.MetaValues != nil {
nestedFieldValue := reflect.Indirect(reflect.ValueOf(record)).FieldByName(meta.GetFieldName())
if nestedFieldValue.Kind() == reflect.Struct {
clearUpRecord(nestedFieldValue.Addr().Interface(), metaResource.GetMetas([]string{}), metaValue.MetaValues.Values)
} else if nestedFieldValue.Kind() == reflect.Slice {
nestedFieldValue.Set(reflect.Zero(nestedFieldValue.Type()))
}
}
}
}
}
}
clearUpRecord(value, serializeArgumentResource.GetMetas([]string{}), metaValue.MetaValues.Values)
fillUpRecord = func(record interface{}, metaors []resource.Metaor, metaValues []*resource.MetaValue) {
for _, meta := range metaors {
for _, metaValue := range metaValues {
if meta.GetName() == metaValue.Name {
if setter := meta.GetSetter(); setter != nil {
setter(record, metaValue, context)
}
if metaResource, ok := meta.GetResource().(*admin.Resource); ok && metaResource != nil && metaValue.MetaValues != nil {
nestedFieldValue := reflect.Indirect(reflect.ValueOf(record)).FieldByName(meta.GetFieldName())
if meta.GetSetter() == nil || reflect.Indirect(nestedFieldValue).Type() == utils.ModelType(metaResource.NewStruct()) {
if nestedFieldValue.Kind() == reflect.Struct {
nestedValue := nestedFieldValue.Addr().Interface()
for _, v := range metaResource.Validators {
context.AddError(v.Handler(nestedValue, metaValue.MetaValues, context))
}
fillUpRecord(nestedValue, metaResource.GetMetas([]string{}), metaValue.MetaValues.Values)
for _, p := range metaResource.Processors {
context.AddError(p.Handler(nestedValue, metaValue.MetaValues, context))
}
}
if nestedFieldValue.Kind() == reflect.Slice {
nestedValue := reflect.New(nestedFieldValue.Type().Elem())
for _, v := range metaResource.Validators {
context.AddError(v.Handler(nestedValue, metaValue.MetaValues, context))
}
if destroy := metaValue.MetaValues.Get("_destroy"); destroy == nil || fmt.Sprint(destroy.Value) == "0" {
fillUpRecord(nestedValue.Interface(), metaResource.GetMetas([]string{}), metaValue.MetaValues.Values)
if !reflect.DeepEqual(reflect.Zero(nestedFieldValue.Type().Elem()).Interface(), nestedValue.Elem().Interface()) {
nestedFieldValue.Set(reflect.Append(nestedFieldValue, nestedValue.Elem()))
for _, p := range metaResource.Processors {
context.AddError(p.Handler(nestedValue, metaValue.MetaValues, context))
}
}
}
}
continue
}
}
}
}
}
}
fillUpRecord(value, serializeArgumentResource.GetMetas([]string{}), metaValue.MetaValues.Values)
for _, p := range serializeArgumentResource.Processors {
context.AddError(p.Handler(value, metaValue.MetaValues, context))
}
serializeArgument.SetSerializableArgumentValue(value)
}
}
},
})
res.NewAttrs("Kind", "SerializableMeta")
res.EditAttrs("ID", "Kind", "SerializableMeta")
}
}
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/builder/builder.go#L68-L74
|
func get(name string) (Builder, error) {
b, ok := builders[name]
if !ok {
return nil, errors.Errorf("unknown builder: %q", name)
}
return b, nil
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/log/api.go#L18-L20
|
func Debugf(ctx context.Context, format string, args ...interface{}) {
internal.Logf(ctx, 0, format, args...)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/cmdutil/cobra.go#L121-L146
|
func ParseFile(arg string) (*pfs.File, error) {
repoAndRest := strings.SplitN(arg, "@", 2)
if repoAndRest[0] == "" {
return nil, fmt.Errorf("invalid format \"%s\": repo cannot be empty", arg)
}
file := &pfs.File{
Commit: &pfs.Commit{
Repo: &pfs.Repo{
Name: repoAndRest[0],
},
ID: "",
},
Path: "",
}
if len(repoAndRest) > 1 {
commitAndPath := strings.SplitN(repoAndRest[1], ":", 2)
if commitAndPath[0] == "" {
return nil, fmt.Errorf("invalid format \"%s\": commit cannot be empty", arg)
}
file.Commit.ID = commitAndPath[0]
if len(commitAndPath) > 1 {
file.Path = commitAndPath[1]
}
}
return file, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/node.go#L384-L396
|
func (n *node) recoverAndclean() {
if n.IsDir() {
for _, child := range n.Children {
child.Parent = n
child.store = n.store
child.recoverAndclean()
}
}
if !n.ExpireTime.IsZero() {
n.store.ttlKeyHeap.push(n)
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/easyjson.go#L818-L822
|
func (v SamplingHeapProfile) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoHeapprofiler8(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/portforwarder.go#L169-L174
|
func (f *PortForwarder) RunForDashUI(localPort uint16) error {
if localPort == 0 {
localPort = dashUILocalPort
}
return f.Run("dash", localPort, 8080)
}
|
https://github.com/kelseyhightower/envconfig/blob/dd1402a4d99de9ac2f396cd6fcb957bc2c695ec1/envconfig.go#L222-L226
|
func MustProcess(prefix string, spec interface{}) {
if err := Process(prefix, spec); err != nil {
panic(err)
}
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/y.go#L102-L106
|
func Copy(a []byte) []byte {
b := make([]byte, len(a))
copy(b, a)
return b
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/approve/approvers/owners.go#L369-L377
|
func (ap Approvers) GetNoIssueApproversSet() sets.String {
approvers := sets.NewString()
for approver := range ap.NoIssueApprovers() {
approvers.Insert(approver)
}
return approvers
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L646-L667
|
func (c APIClient) GetObjects(hashes []string, offset uint64, size uint64, totalSize uint64, writer io.Writer) error {
var objects []*pfs.Object
for _, hash := range hashes {
objects = append(objects, &pfs.Object{Hash: hash})
}
getObjectsClient, err := c.ObjectAPIClient.GetObjects(
c.Ctx(),
&pfs.GetObjectsRequest{
Objects: objects,
OffsetBytes: offset,
SizeBytes: size,
TotalSize: totalSize,
},
)
if err != nil {
return grpcutil.ScrubGRPC(err)
}
if err := grpcutil.WriteFromStreamingBytesClient(getObjectsClient, writer); err != nil {
return grpcutil.ScrubGRPC(err)
}
return nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/robots/issue-creator/creator/creator.go#L142-L148
|
func RegisterSourceOrDie(name string, src IssueSource) {
if _, ok := sources[name]; ok {
glog.Fatalf("Cannot register an IssueSource with name %q, already exists!", name)
}
sources[name] = src
glog.Infof("Registered issue source '%s'.", name)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L1083-L1096
|
func (c *Client) GetPullRequest(org, repo string, number int) (*PullRequest, error) {
c.log("GetPullRequest", org, repo, number)
var pr PullRequest
_, err := c.request(&request{
// allow the description and draft fields
// https://developer.github.com/changes/2018-02-22-label-description-search-preview/
// https://developer.github.com/changes/2019-02-14-draft-pull-requests/
accept: "application/vnd.github.symmetra-preview+json, application/vnd.github.shadow-cat-preview",
method: http.MethodGet,
path: fmt.Sprintf("/repos/%s/%s/pulls/%d", org, repo, number),
exitCodes: []int{200},
}, &pr)
return &pr, err
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L488-L499
|
func (s *FileSequence) String() string {
var fs string
if s.frameSet != nil {
fs = s.frameSet.String()
}
buf := bytes.NewBufferString(s.dir)
buf.WriteString(s.basename)
buf.WriteString(fs)
buf.WriteString(s.padChar)
buf.WriteString(s.ext)
return buf.String()
}
|
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/base.go#L171-L195
|
func (b *Base) RemoveLogger(logger Logger) error {
for idx, rLogger := range b.loggers {
if rLogger == logger {
err := rLogger.ShutdownLogger()
if err != nil {
return err
}
b.loggers[idx] = b.loggers[len(b.loggers)-1]
b.loggers[len(b.loggers)-1] = nil
b.loggers = b.loggers[:len(b.loggers)-1]
return nil
}
}
// Remove any hook instances the logger has
for idx, hookLogger := range b.hookPreQueue {
if hookLogger == logger {
b.hookPreQueue[idx] = b.hookPreQueue[len(b.hookPreQueue)-1]
b.hookPreQueue[len(b.hookPreQueue)-1] = nil
b.hookPreQueue = b.hookPreQueue[:len(b.hookPreQueue)-1]
}
}
return nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/copy/copy.go#L742-L751
|
func diffIDComputationGoroutine(dest chan<- diffIDResult, layerStream io.ReadCloser, decompressor compression.DecompressorFunc) {
result := diffIDResult{
digest: "",
err: errors.New("Internal error: unexpected panic in diffIDComputationGoroutine"),
}
defer func() { dest <- result }()
defer layerStream.Close() // We do not care to bother the other end of the pipe with other failures; we send them to dest instead.
result.digest, result.err = computeDiffID(layerStream, decompressor)
}
|
https://github.com/grokify/go-scim-client/blob/800878015236174e45b05db1ec125aae20a093e4/api_client.go#L157-L300
|
func (c *APIClient) prepareRequest(
ctx context.Context,
path string, method string,
postBody interface{},
headerParams map[string]string,
queryParams url.Values,
formParams url.Values,
fileName string,
fileBytes []byte) (localVarRequest *http.Request, err error) {
var body *bytes.Buffer
// Detect postBody type and post.
if postBody != nil {
contentType := headerParams["Content-Type"]
if contentType == "" {
contentType = detectContentType(postBody)
headerParams["Content-Type"] = contentType
}
body, err = setBody(postBody, contentType)
if err != nil {
return nil, err
}
}
// add form parameters and file if available.
if len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") {
if body != nil {
return nil, errors.New("Cannot specify postBody and multipart form at the same time.")
}
body = &bytes.Buffer{}
w := multipart.NewWriter(body)
for k, v := range formParams {
for _, iv := range v {
if strings.HasPrefix(k, "@") { // file
err = addFile(w, k[1:], iv)
if err != nil {
return nil, err
}
} else { // form value
w.WriteField(k, iv)
}
}
}
if len(fileBytes) > 0 && fileName != "" {
w.Boundary()
//_, fileNm := filepath.Split(fileName)
part, err := w.CreateFormFile("file", filepath.Base(fileName))
if err != nil {
return nil, err
}
_, err = part.Write(fileBytes)
if err != nil {
return nil, err
}
// Set the Boundary in the Content-Type
headerParams["Content-Type"] = w.FormDataContentType()
}
// Set Content-Length
headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len())
w.Close()
}
// Setup path and query parameters
url, err := url.Parse(path)
if err != nil {
return nil, err
}
// Adding Query Param
query := url.Query()
for k, v := range queryParams {
for _, iv := range v {
query.Add(k, iv)
}
}
// Encode the parameters.
url.RawQuery = query.Encode()
// Generate a new request
if body != nil {
localVarRequest, err = http.NewRequest(method, url.String(), body)
} else {
localVarRequest, err = http.NewRequest(method, url.String(), nil)
}
if err != nil {
return nil, err
}
// add header parameters, if any
if len(headerParams) > 0 {
headers := http.Header{}
for h, v := range headerParams {
headers.Set(h, v)
}
localVarRequest.Header = headers
}
// Override request host, if applicable
if c.cfg.Host != "" {
localVarRequest.Host = c.cfg.Host
}
// Add the user agent to the request.
localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent)
if ctx != nil {
// add context to the request
localVarRequest = localVarRequest.WithContext(ctx)
// Walk through any authentication.
// OAuth2 authentication
if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok {
// We were able to grab an oauth2 token from the context
var latestToken *oauth2.Token
if latestToken, err = tok.Token(); err != nil {
return nil, err
}
latestToken.SetAuthHeader(localVarRequest)
}
// Basic HTTP Authentication
if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok {
localVarRequest.SetBasicAuth(auth.UserName, auth.Password)
}
// AccessToken Authentication
if auth, ok := ctx.Value(ContextAccessToken).(string); ok {
localVarRequest.Header.Add("Authorization", "Bearer "+auth)
}
}
for header, value := range c.cfg.DefaultHeader {
localVarRequest.Header.Add(header, value)
}
return localVarRequest, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/heapprofiler.go#L142-L145
|
func (p GetObjectByHeapObjectIDParams) WithObjectGroup(objectGroup string) *GetObjectByHeapObjectIDParams {
p.ObjectGroup = objectGroup
return &p
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/paths.go#L139-L141
|
func nicPath(dcid, srvid, nicid string) string {
return nicColPath(dcid, srvid) + slash(nicid)
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/main.go#L97-L107
|
func runCommand(client cmd.CommandClient, cmdLine *cmd.CommandLine) (resp *http.Response, err error) {
cmds := strings.Split(cmdLine.Command, " ")
if cmdLine.ShowHelp {
err = client.ShowCommandHelp(cmdLine.Command)
} else if len(cmds) > 1 && cmds[1] == "actions" {
err = client.ShowAPIActions(cmdLine.Command)
} else {
resp, err = client.RunCommand(cmdLine.Command)
}
return
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/mapping.go#L70-L73
|
func (m *Mapping) FieldColumnName(name string) string {
field := m.FieldByName(name)
return fmt.Sprintf("%s.%s", entityTable(m.Name), field.Column())
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/applicationcache/applicationcache.go#L58-L67
|
func (p *GetApplicationCacheForFrameParams) Do(ctx context.Context) (applicationCache *ApplicationCache, err error) {
// execute
var res GetApplicationCacheForFrameReturns
err = cdp.Execute(ctx, CommandGetApplicationCacheForFrame, p, &res)
if err != nil {
return nil, err
}
return res.ApplicationCache, nil
}
|
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/utils/sanitize.go#L102-L115
|
func SanitizeTitle(s string) string {
p := SanitizeAccent(s)
r, _ := regexp.Compile("[^A-Za-z0-9 ']+")
p = r.ReplaceAllString(p, "")
p = strings.Replace(p, " ", "-", -1)
r, _ = regexp.Compile("^-|-$")
p = r.ReplaceAllString(p, "")
p = strings.Replace(p, "'", "-", -1)
r, _ = regexp.Compile("-+")
p = r.ReplaceAllString(p, "-")
p = strings.Replace(p, "&", "and", -1)
p = strings.ToLower(p)
return p
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L87-L93
|
func LoadFile(path, pkg string) (*File, error) {
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
return LoadData(path, pkg, data)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v3compactor/periodic.go#L98-L172
|
func (pc *Periodic) Run() {
compactInterval := pc.getCompactInterval()
retryInterval := pc.getRetryInterval()
retentions := pc.getRetentions()
go func() {
lastSuccess := pc.clock.Now()
baseInterval := pc.period
for {
pc.revs = append(pc.revs, pc.rg.Rev())
if len(pc.revs) > retentions {
pc.revs = pc.revs[1:] // pc.revs[0] is always the rev at pc.period ago
}
select {
case <-pc.ctx.Done():
return
case <-pc.clock.After(retryInterval):
pc.mu.Lock()
p := pc.paused
pc.mu.Unlock()
if p {
continue
}
}
if pc.clock.Now().Sub(lastSuccess) < baseInterval {
continue
}
// wait up to initial given period
if baseInterval == pc.period {
baseInterval = compactInterval
}
rev := pc.revs[0]
if pc.lg != nil {
pc.lg.Info(
"starting auto periodic compaction",
zap.Int64("revision", rev),
zap.Duration("compact-period", pc.period),
)
} else {
plog.Noticef("Starting auto-compaction at revision %d (retention: %v)", rev, pc.period)
}
_, err := pc.c.Compact(pc.ctx, &pb.CompactionRequest{Revision: rev})
if err == nil || err == mvcc.ErrCompacted {
if pc.lg != nil {
pc.lg.Info(
"completed auto periodic compaction",
zap.Int64("revision", rev),
zap.Duration("compact-period", pc.period),
zap.Duration("took", time.Since(lastSuccess)),
)
} else {
plog.Noticef("Finished auto-compaction at revision %d", rev)
}
lastSuccess = pc.clock.Now()
} else {
if pc.lg != nil {
pc.lg.Warn(
"failed auto periodic compaction",
zap.Int64("revision", rev),
zap.Duration("compact-period", pc.period),
zap.Duration("retry-interval", retryInterval),
zap.Error(err),
)
} else {
plog.Noticef("Failed auto-compaction at revision %d (%v)", rev, err)
plog.Noticef("Retry after %v", retryInterval)
}
}
}
}()
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/tasks/get_tasks_parameters.go#L81-L84
|
func (o *GetTasksParams) WithContext(ctx context.Context) *GetTasksParams {
o.SetContext(ctx)
return o
}
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/gzip.go#L90-L93
|
func (w *gzipResponseWriter) CloseNotify() <-chan bool {
notifier := w.ResponseWriter.(http.CloseNotifier)
return notifier.CloseNotify()
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pps.go#L453-L484
|
func (c APIClient) GetLogs(
pipelineName string,
jobID string,
data []string,
datumID string,
master bool,
follow bool,
tail int64,
) *LogsIter {
request := pps.GetLogsRequest{
Master: master,
Follow: follow,
Tail: tail,
}
resp := &LogsIter{}
if pipelineName != "" {
request.Pipeline = NewPipeline(pipelineName)
}
if jobID != "" {
request.Job = NewJob(jobID)
}
request.DataFilters = data
if datumID != "" {
request.Datum = &pps.Datum{
Job: NewJob(jobID),
ID: datumID,
}
}
resp.logsClient, resp.err = c.PpsAPIClient.GetLogs(c.Ctx(), &request)
resp.err = grpcutil.ScrubGRPC(resp.err)
return resp
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_btrfs.go#L1569-L1605
|
func (s *storageBtrfs) ContainerSnapshotCreateEmpty(snapshotContainer container) error {
logger.Debugf("Creating empty BTRFS storage volume for snapshot \"%s\" on storage pool \"%s\"", s.volume.Name, s.pool.Name)
// Mount the storage pool.
_, err := s.StoragePoolMount()
if err != nil {
return err
}
// Create the snapshot subvole path on the storage pool.
sourceName, _, _ := containerGetParentAndSnapshotName(snapshotContainer.Name())
snapshotSubvolumePath := getSnapshotSubvolumePath(snapshotContainer.Project(), s.pool.Name, sourceName)
snapshotSubvolumeName := getSnapshotMountPoint(snapshotContainer.Project(), s.pool.Name, snapshotContainer.Name())
if !shared.PathExists(snapshotSubvolumePath) {
err := os.MkdirAll(snapshotSubvolumePath, containersDirMode)
if err != nil {
return err
}
}
err = btrfsSubVolumeCreate(snapshotSubvolumeName)
if err != nil {
return err
}
snapshotMntPointSymlinkTarget := shared.VarPath("storage-pools", s.pool.Name, "containers-snapshots", projectPrefix(snapshotContainer.Project(), sourceName))
snapshotMntPointSymlink := shared.VarPath("snapshots", projectPrefix(snapshotContainer.Project(), sourceName))
if !shared.PathExists(snapshotMntPointSymlink) {
err := createContainerMountpoint(snapshotMntPointSymlinkTarget, snapshotMntPointSymlink, snapshotContainer.IsPrivileged())
if err != nil {
return err
}
}
logger.Debugf("Created empty BTRFS storage volume for snapshot \"%s\" on storage pool \"%s\"", s.volume.Name, s.pool.Name)
return nil
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/usermanagment.go#L190-L195
|
func (c *Client) UpdateGroup(groupid string, obj Group) (*Group, error) {
url := umGroupPath(groupid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty)
ret := &Group{}
err := c.client.Put(url, obj, ret, http.StatusAccepted)
return ret, err
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/grpc.go#L15-L48
|
func (t Type) GRPCCode() codes.Code {
switch t {
case InvalidArgument:
return codes.InvalidArgument
case OutOfRange:
return codes.OutOfRange
case NotFound:
return codes.NotFound
case Conflict:
case AlreadyExists:
return codes.AlreadyExists
case Unauthorized:
return codes.Unauthenticated
case PermissionDenied:
return codes.PermissionDenied
case Timeout:
return codes.DeadlineExceeded
case NotImplemented:
return codes.Unimplemented
case TemporarilyUnavailable:
return codes.Unavailable
case PermanentlyUnavailable:
return codes.FailedPrecondition
case Canceled:
return codes.Canceled
case ResourceExhausted:
return codes.ResourceExhausted
case Internal:
case Unknown:
return codes.Unknown
}
return codes.Unknown
}
|
https://github.com/codegangsta/martini-contrib/blob/8ce6181c2609699e4c7cd30994b76a850a9cdadc/acceptlang/handler.go#L52-L66
|
func (al AcceptLanguages) String() string {
output := bytes.NewBufferString("")
for i, language := range al {
output.WriteString(fmt.Sprintf("%s (%1.1f)", language.Language, language.Quality))
if i != len(al)-1 {
output.WriteString(", ")
}
}
if output.Len() == 0 {
output.WriteString("[]")
}
return output.String()
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/repo/repo.go#L228-L250
|
func ListRepositories(workspace *rule.File) (repos []Repo, repoNamesByFile map[*rule.File][]string, err error) {
repoNamesByFile = make(map[*rule.File][]string)
repos, repoNamesByFile[workspace] = getRepos(workspace.Rules)
for _, d := range workspace.Directives {
switch d.Key {
case "repository_macro":
f, defName, err := parseRepositoryMacroDirective(d.Value)
if err != nil {
return nil, nil, err
}
f = filepath.Join(filepath.Dir(workspace.Path), filepath.Clean(f))
macroFile, err := rule.LoadMacroFile(f, "", defName)
if err != nil {
return nil, nil, err
}
currRepos, names := getRepos(macroFile.Rules)
repoNamesByFile[macroFile] = names
repos = append(repos, currRepos...)
}
}
return repos, repoNamesByFile, nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/httpclient/http.go#L158-L184
|
func NewPB(pb *ParamBlock) HTTPClient {
responseHeaderTimeout := pb.ResponseHeaderTimeout
if responseHeaderTimeout == 0 {
responseHeaderTimeout = defaultResponseHeaderTimeout
}
dumpFormat := pb.DumpFormat
if dumpFormat == 0 {
dumpFormat = NoDump
}
hiddenHeaders := pb.HiddenHeaders
if hiddenHeaders == nil {
hiddenHeaders = defaultHiddenHeaders // immutable
} else {
hiddenHeaders = copyHiddenHeaders(hiddenHeaders) // copy to avoid side-effects
}
dc := &dumpClient{Client: newRawClient(pb.NoRedirect, pb.NoCertCheck, pb.DisableKeepAlives, responseHeaderTimeout)}
dc.isInsecure = func() bool {
return pb.Insecure
}
dc.dumpFormat = func() Format {
return dumpFormat
}
dc.hiddenHeaders = func() map[string]bool {
return hiddenHeaders
}
return dc
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/server.go#L1384-L1421
|
func (s *EtcdServer) MoveLeader(ctx context.Context, lead, transferee uint64) error {
now := time.Now()
interval := time.Duration(s.Cfg.TickMs) * time.Millisecond
if lg := s.getLogger(); lg != nil {
lg.Info(
"leadership transfer starting",
zap.String("local-member-id", s.ID().String()),
zap.String("current-leader-member-id", types.ID(lead).String()),
zap.String("transferee-member-id", types.ID(transferee).String()),
)
} else {
plog.Infof("%s starts leadership transfer from %s to %s", s.ID(), types.ID(lead), types.ID(transferee))
}
s.r.TransferLeadership(ctx, lead, transferee)
for s.Lead() != transferee {
select {
case <-ctx.Done(): // time out
return ErrTimeoutLeaderTransfer
case <-time.After(interval):
}
}
// TODO: drain all requests, or drop all messages to the old leader
if lg := s.getLogger(); lg != nil {
lg.Info(
"leadership transfer finished",
zap.String("local-member-id", s.ID().String()),
zap.String("old-leader-member-id", types.ID(lead).String()),
zap.String("new-leader-member-id", types.ID(transferee).String()),
zap.Duration("took", time.Since(now)),
)
} else {
plog.Infof("%s finished leadership transfer from %s to %s (took %v)", s.ID(), types.ID(lead), types.ID(transferee), time.Since(now))
}
return nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ss.go#L37-L41
|
func New(h string, a rsapi.Authenticator) *API {
api := rsapi.New(h, a)
api.Metadata = GenMetadata
return &API{API: api}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/mvcc/watcher_group.go#L194-L220
|
func (wg *watcherGroup) delete(wa *watcher) bool {
if _, ok := wg.watchers[wa]; !ok {
return false
}
wg.watchers.delete(wa)
if wa.end == nil {
wg.keyWatchers.delete(wa)
return true
}
ivl := adt.NewStringAffineInterval(string(wa.key), string(wa.end))
iv := wg.ranges.Find(ivl)
if iv == nil {
return false
}
ws := iv.Val.(watcherSet)
delete(ws, wa)
if len(ws) == 0 {
// remove interval missing watchers
if ok := wg.ranges.Delete(ivl); !ok {
panic("could not remove watcher from interval tree")
}
}
return true
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L4592-L4596
|
func (v *GetCookiesReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork34(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L502-L505
|
func (p SynthesizeScrollGestureParams) WithGestureSourceType(gestureSourceType GestureType) *SynthesizeScrollGestureParams {
p.GestureSourceType = gestureSourceType
return &p
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/integration/util.go#L27-L35
|
func mustWaitPinReady(t *testing.T, cli *clientv3.Client) {
// TODO: decrease timeout after balancer rewrite!!!
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
_, err := cli.Get(ctx, "foo")
cancel()
if err != nil {
t.Fatal(err)
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/endpoints.go#L151-L231
|
func (e *Endpoints) up(config *Config) error {
e.mu.Lock()
defer e.mu.Unlock()
e.servers = map[kind]*http.Server{
devlxd: config.DevLxdServer,
local: config.RestServer,
network: config.RestServer,
cluster: config.RestServer,
pprof: pprofCreateServer(),
}
e.cert = config.Cert
e.inherited = map[kind]bool{}
var err error
// Check for socket activation.
systemdListeners := util.GetListeners(e.systemdListenFDsStart)
if len(systemdListeners) > 0 {
e.listeners = activatedListeners(systemdListeners, e.cert)
for kind := range e.listeners {
e.inherited[kind] = true
}
} else {
e.listeners = map[kind]net.Listener{}
e.listeners[local], err = localCreateListener(config.UnixSocket, config.LocalUnixSocketGroup)
if err != nil {
return fmt.Errorf("local endpoint: %v", err)
}
}
// Start the devlxd listener
e.listeners[devlxd], err = createDevLxdlListener(config.Dir)
if err != nil {
return err
}
if config.NetworkAddress != "" {
listener, ok := e.listeners[network]
if ok {
logger.Infof("Replacing inherited TCP socket with configured one")
listener.Close()
e.inherited[network] = false
}
// Errors here are not fatal and are just logged.
e.listeners[network] = networkCreateListener(config.NetworkAddress, e.cert)
isCovered := util.IsAddressCovered(config.ClusterAddress, config.NetworkAddress)
if config.ClusterAddress != "" && !isCovered {
e.listeners[cluster], err = clusterCreateListener(config.ClusterAddress, e.cert)
if err != nil {
return err
}
logger.Infof("Starting cluster handler:")
e.serveHTTP(cluster)
}
}
if config.DebugAddress != "" {
e.listeners[pprof], err = pprofCreateListener(config.DebugAddress)
if err != nil {
return err
}
logger.Infof("Starting pprof handler:")
e.serveHTTP(pprof)
}
logger.Infof("Starting /dev/lxd handler:")
e.serveHTTP(devlxd)
logger.Infof("REST API daemon:")
e.serveHTTP(local)
e.serveHTTP(network)
return nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/examples/auditail/main.go#L104-L108
|
func printAudits(entries []*cm15.AuditEntry) {
for _, a := range entries {
fmt.Printf("[%v] <%v>: %v\n", a.UpdatedAt, a.UserEmail, a.Summary)
}
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/context_builder.go#L119-L125
|
func (cb *ContextBuilder) SetRoutingKey(rk string) *ContextBuilder {
if cb.CallOptions == nil {
cb.CallOptions = new(CallOptions)
}
cb.CallOptions.RoutingKey = rk
return cb
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nitro.go#L711-L722
|
func (m *Nitro) GetSnapshots() []*Snapshot {
var snaps []*Snapshot
buf := m.snapshots.MakeBuf()
defer m.snapshots.FreeBuf(buf)
iter := m.snapshots.NewIterator(CompareSnapshot, buf)
iter.SeekFirst()
for ; iter.Valid(); iter.Next() {
snaps = append(snaps, (*Snapshot)(iter.Get()))
}
return snaps
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/metadata/action.go#L52-L61
|
func (a *Action) paramsByLocation(loc Location) []string {
var res []string
for _, p := range a.APIParams {
if p.Location == loc {
res = append(res, p.Name)
}
}
sort.Strings(res)
return res
}
|
https://github.com/nicholasjackson/bench/blob/2df9635f0ad020b2e82616b0fd87130aaa1ee12e/results/summary.go#L41-L102
|
func (t *TabularResults) Tabulate(results []ResultSet) []Row {
var rows []Row
startTime := time.Unix(0, 0)
for _, bucket := range results {
if len(bucket) > 0 {
var elapsedTime time.Duration
if startTime == time.Unix(0, 0) {
startTime = bucket[0].Timestamp
}
elapsedTime = bucket[0].Timestamp.Sub(startTime)
row := Row{
StartTime: bucket[0].Timestamp,
ElapsedTime: elapsedTime,
Threads: 0,
TotalRequests: 0,
TotalFailures: 0,
TotalSuccess: 0,
TotalTimeouts: 0,
AvgRequestTime: 0,
}
totalRequestTime := 0 * time.Second
maxThreads := 0
for _, r := range bucket {
row.TotalRequests++
if r.Error != nil {
if _, ok := r.Error.(errors.Timeout); ok {
row.TotalTimeouts++
}
row.TotalFailures++
} else {
row.TotalSuccess++
totalRequestTime += r.RequestTime
}
if r.Threads > maxThreads {
maxThreads = r.Threads
row.Threads = maxThreads
}
}
if totalRequestTime != 0 && row.TotalSuccess != 0 {
avgTime := int64(totalRequestTime) / int64(row.TotalSuccess)
row.AvgRequestTime = time.Duration(avgTime)
}
rows = append(rows, row)
}
}
return rows
}
|
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/part.go#L167-L218
|
func (p *Part) convertFromDetectedCharset(r io.Reader) (io.Reader, error) {
// Attempt to detect character set from part content.
var cd *chardet.Detector
switch p.ContentType {
case "text/html":
cd = chardet.NewHtmlDetector()
default:
cd = chardet.NewTextDetector()
}
buf, err := ioutil.ReadAll(r)
if err != nil {
return nil, errors.WithStack(err)
}
cs, err := cd.DetectBest(buf)
switch err {
case nil:
// Carry on
case chardet.NotDetectedError:
p.addWarning(ErrorCharsetDeclaration, "charset could not be detected: %v", err)
default:
return nil, errors.WithStack(err)
}
// Restore r.
r = bytes.NewReader(buf)
if cs == nil || cs.Confidence < minCharsetConfidence {
// Low confidence, use declared character set.
return p.convertFromStatedCharset(r), nil
}
// Confidence exceeded our threshold, use detected character set.
if p.Charset != "" && !strings.EqualFold(cs.Charset, p.Charset) {
p.addWarning(ErrorCharsetDeclaration,
"declared charset %q, detected %q, confidence %d",
p.Charset, cs.Charset, cs.Confidence)
}
reader, err := coding.NewCharsetReader(cs.Charset, r)
if err != nil {
// Failed to get a conversion reader.
p.addWarning(ErrorCharsetConversion, err.Error())
} else {
r = reader
p.OrigCharset = p.Charset
p.Charset = cs.Charset
}
return r, nil
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/gossip_channel.go#L82-L84
|
func (c *gossipChannel) GossipBroadcast(update GossipData) {
c.relayBroadcast(c.ourself.Name, update)
}
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/amino.go#L233-L254
|
func (cdc *Codec) UnmarshalBinaryLengthPrefixed(bz []byte, ptr interface{}) error {
if len(bz) == 0 {
return errors.New("UnmarshalBinaryLengthPrefixed cannot decode empty bytes")
}
// Read byte-length prefix.
u64, n := binary.Uvarint(bz)
if n < 0 {
return fmt.Errorf("Error reading msg byte-length prefix: got code %v", n)
}
if u64 > uint64(len(bz)-n) {
return fmt.Errorf("Not enough bytes to read in UnmarshalBinaryLengthPrefixed, want %v more bytes but only have %v",
u64, len(bz)-n)
} else if u64 < uint64(len(bz)-n) {
return fmt.Errorf("Bytes left over in UnmarshalBinaryLengthPrefixed, should read %v more bytes but have %v",
u64, len(bz)-n)
}
bz = bz[n:]
// Decode.
return cdc.UnmarshalBinaryBare(bz, ptr)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/db.go#L161-L259
|
func OpenCluster(name string, store dqlite.ServerStore, address, dir string, timeout time.Duration, options ...dqlite.DriverOption) (*Cluster, error) {
db, err := cluster.Open(name, store, options...)
if err != nil {
return nil, errors.Wrap(err, "failed to open database")
}
// Test that the cluster database is operational. We wait up to the
// given timeout , in case there's no quorum of nodes online yet.
timer := time.After(timeout)
for i := 0; ; i++ {
// Log initial attempts at debug level, but use warn
// level after the 5'th attempt (about 10 seconds).
// After the 15'th attempt (about 30 seconds), log
// only one attempt every 5.
logPriority := 1 // 0 is discard, 1 is Debug, 2 is Warn
if i > 5 {
logPriority = 2
if i > 15 && !((i % 5) == 0) {
logPriority = 0
}
}
err = db.Ping()
if err == nil {
break
}
cause := errors.Cause(err)
if cause != dqlite.ErrNoAvailableLeader {
return nil, err
}
switch logPriority {
case 1:
logger.Debugf("Failed connecting to global database (attempt %d): %v", i, err)
case 2:
logger.Warnf("Failed connecting to global database (attempt %d): %v", i, err)
}
time.Sleep(2 * time.Second)
select {
case <-timer:
return nil, fmt.Errorf("failed to connect to cluster database")
default:
}
}
nodesVersionsMatch, err := cluster.EnsureSchema(db, address, dir)
if err != nil {
return nil, errors.Wrap(err, "failed to ensure schema")
}
db.SetMaxOpenConns(1)
db.SetMaxIdleConns(1)
if !nodesVersionsMatch {
cluster := &Cluster{
db: db,
stmts: map[int]*sql.Stmt{},
}
return cluster, ErrSomeNodesAreBehind
}
stmts, err := cluster.PrepareStmts(db)
if err != nil {
return nil, errors.Wrap(err, "Failed to prepare statements")
}
cluster := &Cluster{
db: db,
stmts: stmts,
}
// Figure out the ID of this node.
err = cluster.Transaction(func(tx *ClusterTx) error {
nodes, err := tx.Nodes()
if err != nil {
return errors.Wrap(err, "failed to fetch nodes")
}
if len(nodes) == 1 && nodes[0].Address == "0.0.0.0" {
// We're not clustered
cluster.NodeID(1)
return nil
}
for _, node := range nodes {
if node.Address == address {
cluster.nodeID = node.ID
return nil
}
}
return fmt.Errorf("no node registered with address %s", address)
})
if err != nil {
return nil, err
}
return cluster, err
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/apis/prowjobs/v1/zz_generated.deepcopy.go#L142-L147
|
func (in *ProwJob) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/log/types.go#L135-L137
|
func (t Level) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/log15/stack/stack.go#L176-L181
|
func (pcs Trace) TrimAbove(pc Call) Trace {
for len(pcs) > 0 && pcs[len(pcs)-1] != pc {
pcs = pcs[:len(pcs)-1]
}
return pcs
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/etcdserverpb/rpc.pb.go#L1111-L1119
|
func (*Compare) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
return _Compare_OneofMarshaler, _Compare_OneofUnmarshaler, _Compare_OneofSizer, []interface{}{
(*Compare_Version)(nil),
(*Compare_CreateRevision)(nil),
(*Compare_ModRevision)(nil),
(*Compare_Value)(nil),
(*Compare_Lease)(nil),
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/rpcpb/member.go#L133-L153
|
func (m *Member) CheckCompact(rev int64) error {
cli, err := m.CreateEtcdClient()
if err != nil {
return fmt.Errorf("%v (%q)", err, m.EtcdClientEndpoint)
}
defer cli.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
wch := cli.Watch(ctx, "\x00", clientv3.WithFromKey(), clientv3.WithRev(rev-1))
wr, ok := <-wch
cancel()
if !ok {
return fmt.Errorf("watch channel terminated (endpoint %q)", m.EtcdClientEndpoint)
}
if wr.CompactRevision != rev {
return fmt.Errorf("got compact revision %v, wanted %v (endpoint %q)", wr.CompactRevision, rev, m.EtcdClientEndpoint)
}
return nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.