_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/base.go#L203-L215
|
func (b *Base) ClearLoggers() error {
for _, logger := range b.loggers {
err := logger.ShutdownLogger()
if err != nil {
return err
}
}
b.loggers = make([]Logger, 0)
b.hookPreQueue = make([]HookPreQueue, 0)
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L2972-L2976
|
func (v *ExecutionContextDescription) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime27(&r, v)
return r.Error()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pubsub/reporter/reporter.go#L92-L120
|
func (c *Client) Report(pj *prowapi.ProwJob) ([]*prowapi.ProwJob, error) {
message := c.generateMessageFromPJ(pj)
ctx := context.Background()
client, err := pubsub.NewClient(ctx, message.Project)
if err != nil {
return nil, fmt.Errorf("could not create pubsub Client: %v", err)
}
topic := client.Topic(message.Topic)
d, err := json.Marshal(message)
if err != nil {
return nil, fmt.Errorf("could not marshal pubsub report: %v", err)
}
res := topic.Publish(ctx, &pubsub.Message{
Data: d,
})
_, err = res.Get(ctx)
if err != nil {
return nil, fmt.Errorf(
"failed to publish pubsub message with run ID %q to topic: \"%s/%s\". %v",
message.RunID, message.Project, message.Topic, err)
}
return []*prowapi.ProwJob{pj}, nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/response.go#L213-L227
|
func ForwardedResponseIfVolumeIsRemote(d *Daemon, r *http.Request, poolID int64, volumeName string, volumeType int) Response {
if queryParam(r, "target") != "" {
return nil
}
cert := d.endpoints.NetworkCert()
client, err := cluster.ConnectIfVolumeIsRemote(d.cluster, poolID, volumeName, volumeType, cert)
if err != nil && err != db.ErrNoSuchObject {
return SmartError(err)
}
if client == nil {
return nil
}
return ForwardedResponse(client, r)
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/raft.go#L969-L986
|
func (r *Raft) processRPC(rpc RPC) {
if err := r.checkRPCHeader(rpc); err != nil {
rpc.Respond(nil, err)
return
}
switch cmd := rpc.Command.(type) {
case *AppendEntriesRequest:
r.appendEntries(rpc, cmd)
case *RequestVoteRequest:
r.requestVote(rpc, cmd)
case *InstallSnapshotRequest:
r.installSnapshot(rpc, cmd)
default:
r.logger.Error(fmt.Sprintf("Got unexpected command: %#v", rpc.Command))
rpc.Respond(nil, fmt.Errorf("unexpected command"))
}
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/region.go#L28-L33
|
func (r region) Int() int64 {
if r.typ.Kind != KindInt || r.typ.Size != r.p.proc.PtrSize() {
panic("not an int: " + r.typ.Name)
}
return r.p.proc.ReadInt(r.a)
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/ops.go#L357-L366
|
func txPrintRaw(st *State) {
// XXX TODO: mark_raw handling
arg := st.sa
if arg == nil {
st.Warnf("Use of nil to print\n")
} else {
st.AppendOutputString(interfaceToString(arg))
}
st.Advance()
}
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/cmpopts/ignore.go#L67-L70
|
func IgnoreInterfaces(ifaces interface{}) cmp.Option {
tf := newIfaceFilter(ifaces)
return cmp.FilterPath(tf.filter, cmp.Ignore())
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/headlessexperimental/easyjson.go#L164-L168
|
func (v *EventNeedsBeginFramesChanged) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoHeadlessexperimental1(&r, v)
return r.Error()
}
|
https://github.com/VividCortex/godaemon/blob/3d9f6e0b234fe7d17448b345b2e14ac05814a758/daemon.go#L116-L231
|
func MakeDaemon(attrs *DaemonAttr) (io.Reader, io.Reader, error) {
stage, advanceStage, resetEnv := getStage()
// This is a handy wrapper to do the proper thing in case of fatal
// conditions. For the first stage you may want to recover, so it will
// return the error. Otherwise it will exit the process, cause you'll be
// half-way with some descriptors already changed. There's no chance to
// write to stdout or stderr in the later case; they'll be already closed.
fatal := func(err error) (io.Reader, io.Reader, error) {
if stage > 0 {
os.Exit(1)
}
resetEnv()
return nil, nil, err
}
fileCount := 3 + len(attrs.Files)
files := make([]*os.File, fileCount, fileCount+2)
if stage == 0 {
// Descriptors 0, 1 and 2 are fixed in the "os" package. If we close
// them, the process may choose to open something else there, with bad
// consequences if some write to os.Stdout or os.Stderr follows (even
// from Go's library itself, through the default log package). We thus
// reserve these descriptors to avoid that.
nullDev, err := os.OpenFile("/dev/null", 0, 0)
if err != nil {
return fatal(err)
}
files[0], files[1], files[2] = nullDev, nullDev, nullDev
fd := 3
for _, fPtr := range attrs.Files {
files[fd] = *fPtr
saveFileName(fd, (*fPtr).Name())
fd++
}
} else {
files[0], files[1], files[2] = os.Stdin, os.Stdout, os.Stderr
fd := 3
for _, fPtr := range attrs.Files {
*fPtr = os.NewFile(uintptr(fd), getFileName(fd))
syscall.CloseOnExec(fd)
files[fd] = *fPtr
fd++
}
}
if stage < 2 {
// getExecutablePath() is OS-specific.
procName, err := GetExecutablePath()
if err != nil {
return fatal(fmt.Errorf("can't determine full path to executable: %s", err))
}
// If getExecutablePath() returns "" but no error, determinating the
// executable path is not implemented on the host OS, so daemonization
// is not supported.
if len(procName) == 0 {
return fatal(fmt.Errorf("can't determine full path to executable"))
}
if stage == 1 && attrs.CaptureOutput {
files = files[:fileCount+2]
// stdout: write at fd:1, read at fd:fileCount
if files[fileCount], files[1], err = os.Pipe(); err != nil {
return fatal(err)
}
// stderr: write at fd:2, read at fd:fileCount+1
if files[fileCount+1], files[2], err = os.Pipe(); err != nil {
return fatal(err)
}
}
if err := advanceStage(); err != nil {
return fatal(err)
}
dir, _ := os.Getwd()
osAttrs := os.ProcAttr{Dir: dir, Env: os.Environ(), Files: files}
if stage == 0 {
sysattrs := syscall.SysProcAttr{Setsid: true}
osAttrs.Sys = &sysattrs
}
progName := attrs.ProgramName
if len(progName) == 0 {
progName = os.Args[0]
}
args := append([]string{progName}, os.Args[1:]...)
proc, err := os.StartProcess(procName, args, &osAttrs)
if err != nil {
return fatal(fmt.Errorf("can't create process %s: %s", procName, err))
}
proc.Release()
os.Exit(0)
}
os.Chdir("/")
syscall.Umask(0)
resetEnv()
for fd := 3; fd < fileCount; fd++ {
resetFileName(fd)
}
currStage = DaemonStage(stage)
var stdout, stderr *os.File
if attrs.CaptureOutput {
stdout = os.NewFile(uintptr(fileCount), "stdout")
stderr = os.NewFile(uintptr(fileCount+1), "stderr")
}
return stdout, stderr, nil
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/page.go#L235-L241
|
func (p *Page) Title() (string, error) {
title, err := p.session.GetTitle()
if err != nil {
return "", fmt.Errorf("failed to retrieve page title: %s", err)
}
return title, nil
}
|
https://github.com/urandom/handler/blob/61508044a5569d1609521d81e81f6737567fd104/lang/i18n.go#L44-L48
|
func URLPrefix(p string) Option {
return Option{func(o *options) {
o.urlPrefix = p
}}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/easyjson.go#L1504-L1508
|
func (v *DispatchKeyEventParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoInput9(&r, v)
return r.Error()
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/archive/transport.go#L95-L100
|
func (ref archiveReference) StringWithinTransport() string {
if ref.destinationRef == nil {
return ref.path
}
return fmt.Sprintf("%s:%s", ref.path, ref.destinationRef.String())
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L1841-L1845
|
func (v SetCookiesParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork13(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/types.go#L293-L295
|
func (t CookieSameSite) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/change_trust.go#L90-L101
|
func RemoveTrust(code, issuer string, args ...interface{}) (result ChangeTrustBuilder) {
mutators := []interface{}{
CreditAsset(code, issuer),
Limit("0"),
}
for _, mut := range args {
mutators = append(mutators, mut)
}
return ChangeTrust(mutators...)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/util_linux.go#L48-L62
|
func GetPathMode(path string) (os.FileMode, error) {
s, err := os.Open(path)
if err != nil {
return os.FileMode(0000), err
}
defer s.Close()
fi, err := s.Stat()
if err != nil {
return os.FileMode(0000), err
}
mode, _, _ := GetOwnerMode(fi)
return mode, nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/kernel.go#L11-L18
|
func LoadModule(module string) error {
if shared.PathExists(fmt.Sprintf("/sys/module/%s", module)) {
return nil
}
_, err := shared.RunCommand("modprobe", module)
return err
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/respond.go#L68-L79
|
func FormatResponseRaw(body, bodyURL, login, reply string) string {
format := `In response to [this](%s):
%s
`
// Quote the user's comment by prepending ">" to each line.
var quoted []string
for _, l := range strings.Split(body, "\n") {
quoted = append(quoted, ">"+l)
}
return FormatResponse(login, reply, fmt.Sprintf(format, bodyURL, strings.Join(quoted, "\n")))
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/mapping.go#L92-L105
|
func (m *Mapping) ColumnFields(exclude ...string) []*Field {
fields := []*Field{}
for _, field := range m.Fields {
if shared.StringInSlice(field.Name, exclude) {
continue
}
if field.Type.Code == TypeColumn {
fields = append(fields, field)
}
}
return fields
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/mvcc/key_index.go#L176-L218
|
func (ki *keyIndex) since(lg *zap.Logger, rev int64) []revision {
if ki.isEmpty() {
if lg != nil {
lg.Panic(
"'since' got an unexpected empty keyIndex",
zap.String("key", string(ki.key)),
)
} else {
plog.Panicf("store.keyindex: unexpected get on empty keyIndex %s", string(ki.key))
}
}
since := revision{rev, 0}
var gi int
// find the generations to start checking
for gi = len(ki.generations) - 1; gi > 0; gi-- {
g := ki.generations[gi]
if g.isEmpty() {
continue
}
if since.GreaterThan(g.created) {
break
}
}
var revs []revision
var last int64
for ; gi < len(ki.generations); gi++ {
for _, r := range ki.generations[gi].revs {
if since.GreaterThan(r) {
continue
}
if r.main == last {
// replace the revision with a new one that has higher sub value,
// because the original one should not be seen by external
revs[len(revs)-1] = r
continue
}
revs = append(revs, r)
last = r.main
}
}
return revs
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/fix.go#L56-L64
|
func migrateGrpcCompilers(c *config.Config, f *rule.File) {
for _, r := range f.Rules {
if r.Kind() != "go_grpc_library" || r.ShouldKeep() || r.Attr("compilers") != nil {
continue
}
r.SetKind("go_proto_library")
r.SetAttr("compilers", []string{grpcCompilerLabel})
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L133-L136
|
func (p CallFunctionOnParams) WithGeneratePreview(generatePreview bool) *CallFunctionOnParams {
p.GeneratePreview = generatePreview
return &p
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/devlxd.go#L347-L372
|
func extractUnderlyingFd(unixConnPtr *net.UnixConn) (int, error) {
conn := reflect.Indirect(reflect.ValueOf(unixConnPtr))
netFdPtr := conn.FieldByName("fd")
if !netFdPtr.IsValid() {
return -1, fmt.Errorf("Unable to extract fd from net.UnixConn")
}
netFd := reflect.Indirect(netFdPtr)
fd := netFd.FieldByName("sysfd")
if !fd.IsValid() {
// Try under the new name
pfdPtr := netFd.FieldByName("pfd")
if !pfdPtr.IsValid() {
return -1, fmt.Errorf("Unable to extract pfd from netFD")
}
pfd := reflect.Indirect(pfdPtr)
fd = pfd.FieldByName("Sysfd")
if !fd.IsValid() {
return -1, fmt.Errorf("Unable to extract Sysfd from poll.FD")
}
}
return int(fd.Int()), nil
}
|
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/logger.go#L192-L195
|
func (l *Logger) Panicf(format string, args ...interface{}) {
l.log(CRITICAL, &format, args...)
panic(fmt.Sprintf(format, args...))
}
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/cmpopts/struct_filter.go#L141-L182
|
func canonicalName(t reflect.Type, sel string) ([]string, error) {
var name string
sel = strings.TrimPrefix(sel, ".")
if sel == "" {
return nil, fmt.Errorf("name must not be empty")
}
if i := strings.IndexByte(sel, '.'); i < 0 {
name, sel = sel, ""
} else {
name, sel = sel[:i], sel[i:]
}
// Type must be a struct or pointer to struct.
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
return nil, fmt.Errorf("%v must be a struct", t)
}
// Find the canonical name for this current field name.
// If the field exists in an embedded struct, then it will be expanded.
if !isExported(name) {
// Disallow unexported fields:
// * To discourage people from actually touching unexported fields
// * FieldByName is buggy (https://golang.org/issue/4876)
return []string{name}, fmt.Errorf("name must be exported")
}
sf, ok := t.FieldByName(name)
if !ok {
return []string{name}, fmt.Errorf("does not exist")
}
var ss []string
for i := range sf.Index {
ss = append(ss, t.FieldByIndex(sf.Index[:i+1]).Name)
}
if sel == "" {
return ss, nil
}
ssPost, err := canonicalName(sf.Type, sel)
return append(ss, ssPost...), err
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L2274-L2295
|
func (c *Client) ListTeamInvitations(id int) ([]OrgInvitation, error) {
c.log("ListTeamInvites", id)
if c.fake {
return nil, nil
}
path := fmt.Sprintf("/teams/%d/invitations", id)
var ret []OrgInvitation
err := c.readPaginatedResults(
path,
acceptNone,
func() interface{} {
return &[]OrgInvitation{}
},
func(obj interface{}) {
ret = append(ret, *(obj.(*[]OrgInvitation))...)
},
)
if err != nil {
return nil, err
}
return ret, nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/transaction.go#L259-L262
|
func (m Network) MutateTransaction(o *TransactionBuilder) error {
o.NetworkID = m.ID()
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/easyjson.go#L1082-L1086
|
func (v HighlightNodeParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoOverlay11(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/serviceworker.go#L225-L227
|
func (p *StopWorkerParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandStopWorker, p, nil)
}
|
https://github.com/imdario/mergo/blob/45df20b7fcedb0ff48e461334a1f0aafcc3892e3/map.go#L139-L141
|
func MapWithOverwrite(dst, src interface{}, opts ...func(*Config)) error {
return _map(dst, src, append(opts, WithOverride)...)
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L757-L759
|
func Info(val ...interface{}) error {
return glg.out(INFO, blankFormat(len(val)), val...)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domstorage/easyjson.go#L915-L919
|
func (v *EventDomStorageItemAdded) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDomstorage8(&r, v)
return r.Error()
}
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/format/format.go#L169-L181
|
func IndentString(s string, indentation uint) string {
components := strings.Split(s, "\n")
result := ""
indent := strings.Repeat(Indent, int(indentation))
for i, component := range components {
result += indent + component
if i < len(components)-1 {
result += "\n"
}
}
return result
}
|
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/apis/cluster/cluster.go#L118-L147
|
func (c *Cluster) SetMachineProviderConfigs(providerConfigs []*MachineProviderConfig) {
for _, providerConfig := range providerConfigs {
name := providerConfig.ServerPool.Name
found := false
for _, machineSet := range c.MachineSets {
if machineSet.Name == name {
//logger.Debug("Matched machine set to provider config: %s", name)
bytes, err := json.Marshal(providerConfig)
if err != nil {
logger.Critical("unable to marshal machine provider config: %v")
continue
}
str := string(bytes)
machineSet.Spec.Template.Spec.ProviderConfig = str
found = true
}
}
// TODO
// @kris-nova
// Right now if we have a machine provider config and we can't match it
// we log a warning and move on. We might want to change this to create
// the machineSet moving forward..
if !found {
logger.Warning("Unable to match provider config to machine set: %s", name)
}
}
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/transaction_envelope.go#L115-L125
|
func (m *TransactionBuilder) MutateTransactionEnvelope(txe *TransactionEnvelopeBuilder) error {
if m.Err != nil {
return m.Err
}
txe.E.Tx = *m.TX
newChild := *m
txe.child = &newChild
m.TX = &txe.E.Tx
return nil
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/genny/grift/grift.go#L12-L29
|
func New(opts *Options) (*genny.Generator, error) {
g := genny.New()
if err := opts.Validate(); err != nil {
return g, err
}
data := map[string]interface{}{
"opts": opts,
}
t := gogen.TemplateTransformer(data, template.FuncMap{})
g.Transformer(t)
g.RunFn(func(r *genny.Runner) error {
return genFile(r, opts)
})
return g, nil
}
|
https://github.com/avast/retry-go/blob/88ef2130df9642aa2849152b2985af9ba3676ee9/options.go#L46-L50
|
func Delay(delay time.Duration) Option {
return func(c *Config) {
c.delay = delay
}
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/path_payment_result.go#L5-L26
|
func (pr *PathPaymentResult) SendAmount() Int64 {
s, ok := pr.GetSuccess()
if !ok {
return 0
}
if len(s.Offers) == 0 {
return s.Last.Amount
}
sa := s.Offers[0].AssetBought
var ret Int64
for _, o := range s.Offers {
if o.AssetBought.String() != sa.String() {
break
}
ret += o.AmountBought
}
return ret
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/transaction_envelope.go#L80-L83
|
func (b *TransactionEnvelopeBuilder) Base64() (string, error) {
bs, err := b.Bytes()
return base64.StdEncoding.EncodeToString(bs), err
}
|
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/zero/string.go#L71-L76
|
func (s String) MarshalText() ([]byte, error) {
if !s.Valid {
return []byte{}, nil
}
return []byte(s.String), nil
}
|
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/zero/int.go#L102-L108
|
func (i Int) MarshalText() ([]byte, error) {
n := i.Int64
if !i.Valid {
n = 0
}
return []byte(strconv.FormatInt(n, 10)), nil
}
|
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/concourse.go#L55-L59
|
func (s *ConcoursePipeline) SetImageDefaults(platform, imagetype, repo string) {
s.defaultPlatform = platform
s.defaultImageType = imagetype
s.defaultImageRepository = repo
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/route_mappings.go#L234-L241
|
func (a *App) RouteHelpers() map[string]RouteHelperFunc {
rh := map[string]RouteHelperFunc{}
for _, route := range a.Routes() {
cRoute := route
rh[cRoute.PathName] = cRoute.BuildPathHelper()
}
return rh
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/util.go#L31-L37
|
func randomTimeout(minVal time.Duration) <-chan time.Time {
if minVal == 0 {
return nil
}
extra := (time.Duration(rand.Int63()) % minVal)
return time.After(minVal + extra)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/deploy/assets/assets.go#L926-L946
|
func EtcdHeadlessService(opts *AssetOpts) *v1.Service {
return &v1.Service{
TypeMeta: metav1.TypeMeta{
Kind: "Service",
APIVersion: "v1",
},
ObjectMeta: objectMeta(etcdHeadlessServiceName, labels(etcdName), nil, opts.Namespace),
Spec: v1.ServiceSpec{
Selector: map[string]string{
"app": etcdName,
},
ClusterIP: "None",
Ports: []v1.ServicePort{
{
Name: "peer-port",
Port: 2380,
},
},
},
}
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/platform_strings.go#L120-L135
|
func (ps *PlatformStrings) Map(f func(s string) (string, error)) (PlatformStrings, []error) {
var errors []error
mapSlice := func(ss []string) ([]string, error) {
rs := make([]string, 0, len(ss))
for _, s := range ss {
if r, err := f(s); err != nil {
errors = append(errors, err)
} else if r != "" {
rs = append(rs, r)
}
}
return rs, nil
}
result, _ := ps.MapSlice(mapSlice)
return result, errors
}
|
https://github.com/codegangsta/martini-contrib/blob/8ce6181c2609699e4c7cd30994b76a850a9cdadc/encoder/encoder.go#L32-L58
|
func (_ JsonEncoder) Encode(v ...interface{}) ([]byte, error) {
var data interface{} = v
var result interface{}
if v == nil {
// So that empty results produces `[]` and not `null`
data = []interface{}{}
} else if len(v) == 1 {
data = v[0]
}
t := reflect.TypeOf(data)
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() == reflect.Struct {
result = copyStruct(reflect.ValueOf(data), t).Interface()
} else {
result = data
}
b, err := json.Marshal(result)
return b, err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tethering/easyjson.go#L223-L227
|
func (v BindParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoTethering2(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/client.go#L276-L308
|
func getUserMachineAddrAndOpts(cfg *config.Config) (string, []Option, error) {
// 1) PACHD_ADDRESS environment variable (shell-local) overrides global config
if envAddr, ok := os.LookupEnv("PACHD_ADDRESS"); ok {
if !strings.Contains(envAddr, ":") {
envAddr = fmt.Sprintf("%s:%s", envAddr, DefaultPachdNodePort)
}
options, err := getCertOptionsFromEnv()
if err != nil {
return "", nil, err
}
return envAddr, options, nil
}
// 2) Get target address from global config if possible
if cfg != nil && cfg.V1 != nil && cfg.V1.PachdAddress != "" {
// Also get cert info from config (if set)
if cfg.V1.ServerCAs != "" {
pemBytes, err := base64.StdEncoding.DecodeString(cfg.V1.ServerCAs)
if err != nil {
return "", nil, fmt.Errorf("could not decode server CA certs in config: %v", err)
}
return cfg.V1.PachdAddress, []Option{WithAdditionalRootCAs(pemBytes)}, nil
}
return cfg.V1.PachdAddress, nil, nil
}
// 3) Use default address (broadcast) if nothing else works
options, err := getCertOptionsFromEnv()
if err != nil {
return "", nil, err
}
return "", options, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/easyjson.go#L350-L354
|
func (v StartTrackingHeapObjectsParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoHeapprofiler4(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/api15gen/api_analyzer.go#L499-L505
|
func refType(resName string) string {
res := resourceType(resName)
if res != "map[string]interface{}" {
res = "*" + res
}
return res
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/message.go#L44-L58
|
func (m *Message) AddBody(r render.Renderer, data render.Data) error {
buf := bytes.NewBuffer([]byte{})
err := r.Render(buf, m.merge(data))
if err != nil {
return err
}
m.Bodies = append(m.Bodies, Body{
Content: buf.String(),
ContentType: r.ContentType(),
})
return nil
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dimg/ftgc.go#L104-L115
|
func DrawImage(src image.Image, dest draw.Image, tr draw2d.Matrix, op draw.Op, filter ImageFilter) {
var transformer draw.Transformer
switch filter {
case LinearFilter:
transformer = draw.NearestNeighbor
case BilinearFilter:
transformer = draw.BiLinear
case BicubicFilter:
transformer = draw.CatmullRom
}
transformer.Transform(dest, f64.Aff3{tr[0], tr[1], tr[4], tr[2], tr[3], tr[5]}, src, src.Bounds(), op, nil)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cast/cast.go#L41-L44
|
func (p EnableParams) WithPresentationURL(presentationURL string) *EnableParams {
p.PresentationURL = presentationURL
return &p
}
|
https://github.com/knq/sdhook/blob/41b9ccbff0b5fa5a56fbdccf2eb8653e7afe8d4b/opts.go#L27-L32
|
func Levels(levels ...logrus.Level) Option {
return func(sh *StackdriverHook) error {
sh.levels = levels
return nil
}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/dlock/dlock.go#L32-L37
|
func NewDLock(client *etcd.Client, prefix string) DLock {
return &etcdImpl{
client: client,
prefix: prefix,
}
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/connection.go#L539-L563
|
func (c *Connection) connectionError(site string, err error) error {
var closeLogFields LogFields
if err == io.EOF {
closeLogFields = LogFields{{"reason", "network connection EOF"}}
} else {
closeLogFields = LogFields{
{"reason", "connection error"},
ErrField(err),
}
}
c.stopHealthCheck()
err = c.logConnectionError(site, err)
c.close(closeLogFields...)
// On any connection error, notify the exchanges of this error.
if c.stoppedExchanges.CAS(false, true) {
c.outbound.stopExchanges(err)
c.inbound.stopExchanges(err)
}
// checkExchanges will close the connection due to stoppedExchanges.
c.checkExchanges()
return err
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/exec/exec.go#L455-L472
|
func (c *Cmd) WaitIO(state *os.ProcessState, err error) (retErr error) {
if c.waitDone != nil {
close(c.waitDone)
}
c.ProcessState = state
if err != nil {
return err
} else if !state.Success() {
return &ExitError{ProcessState: state}
}
for range c.goroutine {
if err := <-c.errch; err != nil && retErr == nil {
retErr = err
}
}
c.closeDescriptors(c.closeAfterWait)
return retErr
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/relay.go#L476-L492
|
func (r *Relayer) addRelayItem(isOriginator bool, id, remapID uint32, destination *Relayer, ttl time.Duration, span Span, call RelayCall) relayItem {
item := relayItem{
call: call,
remapID: remapID,
destination: destination,
span: span,
}
items := r.inbound
if isOriginator {
items = r.outbound
}
item.timeout = r.timeouts.Get()
items.Add(id, item)
item.timeout.Start(ttl, items, id, isOriginator)
return item
}
|
https://github.com/libp2p/go-libp2p-crypto/blob/9d2fed53443f745e6dc4d02bdcc94d9742a0ca84/ed25519.go#L128-L155
|
func UnmarshalEd25519PrivateKey(data []byte) (PrivKey, error) {
switch len(data) {
case ed25519.PrivateKeySize + ed25519.PublicKeySize:
// Remove the redundant public key. See issue #36.
redundantPk := data[ed25519.PrivateKeySize:]
pk := data[ed25519.PrivateKeySize-ed25519.PublicKeySize : ed25519.PrivateKeySize]
if !bytes.Equal(pk, redundantPk) {
return nil, errors.New("expected redundant ed25519 public key to be redundant")
}
// No point in storing the extra data.
newKey := make([]byte, ed25519.PrivateKeySize)
copy(newKey, data[:ed25519.PrivateKeySize])
data = newKey
case ed25519.PrivateKeySize:
default:
return nil, fmt.Errorf(
"expected ed25519 data size to be %d or %d, got %d",
ed25519.PrivateKeySize,
ed25519.PrivateKeySize+ed25519.PublicKeySize,
len(data),
)
}
return &Ed25519PrivateKey{
k: ed25519.PrivateKey(data),
}, nil
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/callbacks.go#L362-L435
|
func RelationshipValidator(model coal.Model, catalog *coal.Catalog, excludedFields ...string) *Callback {
// prepare lists
dependentResources := make(map[coal.Model]string)
references := make(map[string]coal.Model)
// iterate through all fields
for _, field := range coal.Init(model).Meta().Relationships {
// exclude field if requested
if Contains(excludedFields, field.Name) {
continue
}
// handle has-one and has-many relationships
if field.HasOne || field.HasMany {
// get related model
relatedModel := catalog.Find(field.RelType)
if relatedModel == nil {
panic(fmt.Sprintf(`fire: missing model in catalog: "%s"`, field.RelType))
}
// get related bson field
bsonField := ""
for _, relatedField := range relatedModel.Meta().Relationships {
if relatedField.RelName == field.RelInverse {
bsonField = relatedField.Name
}
}
if bsonField == "" {
panic(fmt.Sprintf(`fire: missing field for inverse relationship: "%s"`, field.RelInverse))
}
// add relationship
dependentResources[relatedModel] = bsonField
}
// handle to-one and to-many relationships
if field.ToOne || field.ToMany {
// get related model
relatedModel := catalog.Find(field.RelType)
if relatedModel == nil {
panic(fmt.Sprintf(`fire: missing model in catalog: "%s"`, field.RelType))
}
// add relationship
references[field.Name] = relatedModel
}
}
// create callbacks
cb1 := DependentResourcesValidator(dependentResources)
cb2 := VerifyReferencesValidator(references)
return C("RelationshipValidator", func(ctx *Context) bool {
return cb1.Matcher(ctx) || cb2.Matcher(ctx)
}, func(ctx *Context) error {
// run dependent resources validator
if cb1.Matcher(ctx) {
err := cb1.Handler(ctx)
if err != nil {
return err
}
}
// run dependent resources validator
if cb2.Matcher(ctx) {
err := cb2.Handler(ctx)
if err != nil {
return err
}
}
return nil
})
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L995-L1000
|
func ErrorFunc(f func() string) error {
if isModeEnable(ERR) {
return glg.out(ERR, "%s", f())
}
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/api_cluster.go#L68-L97
|
func clusterGet(d *Daemon, r *http.Request) Response {
name := ""
err := d.cluster.Transaction(func(tx *db.ClusterTx) error {
var err error
name, err = tx.NodeName()
return err
})
if err != nil {
return SmartError(err)
}
// If the name is set to the hard-coded default node name, then
// clustering is not enabled.
if name == "none" {
name = ""
}
memberConfig, err := clusterGetMemberConfig(d.cluster)
if err != nil {
return SmartError(err)
}
cluster := api.Cluster{
ServerName: name,
Enabled: name != "",
MemberConfig: memberConfig,
}
return SyncResponseETag(true, cluster, cluster)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L969-L971
|
func (p *SetAdBlockingEnabledParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandSetAdBlockingEnabled, p, nil)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L3333-L3337
|
func (v *GetPossibleBreakpointsReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger35(&r, v)
return r.Error()
}
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/mock_client.go#L55-L57
|
func (p *mockClient) RemoveAllServers(server *types.MockServer) []*types.MockServer {
return p.RemoveAllServersResponse
}
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/examples/gin/provider/user_service.go#L50-L65
|
func UserLogin(c *gin.Context) {
c.Header("X-Api-Correlation-Id", "1234")
var json Login
if c.BindJSON(&json) == nil {
user, err := userRepository.ByUsername(json.User)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"status": "file not found"})
} else if user.Username != json.User || user.Password != json.Password {
c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
} else {
c.Header("X-Auth-Token", getAuthToken())
c.JSON(http.StatusOK, types.LoginResponse{User: user})
}
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/log/easyjson.go#L257-L261
|
func (v StartViolationsReportParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoLog2(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/daemon.go#L1226-L1252
|
func (d *Daemon) setupMAASController(server string, key string, machine string) error {
var err error
d.maas = nil
// Default the machine name to the hostname
if machine == "" {
machine, err = os.Hostname()
if err != nil {
return err
}
}
// We need both URL and key, otherwise disable MAAS
if server == "" || key == "" {
return nil
}
// Get a new controller struct
controller, err := maas.NewController(server, key, machine)
if err != nil {
d.maas = nil
return err
}
d.maas = controller
return nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L199-L218
|
func iterDir(tx *bolt.Tx, path string, f func(k, v []byte, c *bolt.Cursor) error) error {
node, err := get(tx, path)
if err != nil {
return err
}
if node.DirNode == nil {
return errorf(PathConflict, "the file at \"%s\" is not a directory",
path)
}
c := NewChildCursor(tx, path)
for k, v := c.K(), c.V(); k != nil; k, v = c.Next() {
if err := f(k, v, c.c); err != nil {
if err == errutil.ErrBreak {
return nil
}
return err
}
}
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/server.go#L2408-L2428
|
func (s *EtcdServer) goAttach(f func()) {
s.wgMu.RLock() // this blocks with ongoing close(s.stopping)
defer s.wgMu.RUnlock()
select {
case <-s.stopping:
if lg := s.getLogger(); lg != nil {
lg.Warn("server has stopped; skipping goAttach")
} else {
plog.Warning("server has stopped (skipping goAttach)")
}
return
default:
}
// now safe to add since waitgroup wait has not started yet
s.wg.Add(1)
go func() {
defer s.wg.Done()
f()
}()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/har/easyjson.go#L1674-L1678
|
func (v *HAR) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoHar9(&r, v)
return r.Error()
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/outbound.go#L272-L308
|
func (c *Connection) handleError(frame *Frame) bool {
errMsg := errorMessage{
id: frame.Header.ID,
}
rbuf := typed.NewReadBuffer(frame.SizedPayload())
if err := errMsg.read(rbuf); err != nil {
c.log.WithFields(
LogField{"remotePeer", c.remotePeerInfo},
ErrField(err),
).Warn("Unable to read error frame.")
c.connectionError("parsing error frame", err)
return true
}
if errMsg.errCode == ErrCodeProtocol {
c.log.WithFields(
LogField{"remotePeer", c.remotePeerInfo},
LogField{"error", errMsg.message},
).Warn("Peer reported protocol error.")
c.connectionError("received protocol error", errMsg.AsSystemError())
return true
}
if err := c.outbound.forwardPeerFrame(frame); err != nil {
c.log.WithFields(
LogField{"frameHeader", frame.Header.String()},
LogField{"id", errMsg.id},
LogField{"errorMessage", errMsg.message},
LogField{"errorCode", errMsg.errCode},
ErrField(err),
).Info("Failed to forward error frame.")
return true
}
// If the frame was forwarded, then the other side is responsible for releasing the frame.
return false
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L5998-L6002
|
func (v *EventFrameRequestedNavigation) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage63(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L4257-L4261
|
func (v GetContentQuadsReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom48(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/ppsutil/util.go#L67-L69
|
func GetRequestsResourceListFromPipeline(pipelineInfo *pps.PipelineInfo) (*v1.ResourceList, error) {
return getResourceListFromSpec(pipelineInfo.ResourceRequests, pipelineInfo.CacheSize)
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/repo/modules.go#L174-L203
|
func copyGoModToTemp(filename string) (tempDir string, err error) {
goModOrig, err := os.Open(filename)
if err != nil {
return "", err
}
defer goModOrig.Close()
tempDir, err = ioutil.TempDir("", "gazelle-temp-gomod")
if err != nil {
return "", err
}
goModCopy, err := os.Create(filepath.Join(tempDir, "go.mod"))
if err != nil {
os.Remove(tempDir)
return "", err
}
defer func() {
if cerr := goModCopy.Close(); err == nil && cerr != nil {
err = cerr
}
}()
_, err = io.Copy(goModCopy, goModOrig)
if err != nil {
os.RemoveAll(tempDir)
return "", err
}
return tempDir, err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domstorage/domstorage.go#L150-L156
|
func SetDOMStorageItem(storageID *StorageID, key string, value string) *SetDOMStorageItemParams {
return &SetDOMStorageItemParams{
StorageID: storageID,
Key: key,
Value: value,
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/rbac/server.go#L216-L228
|
func (r *Server) IsAdmin(username string) bool {
r.permissionsLock.Lock()
defer r.permissionsLock.Unlock()
// Check whether the permissions are cached
_, cached := r.permissions[username]
if !cached {
r.syncPermissions(username)
}
return shared.StringInSlice("admin", r.permissions[username][""])
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/errorutil/aggregate.go#L60-L66
|
func (agg aggregate) Error() string {
if len(agg) == 0 {
// This should never happen, really.
return ""
}
return fmt.Sprintf("[%s]", strings.Join(agg.Strings(), ", "))
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L2480-L2503
|
func (c *Client) IsMergeable(org, repo string, number int, SHA string) (bool, error) {
backoff := time.Second * 3
maxTries := 3
for try := 0; try < maxTries; try++ {
pr, err := c.GetPullRequest(org, repo, number)
if err != nil {
return false, err
}
if pr.Head.SHA != SHA {
return false, fmt.Errorf("pull request head changed while checking mergeability (%s -> %s)", SHA, pr.Head.SHA)
}
if pr.Merged {
return false, errors.New("pull request was merged while checking mergeability")
}
if pr.Mergable != nil {
return *pr.Mergable, nil
}
if try+1 < maxTries {
c.time.Sleep(backoff)
backoff *= 2
}
}
return false, fmt.Errorf("reached maximum number of retries (%d) checking mergeability", maxTries)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_projects.go#L72-L84
|
func (r *ProtocolLXD) CreateProject(project api.ProjectsPost) error {
if !r.HasExtension("projects") {
return fmt.Errorf("The server is missing the required \"projects\" API extension")
}
// Send the request
_, _, err := r.query("POST", "/projects", project, "")
if err != nil {
return err
}
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_post.go#L395-L499
|
func containerPostClusteringMigrateWithCeph(d *Daemon, c container, project, oldName, newName, newNode string) Response {
run := func(*operation) error {
// If source node is online (i.e. we're serving the request on
// it, and c != nil), let's unmap the RBD volume locally
if c != nil {
logger.Debugf(`Renaming RBD storage volume for source container "%s" from "%s" to "%s"`, c.Name(), c.Name(), newName)
poolName, err := c.StoragePool()
if err != nil {
return errors.Wrap(err, "Failed to get source container's storage pool name")
}
_, pool, err := d.cluster.StoragePoolGet(poolName)
if err != nil {
return errors.Wrap(err, "Failed to get source container's storage pool")
}
if pool.Driver != "ceph" {
return fmt.Errorf("Source container's storage pool is not of type ceph")
}
si, err := storagePoolVolumeContainerLoadInit(d.State(), c.Project(), c.Name())
if err != nil {
return errors.Wrap(err, "Failed to initialize source container's storage pool")
}
s, ok := si.(*storageCeph)
if !ok {
return fmt.Errorf("Unexpected source container storage backend")
}
err = cephRBDVolumeUnmap(s.ClusterName, s.OSDPoolName, c.Name(),
storagePoolVolumeTypeNameContainer, s.UserName, true)
if err != nil {
return errors.Wrap(err, "Failed to unmap source container's RBD volume")
}
}
// Re-link the database entries against the new node name.
var poolName string
err := d.cluster.Transaction(func(tx *db.ClusterTx) error {
err := tx.ContainerNodeMove(oldName, newName, newNode)
if err != nil {
return err
}
poolName, err = tx.ContainerPool(project, newName)
if err != nil {
return err
}
return nil
})
if err != nil {
return errors.Wrap(err, "Failed to relink container database data")
}
// Rename the RBD volume if necessary.
if newName != oldName {
s := storageCeph{}
_, s.pool, err = d.cluster.StoragePoolGet(poolName)
if err != nil {
return errors.Wrap(err, "Failed to get storage pool")
}
if err != nil {
return errors.Wrap(err, "Failed to get storage pool")
}
err = s.StoragePoolInit()
if err != nil {
return errors.Wrap(err, "Failed to initialize ceph storage pool")
}
err = cephRBDVolumeRename(s.ClusterName, s.OSDPoolName,
storagePoolVolumeTypeNameContainer, oldName, newName, s.UserName)
if err != nil {
return errors.Wrap(err, "Failed to rename ceph RBD volume")
}
}
// Create the container mount point on the target node
cert := d.endpoints.NetworkCert()
client, err := cluster.ConnectIfContainerIsRemote(d.cluster, project, newName, cert)
if err != nil {
return errors.Wrap(err, "Failed to connect to target node")
}
if client == nil {
err := containerPostCreateContainerMountPoint(d, project, newName)
if err != nil {
return errors.Wrap(err, "Failed to create mount point on target node")
}
} else {
path := fmt.Sprintf("/internal/cluster/container-moved/%s", newName)
resp, _, err := client.RawQuery("POST", path, nil, "")
if err != nil {
return errors.Wrap(err, "Failed to create mount point on target node")
}
if resp.StatusCode != 200 {
return fmt.Errorf("Failed to create mount point on target node: %s", resp.Error)
}
}
return nil
}
resources := map[string][]string{}
resources["containers"] = []string{oldName}
op, err := operationCreate(d.cluster, project, operationClassTask, db.OperationContainerMigrate, resources, nil, run, nil, nil)
if err != nil {
return InternalError(err)
}
return OperationResponse(op)
}
|
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/snowballword/snowballword.go#L292-L298
|
func (w *SnowballWord) RemoveFirstSuffixIn(startPos int, suffixes ...string) (suffix string, suffixRunes []rune) {
suffix, suffixRunes = w.FirstSuffixIn(startPos, len(w.RS), suffixes...)
if suffix != "" {
w.RemoveLastNRunes(len(suffixRunes))
}
return
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/raw/handler.go#L71-L84
|
func WriteResponse(response *tchannel.InboundCallResponse, resp *Res) error {
if resp.SystemErr != nil {
return response.SendSystemError(resp.SystemErr)
}
if resp.IsErr {
if err := response.SetApplicationError(); err != nil {
return err
}
}
if err := tchannel.NewArgWriter(response.Arg2Writer()).Write(resp.Arg2); err != nil {
return err
}
return tchannel.NewArgWriter(response.Arg3Writer()).Write(resp.Arg3)
}
|
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/render.go#L142-L144
|
func (render *Render) Asset(name string) ([]byte, error) {
return render.AssetFileSystem.Asset(name)
}
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L331-L333
|
func (l *Logger) Info(args ...interface{}) {
l.Output(2, LevelInfo, fmt.Sprint(args...))
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm16/codegen_client.go#L1424-L1426
|
func (r *NetworkInterfaceAttachment) Locator(api *API) *NetworkInterfaceAttachmentLocator {
return api.NetworkInterfaceAttachmentLocator(r.Href)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L6338-L6342
|
func (v *EventDownloadWillBegin) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage67(&r, v)
return r.Error()
}
|
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/storage/storagemock/storage.go#L38-L56
|
func (_m *Storage) Delete(_a0 context.Context, _a1 string, _a2 string, _a3 string, _a4 *time.Time, _a5 *time.Time) (int64, error) {
ret := _m.Called(_a0, _a1, _a2, _a3, _a4, _a5)
var r0 int64
if rf, ok := ret.Get(0).(func(context.Context, string, string, string, *time.Time, *time.Time) int64); ok {
r0 = rf(_a0, _a1, _a2, _a3, _a4, _a5)
} else {
r0 = ret.Get(0).(int64)
}
var r1 error
if rf, ok := ret.Get(1).(func(context.Context, string, string, string, *time.Time, *time.Time) error); ok {
r1 = rf(_a0, _a1, _a2, _a3, _a4, _a5)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/profiles_utils.go#L225-L253
|
func getProfileContainersInfo(cluster *db.Cluster, project, profile string) ([]db.ContainerArgs, error) {
// Query the db for information about containers associated with the
// given profile.
names, err := cluster.ProfileContainersGet(project, profile)
if err != nil {
return nil, errors.Wrapf(err, "failed to query containers with profile '%s'", profile)
}
containers := []db.ContainerArgs{}
err = cluster.Transaction(func(tx *db.ClusterTx) error {
for ctProject, ctNames := range names {
for _, ctName := range ctNames {
container, err := tx.ContainerGet(ctProject, ctName)
if err != nil {
return err
}
containers = append(containers, db.ContainerToArgs(container))
}
}
return nil
})
if err != nil {
return nil, errors.Wrapf(err, "Failed to fetch containers")
}
return containers, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/performance/easyjson.go#L463-L467
|
func (v *EventMetrics) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoPerformance4(&r, v)
return r.Error()
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/internal/mail/message.go#L271-L277
|
func SetHeader(h map[string][]string) FileSetting {
return func(f *file) {
for k, v := range h {
f.Header[k] = v
}
}
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/internal/mail/message.go#L182-L184
|
func (m *Message) FormatDate(date time.Time) string {
return date.Format(time.RFC1123Z)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/srv/srv.go#L35-L91
|
func GetCluster(serviceScheme, service, name, dns string, apurls types.URLs) ([]string, error) {
tempName := int(0)
tcp2ap := make(map[string]url.URL)
// First, resolve the apurls
for _, url := range apurls {
tcpAddr, err := resolveTCPAddr("tcp", url.Host)
if err != nil {
return nil, err
}
tcp2ap[tcpAddr.String()] = url
}
stringParts := []string{}
updateNodeMap := func(service, scheme string) error {
_, addrs, err := lookupSRV(service, "tcp", dns)
if err != nil {
return err
}
for _, srv := range addrs {
port := fmt.Sprintf("%d", srv.Port)
host := net.JoinHostPort(srv.Target, port)
tcpAddr, terr := resolveTCPAddr("tcp", host)
if terr != nil {
err = terr
continue
}
n := ""
url, ok := tcp2ap[tcpAddr.String()]
if ok {
n = name
}
if n == "" {
n = fmt.Sprintf("%d", tempName)
tempName++
}
// SRV records have a trailing dot but URL shouldn't.
shortHost := strings.TrimSuffix(srv.Target, ".")
urlHost := net.JoinHostPort(shortHost, port)
if ok && url.Scheme != scheme {
err = fmt.Errorf("bootstrap at %s from DNS for %s has scheme mismatch with expected peer %s", scheme+"://"+urlHost, service, url.String())
} else {
stringParts = append(stringParts, fmt.Sprintf("%s=%s://%s", n, scheme, urlHost))
}
}
if len(stringParts) == 0 {
return err
}
return nil
}
err := updateNodeMap(service, serviceScheme)
if err != nil {
return nil, fmt.Errorf("error querying DNS SRV records for _%s %s", service, err)
}
return stringParts, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv2/command/set_command.go#L51-L73
|
func setCommandFunc(c *cli.Context, ki client.KeysAPI) {
if len(c.Args()) == 0 {
handleError(c, ExitBadArgs, errors.New("key required"))
}
key := c.Args()[0]
value, err := argOrStdin(c.Args(), os.Stdin, 1)
if err != nil {
handleError(c, ExitBadArgs, errors.New("value required"))
}
ttl := c.Int("ttl")
prevValue := c.String("swap-with-value")
prevIndex := c.Int("swap-with-index")
ctx, cancel := contextWithTotalTimeout(c)
resp, err := ki.Set(ctx, key, value, &client.SetOptions{TTL: time.Duration(ttl) * time.Second, PrevIndex: uint64(prevIndex), PrevValue: prevValue})
cancel()
if err != nil {
handleError(c, ExitServerError, err)
}
printResponseKey(resp, c.GlobalString("output"))
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nodelist.go#L42-L61
|
func (l *NodeList) Remove(key []byte) *skiplist.Node {
var prev *skiplist.Node
node := l.head
for node != nil {
nodeKey := (*Item)(node.Item()).Bytes()
if bytes.Equal(nodeKey, key) {
if prev == nil {
l.head = node.GetLink()
return node
}
prev.SetLink(node.GetLink())
return node
}
prev = node
node = node.GetLink()
}
return nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/client/client.go#L320-L333
|
func (c *Client) updateLocalResource(i common.Item, state string, data *common.UserData) error {
res, err := common.ItemToResource(i)
if err != nil {
return err
}
res.State = state
if res.UserData == nil {
res.UserData = data
} else {
res.UserData.Update(data)
}
return c.storage.Update(res)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.