_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/access_log_apache.go#L231-L236
|
func (u *accessLogUtil) BytesWritten() int64 {
if u.R.Env["BYTES_WRITTEN"] != nil {
return u.R.Env["BYTES_WRITTEN"].(int64)
}
return 0
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/paths.go#L150-L152
|
func fwrulePath(dcid, srvid, nicid, fwruleid string) string {
return fwruleColPath(dcid, srvid, nicid) + slash(fwruleid)
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ca/cac/codegen_client.go#L702-L704
|
func (api *API) CloudBillMetricLocator(href string) *CloudBillMetricLocator {
return &CloudBillMetricLocator{Href(href), api}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L653-L657
|
func (v *SetInspectedNodeParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom6(&r, v)
return r.Error()
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/goimage.go#L20-L39
|
func FromImage(img image.Image) *IplImage {
b := img.Bounds()
model := color.RGBAModel
dst := CreateImage(
b.Max.X-b.Min.X,
b.Max.Y-b.Min.Y,
IPL_DEPTH_8U, 4)
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
px := img.At(x, y)
c := model.Convert(px).(color.RGBA)
value := NewScalar(float64(c.B), float64(c.G), float64(c.R), float64(c.A))
dst.Set2D(x-b.Min.X, y-b.Min.Y, value)
}
}
return dst
}
|
https://github.com/ccding/go-config-reader/blob/8b6c2b50197f20da3b1c5944c274c173634dc056/config/config.go#L165-L175
|
func checkSection(line string) (string, bool) {
line = strings.TrimSpace(line)
lineLen := len(line)
if lineLen < 2 {
return "", false
}
if line[0] == '[' && line[lineLen-1] == ']' {
return line[1 : lineLen-1], true
}
return "", false
}
|
https://github.com/soygul/gcm/blob/08c1e33b494fc198134b9f1000c99b2ff8d1883b/ccs/ccs.go#L30-L50
|
func Connect(host, senderID, apiKey string, debug bool) (*Conn, error) {
if !strings.Contains(senderID, gcmDomain) {
senderID += "@" + gcmDomain
}
c, err := xmpp.NewClient(host, senderID, apiKey, debug)
if err != nil {
return nil, err
}
if debug {
log.Printf("New CCS connection established with XMPP parameters: %+v\n", c)
}
return &Conn{
Host: host,
SenderID: senderID,
debug: debug,
xmppConn: c,
}, nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pps/pretty/pretty.go#L196-L236
|
func PrintDetailedPipelineInfo(pipelineInfo *PrintablePipelineInfo) error {
template, err := template.New("PipelineInfo").Funcs(funcMap).Parse(
`Name: {{.Pipeline.Name}}{{if .Description}}
Description: {{.Description}}{{end}}{{if .FullTimestamps }}
Created: {{.CreatedAt}}{{ else }}
Created: {{prettyAgo .CreatedAt}} {{end}}
State: {{pipelineState .State}}
Stopped: {{ .Stopped }}
Reason: {{.Reason}}
Parallelism Spec: {{.ParallelismSpec}}
{{ if .ResourceRequests }}ResourceRequests:
CPU: {{ .ResourceRequests.Cpu }}
Memory: {{ .ResourceRequests.Memory }} {{end}}
{{ if .ResourceLimits }}ResourceLimits:
CPU: {{ .ResourceLimits.Cpu }}
Memory: {{ .ResourceLimits.Memory }}
{{ if .ResourceLimits.Gpu }}GPU:
Type: {{ .ResourceLimits.Gpu.Type }}
Number: {{ .ResourceLimits.Gpu.Number }} {{end}} {{end}}
Datum Timeout: {{.DatumTimeout}}
Job Timeout: {{.JobTimeout}}
Input:
{{pipelineInput .PipelineInfo}}
{{ if .GithookURL }}Githook URL: {{.GithookURL}} {{end}}
Output Branch: {{.OutputBranch}}
Transform:
{{prettyTransform .Transform}}
{{ if .Egress }}Egress: {{.Egress.URL}} {{end}}
{{if .RecentError}} Recent Error: {{.RecentError}} {{end}}
Job Counts:
{{jobCounts .JobCounts}}
`)
if err != nil {
return err
}
err = template.Execute(os.Stdout, pipelineInfo)
if err != nil {
return err
}
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxc/utils/cancel.go#L14-L71
|
func CancelableWait(rawOp interface{}, progress *ProgressRenderer) error {
var op lxd.Operation
var rop lxd.RemoteOperation
// Check what type of operation we're dealing with
switch v := rawOp.(type) {
case lxd.Operation:
op = v
case lxd.RemoteOperation:
rop = v
default:
return fmt.Errorf("Invalid operation type for CancelableWait")
}
// Signal handling
chSignal := make(chan os.Signal)
signal.Notify(chSignal, os.Interrupt)
// Operation handling
chOperation := make(chan error)
go func() {
if op != nil {
chOperation <- op.Wait()
} else {
chOperation <- rop.Wait()
}
close(chOperation)
}()
count := 0
for {
var err error
select {
case err := <-chOperation:
return err
case <-chSignal:
if op != nil {
err = op.Cancel()
} else {
err = rop.CancelTarget()
}
if err == nil {
return fmt.Errorf(i18n.G("Remote operation canceled by user"))
}
count++
if count == 3 {
return fmt.Errorf(i18n.G("User signaled us three times, exiting. The remote operation will keep running"))
}
if progress != nil {
progress.Warn(fmt.Sprintf(i18n.G("%v (interrupt two more times to force)"), err), time.Second*5)
}
}
}
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/thrift/headers.go#L84-L90
|
func ReadHeaders(r io.Reader) (map[string]string, error) {
reader := typed.NewReader(r)
m, err := readHeaders(reader)
reader.Release()
return m, err
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/schema.go#L88-L90
|
func (s *Schema) Add(update Update) {
s.updates = append(s.updates, update)
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/merge.go#L48-L59
|
func (db *DB) GetMergeOperator(key []byte,
f MergeFunc, dur time.Duration) *MergeOperator {
op := &MergeOperator{
f: f,
db: db,
key: key,
closer: y.NewCloser(1),
}
go op.runCompactions(dur)
return op
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/auth/options.go#L63-L94
|
func (opts *jwtOptions) Parse(optMap map[string]string) error {
var err error
if ttl := optMap[optTTL]; ttl != "" {
opts.TTL, err = time.ParseDuration(ttl)
if err != nil {
return err
}
}
if file := optMap[optPublicKey]; file != "" {
opts.PublicKey, err = ioutil.ReadFile(file)
if err != nil {
return err
}
}
if file := optMap[optPrivateKey]; file != "" {
opts.PrivateKey, err = ioutil.ReadFile(file)
if err != nil {
return err
}
}
// signing method is a required field
method := optMap[optSignMethod]
opts.SignMethod = jwt.GetSigningMethod(method)
if opts.SignMethod == nil {
return ErrInvalidAuthMethod
}
return nil
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/iaas.go#L216-L251
|
func templateUpdate(w http.ResponseWriter, r *http.Request, token auth.Token) (err error) {
var paramTemplate iaas.Template
err = ParseInput(r, ¶mTemplate)
if err != nil {
return err
}
templateName := r.URL.Query().Get(":template_name")
dbTpl, err := iaas.FindTemplate(templateName)
if err != nil {
if err == mgo.ErrNotFound {
return &errors.HTTP{Code: http.StatusNotFound, Message: "template not found"}
}
return err
}
iaasValue := InputValue(r, "IaaSName")
if iaasValue != "" {
dbTpl.IaaSName = iaasValue
}
iaasCtx := permission.Context(permTypes.CtxIaaS, dbTpl.IaaSName)
allowed := permission.Check(token, permission.PermMachineTemplateUpdate, iaasCtx)
if !allowed {
return permission.ErrUnauthorized
}
evt, err := event.New(&event.Opts{
Target: event.Target{Type: event.TargetTypeIaas, Value: dbTpl.IaaSName},
Kind: permission.PermMachineTemplateUpdate,
Owner: token,
CustomData: event.FormToCustomData(InputFields(r)),
Allowed: event.Allowed(permission.PermMachineReadEvents, iaasCtx),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
return dbTpl.Update(¶mTemplate)
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L555-L641
|
func (l *InclusiveRanges) normalized(invert bool) *InclusiveRanges {
normalized := &InclusiveRanges{}
var (
start int
end int
step int
current int
pending int
keepValue bool
)
totalRange := NewInclusiveRange(l.Min(), l.Max(), 1)
checkValue := l.Contains
if !invert {
checkValue = func(value int) bool {
return !l.Contains(value)
}
}
for it := totalRange.IterValues(); !it.IsDone(); {
current = it.Next()
keepValue = checkValue(current)
// Short-circuit if we encounter a value that
// is not in the original sequence.
if keepValue {
// fmt.Println(" Existing value")
// If we haven't accumulated 2+ values to
// add, just continue now and keep trying
if pending < 2 {
step++
// fmt.Println(" Increasing step to:", step)
continue
}
// If the step has changed from what we have
// already accumulated, then add what we have
// and start a new range.
if (current + 1 - end) != step {
// fmt.Println(" Step changed. Adding range:", start, end, step)
normalized.Append(start, end, step)
step = 1
start = current
pending = 0
}
continue
}
// fmt.Println(" Unique value")
// If the value we want to keep is a different
// stepping from the pending values, add what
// we have and start a new range again.
if pending >= 2 && current-end != step {
// fmt.Println(" Step changed. Adding range:", start, end, step)
normalized.Append(start, end, step)
pending = 0
}
end = current
// Start a new range
if pending == 0 {
// fmt.Println(" Starting new range")
start = end
step = 1
}
pending++
continue
}
// Flush the remaining values
if pending > 0 {
// fmt.Println(" Flushing and adding remaining range:", start, end, step)
normalized.Append(start, end, step)
}
return normalized
}
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gbytes/buffer.go#L136-L143
|
func (b *Buffer) Contents() []byte {
b.lock.Lock()
defer b.lock.Unlock()
contents := make([]byte, len(b.contents))
copy(contents, b.contents)
return contents
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/mirror/syncer.go#L39-L41
|
func NewSyncer(c *clientv3.Client, prefix string, rev int64) Syncer {
return &syncer{c: c, prefix: prefix, rev: rev}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/server/driver.go#L1837-L1839
|
func (d *driver) scratchFilePrefix(file *pfs.File) (string, error) {
return path.Join(d.scratchCommitPrefix(file.Commit), file.Path), nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/ranch/ranch.go#L150-L200
|
func (r *Ranch) AcquireByState(state, dest, owner string, names []string) ([]common.Resource, error) {
r.resourcesLock.Lock()
defer r.resourcesLock.Unlock()
if names == nil {
return nil, fmt.Errorf("must provide names of expected resources")
}
rNames := map[string]bool{}
for _, t := range names {
rNames[t] = true
}
allResources, err := r.Storage.GetResources()
if err != nil {
logrus.WithError(err).Errorf("could not get resources")
return nil, &ResourceNotFound{state}
}
var resources []common.Resource
for idx := range allResources {
res := allResources[idx]
if state == res.State {
if res.Owner != "" {
continue
}
if rNames[res.Name] {
res.LastUpdate = r.UpdateTime()
res.Owner = owner
res.State = dest
if err := r.Storage.UpdateResource(res); err != nil {
logrus.WithError(err).Errorf("could not update resource %s", res.Name)
return nil, err
}
resources = append(resources, res)
delete(rNames, res.Name)
}
}
}
if len(rNames) != 0 {
var missingResources []string
for n := range rNames {
missingResources = append(missingResources, n)
}
err := &ResourceNotFound{state}
logrus.WithError(err).Errorf("could not find required resources %s", strings.Join(missingResources, ", "))
return resources, err
}
return resources, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L704-L707
|
func (p PrintToPDFParams) WithScale(scale float64) *PrintToPDFParams {
p.Scale = scale
return &p
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/levels.go#L201-L207
|
func closeAllTables(tables [][]*table.Table) {
for _, tableSlice := range tables {
for _, table := range tableSlice {
_ = table.Close()
}
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/easyjson.go#L1726-L1730
|
func (v *AuthChallenge) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoFetch15(&r, v)
return r.Error()
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/api15gen/param_analyzer.go#L301-L351
|
func (p *ParamAnalyzer) newParam(path string, param map[string]interface{}, dType gen.DataType) *gen.ActionParam {
var description, regexp string
var mandatory, nonBlank bool
var validValues []interface{}
if d, ok := param["description"]; ok {
description = d.(string)
}
if m, ok := param["mandatory"]; ok {
mandatory = m.(bool)
}
if n, ok := param["non_blank"]; ok {
nonBlank = n.(bool)
}
if r, ok := param["regexp"]; ok {
regexp = r.(string)
}
if v, ok := param["valid_values"]; ok {
validValues = v.([]interface{})
}
native := nativeNameFromPath(path)
isLeaf := false
if _, ok := dType.(*gen.EnumerableDataType); ok {
isLeaf = true
} else {
for _, l := range p.leafParamNames {
if path == l {
isLeaf = true
break
}
}
}
queryName := path
if _, ok := dType.(*gen.ArrayDataType); ok {
queryName += "[]"
}
actionParam := &gen.ActionParam{
Name: native,
QueryName: queryName,
Description: removeBlankLines(description),
VarName: parseParamName(native),
Type: dType,
Mandatory: mandatory,
NonBlank: nonBlank,
Regexp: regexp,
ValidValues: validValues,
}
if isLeaf {
p.LeafParams = append(p.LeafParams, actionParam)
}
return actionParam
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/watch.go#L699-L710
|
func (w *watchGrpcStream) unicastResponse(wr *WatchResponse, watchId int64) bool {
ws, ok := w.substreams[watchId]
if !ok {
return false
}
select {
case ws.recvc <- wr:
case <-ws.donec:
return false
}
return true
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/datastore.go#L378-L390
|
func DeleteMulti(c context.Context, key []*Key) error {
if len(key) == 0 {
return nil
}
if err := multiValid(key); err != nil {
return err
}
req := &pb.DeleteRequest{
Key: multiKeyToProto(internal.FullyQualifiedAppID(c), key),
}
res := &pb.DeleteResponse{}
return internal.Call(c, "datastore_v3", "Delete", req, res)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L1231-L1235
|
func (v ShorthandEntry) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss10(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L360-L363
|
func (m *Mat) Get3D(x, y, z int) Scalar {
ret := C.cvGet3D(unsafe.Pointer(m), C.int(x), C.int(y), C.int(z))
return Scalar(ret)
}
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/client.go#L92-L105
|
func (p *PactClient) StartServer(args []string, port int) *types.MockServer {
log.Println("[DEBUG] client: starting a server with args:", args, "port:", port)
args = append(args, []string{"--port", strconv.Itoa(port)}...)
svc := p.pactMockSvcManager.NewService(args)
cmd := svc.Start()
waitForPort(port, p.getNetworkInterface(), p.Address, p.TimeoutDuration,
fmt.Sprintf(`Timed out waiting for Mock Server to start on port %d - are you sure it's running?`, port))
return &types.MockServer{
Pid: cmd.Process.Pid,
Port: port,
}
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/user/user.go#L71-L80
|
func LogoutURL(c context.Context, dest string) (string, error) {
req := &pb.CreateLogoutURLRequest{
DestinationUrl: proto.String(dest),
}
res := &pb.CreateLogoutURLResponse{}
if err := internal.Call(c, "user", "CreateLogoutURL", req, res); err != nil {
return "", err
}
return *res.LogoutUrl, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/gcsupload/options.go#L59-L76
|
func (o *Options) Validate() error {
if o.gcsPath.String() != "" {
o.Bucket = o.gcsPath.Bucket()
o.PathPrefix = o.gcsPath.Object()
}
if !o.DryRun {
if o.Bucket == "" {
return errors.New("GCS upload was requested no GCS bucket was provided")
}
if o.GcsCredentialsFile == "" {
return errors.New("GCS upload was requested but no GCS credentials file was provided")
}
}
return o.GCSConfiguration.Validate()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/metrics/metrics.go#L33-L48
|
func PushMetrics(component, endpoint string, interval time.Duration) {
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
for {
select {
case <-time.Tick(interval):
if err := push.FromGatherer(component, push.HostnameGroupingKey(), endpoint, prometheus.DefaultGatherer); err != nil {
logrus.WithField("component", component).WithError(err).Error("Failed to push metrics.")
}
case <-sig:
logrus.WithField("component", component).Infof("Metrics pusher shutting down...")
return
}
}
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/commitment.go#L85-L101
|
func (c *commitment) recalculate() {
if len(c.matchIndexes) == 0 {
return
}
matched := make([]uint64, 0, len(c.matchIndexes))
for _, idx := range c.matchIndexes {
matched = append(matched, idx)
}
sort.Sort(uint64Slice(matched))
quorumMatchIndex := matched[(len(matched)-1)/2]
if quorumMatchIndex > c.commitIndex && quorumMatchIndex >= c.startIndex {
c.commitIndex = quorumMatchIndex
asyncNotifyCh(c.commitCh)
}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/deploy/assets/assets.go#L1309-L1417
|
func WriteAssets(encoder Encoder, opts *AssetOpts, objectStoreBackend backend,
persistentDiskBackend backend, volumeSize int,
hostPath string) error {
// If either backend is "local", both must be "local"
if (persistentDiskBackend == localBackend || objectStoreBackend == localBackend) &&
persistentDiskBackend != objectStoreBackend {
return fmt.Errorf("if either persistentDiskBackend or objectStoreBackend "+
"is \"local\", both must be \"local\", but persistentDiskBackend==%d, \n"+
"and objectStoreBackend==%d", persistentDiskBackend, objectStoreBackend)
}
fillDefaultResourceRequests(opts, persistentDiskBackend)
if opts.DashOnly {
if dashErr := WriteDashboardAssets(encoder, opts); dashErr != nil {
return dashErr
}
return nil
}
if err := encoder.Encode(ServiceAccount(opts)); err != nil {
return err
}
if !opts.NoRBAC {
if opts.LocalRoles {
if err := encoder.Encode(Role(opts)); err != nil {
return err
}
if err := encoder.Encode(RoleBinding(opts)); err != nil {
return err
}
} else {
if err := encoder.Encode(ClusterRole(opts)); err != nil {
return err
}
if err := encoder.Encode(ClusterRoleBinding(opts)); err != nil {
return err
}
}
}
if opts.EtcdNodes > 0 && opts.EtcdVolume != "" {
return fmt.Errorf("only one of --dynamic-etcd-nodes and --static-etcd-volume should be given, but not both")
}
// In the dynamic route, we create a storage class which dynamically
// provisions volumes, and run etcd as a statful set.
// In the static route, we create a single volume, a single volume
// claim, and run etcd as a replication controller with a single node.
if objectStoreBackend == localBackend {
if err := encoder.Encode(EtcdDeployment(opts, hostPath)); err != nil {
return err
}
} else if opts.EtcdNodes > 0 {
// Create a StorageClass, if the user didn't provide one.
if opts.EtcdStorageClassName == "" {
sc, err := EtcdStorageClass(opts, persistentDiskBackend)
if err != nil {
return err
}
if sc != nil {
if err = encoder.Encode(sc); err != nil {
return err
}
}
}
if err := encoder.Encode(EtcdHeadlessService(opts)); err != nil {
return err
}
if err := encoder.Encode(EtcdStatefulSet(opts, persistentDiskBackend, volumeSize)); err != nil {
return err
}
} else if opts.EtcdVolume != "" || persistentDiskBackend == localBackend {
volume, err := EtcdVolume(persistentDiskBackend, opts, hostPath, opts.EtcdVolume, volumeSize)
if err != nil {
return err
}
if err = encoder.Encode(volume); err != nil {
return err
}
if err = encoder.Encode(EtcdVolumeClaim(volumeSize, opts)); err != nil {
return err
}
if err = encoder.Encode(EtcdDeployment(opts, "")); err != nil {
return err
}
} else {
return fmt.Errorf("unless deploying locally, either --dynamic-etcd-nodes or --static-etcd-volume needs to be provided")
}
if err := encoder.Encode(EtcdNodePortService(objectStoreBackend == localBackend, opts)); err != nil {
return err
}
if err := encoder.Encode(PachdService(opts)); err != nil {
return err
}
if err := encoder.Encode(PachdDeployment(opts, objectStoreBackend, hostPath)); err != nil {
return err
}
if !opts.NoDash {
if err := WriteDashboardAssets(encoder, opts); err != nil {
return err
}
}
if opts.TLS != nil {
if err := WriteTLSSecret(encoder, opts); err != nil {
return err
}
}
return nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/httpclient/http.go#L365-L388
|
func (d *dumpClient) dumpRequest(req *http.Request) []byte {
df := d.dumpFormat()
if df == NoDump {
return nil
}
reqBody, err := dumpReqBody(req)
if err != nil {
log.Error("Failed to load request body for dump", "error", err.Error())
}
if df.IsDebug() {
var buffer bytes.Buffer
buffer.WriteString(req.Method + " " + req.URL.String() + "\n")
d.writeHeaders(&buffer, req.Header)
if reqBody != nil {
buffer.WriteString("\n")
buffer.Write(reqBody)
buffer.WriteString("\n")
}
fmt.Fprint(OsStderr, buffer.String())
} else if df.IsJSON() {
return reqBody
}
return nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pkg/grpcutil/stream.go#L139-L149
|
func WriteFromStreamingBytesClient(streamingBytesClient StreamingBytesClient, writer io.Writer) error {
for bytesValue, err := streamingBytesClient.Recv(); err != io.EOF; bytesValue, err = streamingBytesClient.Recv() {
if err != nil {
return err
}
if _, err = writer.Write(bytesValue.Value); err != nil {
return err
}
}
return nil
}
|
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/archive50.go#L180-L208
|
func (a *archive50) getKeys(b *readBuf) (keys [][]byte, err error) {
if len(*b) < 17 {
return nil, errCorruptEncrypt
}
// read kdf count and salt
kdfCount := int(b.byte())
if kdfCount > maxKdfCount {
return nil, errCorruptEncrypt
}
kdfCount = 1 << uint(kdfCount)
salt := b.bytes(16)
// check cache of keys for match
for _, v := range a.keyCache {
if kdfCount == v.kdfCount && bytes.Equal(salt, v.salt) {
return v.keys, nil
}
}
// not found, calculate keys
keys = calcKeys50(a.pass, salt, kdfCount)
// store in cache
copy(a.keyCache[1:], a.keyCache[:])
a.keyCache[0].kdfCount = kdfCount
a.keyCache[0].salt = append([]byte(nil), salt...)
a.keyCache[0].keys = keys
return keys, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L5761-L5765
|
func (v EventFrameStoppedLoading) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage60(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/node/raft.go#L28-L61
|
func DetermineRaftNode(tx *db.NodeTx) (*db.RaftNode, error) {
config, err := ConfigLoad(tx)
if err != nil {
return nil, err
}
address := config.ClusterAddress()
// If cluster.https_address is the empty string, then this LXD instance is
// not running in clustering mode.
if address == "" {
return &db.RaftNode{ID: 1}, nil
}
nodes, err := tx.RaftNodes()
if err != nil {
return nil, err
}
// If cluster.https_address and the raft_nodes table is not populated,
// this must be a joining node.
if len(nodes) == 0 {
return &db.RaftNode{ID: 1}, nil
}
// Try to find a matching node.
for _, node := range nodes {
if node.Address == address {
return &node, nil
}
}
return nil, nil
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/tracer.go#L114-L116
|
func (t *Tracer) Log(key string, value interface{}) {
t.Last().LogKV(key, value)
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/servers/servers.go#L203-L213
|
func (s *Servers) TCPAddr(name string) (a *net.TCPAddr) {
s.mu.Lock()
defer s.mu.Unlock()
for _, srv := range s.servers {
if srv.name == name {
return srv.tcpAddr
}
}
return nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/auth/server/api_server.go#L1019-L1042
|
func (a *apiServer) getOneTimePassword(ctx context.Context, username string, expiration time.Time) (code string, err error) {
// Create OTPInfo that will be stored
otpInfo := &authclient.OTPInfo{
Subject: username,
}
if !expiration.IsZero() {
expirationProto, err := types.TimestampProto(expiration)
if err != nil {
return "", fmt.Errorf("could not create OTP with expiration time %s: %v",
expiration.String(), err)
}
otpInfo.SessionExpiration = expirationProto
}
// Generate and store new OTP
code = "auth_code:" + uuid.NewWithoutDashes()
if _, err = col.NewSTM(ctx, a.env.GetEtcdClient(), func(stm col.STM) error {
return a.authenticationCodes.ReadWrite(stm).PutTTL(hashToken(code),
otpInfo, defaultAuthCodeTTLSecs)
}); err != nil {
return "", err
}
return code, nil
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/stream.go#L114-L125
|
func (st *Stream) produceRanges(ctx context.Context) {
splits := st.db.KeySplits(st.Prefix)
start := y.SafeCopy(nil, st.Prefix)
for _, key := range splits {
st.rangeCh <- keyRange{left: start, right: y.SafeCopy(nil, []byte(key))}
start = y.SafeCopy(nil, []byte(key))
}
// Edge case: prefix is empty and no splits exist. In that case, we should have at least one
// keyRange output.
st.rangeCh <- keyRange{left: start}
close(st.rangeCh)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2stats/queue.go#L81-L100
|
func (q *statsQueue) Rate() (float64, float64) {
front, back := q.frontAndBack()
if front == nil || back == nil {
return 0, 0
}
if time.Since(back.SendingTime) > time.Second {
q.Clear()
return 0, 0
}
sampleDuration := back.SendingTime.Sub(front.SendingTime)
pr := float64(q.Len()) / float64(sampleDuration) * float64(time.Second)
br := float64(q.ReqSize()) / float64(sampleDuration) * float64(time.Second)
return pr, br
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pkg/require/require.go#L226-L231
|
func ElementsEqual(tb testing.TB, expecteds interface{}, actuals interface{}, msgAndArgs ...interface{}) {
tb.Helper()
if err := ElementsEqualOrErr(expecteds, actuals); err != nil {
fatal(tb, msgAndArgs, err.Error())
}
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/resource.go#L51-L53
|
func (v BaseResource) List(c Context) error {
return c.Error(404, errors.New("resource not implemented"))
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pps/server/api_server.go#L1588-L1612
|
func (a *apiServer) sudo(pachClient *client.APIClient, f func(*client.APIClient) error) error {
// Get PPS auth token
superUserTokenOnce.Do(func() {
b := backoff.NewExponentialBackOff()
b.MaxElapsedTime = 60 * time.Second
b.MaxInterval = 5 * time.Second
if err := backoff.Retry(func() error {
superUserTokenCol := col.NewCollection(a.env.GetEtcdClient(), ppsconsts.PPSTokenKey, nil, &types.StringValue{}, nil, nil).ReadOnly(pachClient.Ctx())
var result types.StringValue
if err := superUserTokenCol.Get("", &result); err != nil {
return err
}
superUserToken = result.Value
return nil
}, b); err != nil {
panic(fmt.Sprintf("couldn't get PPS superuser token: %v", err))
}
})
// Copy pach client, but keep ctx (to propagate cancellation). Replace token
// with superUserToken
superUserClient := pachClient.WithCtx(pachClient.Ctx())
superUserClient.SetAuthToken(superUserToken)
return f(superUserClient)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/eagain/file.go#L16-L30
|
func (er Reader) Read(p []byte) (int, error) {
again:
n, err := er.Reader.Read(p)
if err == nil {
return n, nil
}
// keep retrying on EAGAIN
errno, ok := shared.GetErrno(err)
if ok && (errno == syscall.EAGAIN || errno == syscall.EINTR) {
goto again
}
return n, err
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/docker/config/config.go#L286-L297
|
func convertToHostname(url string) string {
stripped := url
if strings.HasPrefix(url, "http://") {
stripped = strings.TrimPrefix(url, "http://")
} else if strings.HasPrefix(url, "https://") {
stripped = strings.TrimPrefix(url, "https://")
}
nameParts := strings.SplitN(stripped, "/", 2)
return nameParts[0]
}
|
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/log_adapter.go#L159-L161
|
func (la *LogAdapter) Infom(m *Attrs, msg string, a ...interface{}) error {
return la.Log(LevelInfo, m, msg, a...)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_pools.go#L55-L69
|
func (r *ProtocolLXD) GetStoragePool(name string) (*api.StoragePool, string, error) {
if !r.HasExtension("storage") {
return nil, "", fmt.Errorf("The server is missing the required \"storage\" API extension")
}
pool := api.StoragePool{}
// Fetch the raw value
etag, err := r.queryStruct("GET", fmt.Sprintf("/storage-pools/%s", url.QueryEscape(name)), nil, "", &pool)
if err != nil {
return nil, "", err
}
return &pool, etag, nil
}
|
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/storage/postgres/storage.go#L384-L407
|
func (s *Storage) Setup() error {
query := fmt.Sprintf(`
CREATE SCHEMA IF NOT EXISTS %s;
CREATE TABLE IF NOT EXISTS %s.%s (
access_token BYTEA PRIMARY KEY,
refresh_token BYTEA,
subject_id TEXT NOT NULL,
subject_client TEXT,
bag bytea NOT NULL,
expire_at TIMESTAMPTZ NOT NULL DEFAULT (NOW() + '%d seconds')
);
CREATE INDEX ON %s.%s (refresh_token);
CREATE INDEX ON %s.%s (subject_id);
CREATE INDEX ON %s.%s (expire_at DESC);
`, s.schema, s.schema, s.table, int64(s.ttl.Seconds()),
s.schema, s.table,
s.schema, s.table,
s.schema, s.table,
)
_, err := s.db.Exec(query)
return err
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/fileseq.go#L175-L215
|
func frameRangeMatches(frange string) ([][]string, error) {
for _, k := range defaultPadding.AllChars() {
frange = strings.Replace(frange, k, "", -1)
}
var (
matched bool
match []string
rx *regexp.Regexp
)
frange = strings.Replace(frange, " ", "", -1)
// For each comma-sep component, we will parse a frame range
parts := strings.Split(frange, ",")
size := len(parts)
matches := make([][]string, size, size)
for i, part := range parts {
matched = false
// Build up frames for all comma-sep components
for _, rx = range rangePatterns {
if match = rx.FindStringSubmatch(part); match == nil {
continue
}
matched = true
matches[i] = match[1:]
}
// If any component of the comma-sep frame range fails to
// parse, we bail out
if !matched {
err := fmt.Errorf("Failed to parse frame range: %s on part %q", frange, part)
return nil, err
}
}
return matches, nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/raft.go#L326-L349
|
func raftNetworkTransport(
db *db.Node,
address string,
logger *log.Logger,
timeout time.Duration,
dial rafthttp.Dial) (raft.Transport, *rafthttp.Handler, *rafthttp.Layer, error) {
handler := rafthttp.NewHandlerWithLogger(logger)
addr, err := net.ResolveTCPAddr("tcp", address)
if err != nil {
return nil, nil, nil, errors.Wrap(err, "invalid node address")
}
layer := rafthttp.NewLayer(raftEndpoint, addr, handler, dial)
config := &raft.NetworkTransportConfig{
Logger: logger,
Stream: layer,
MaxPool: 2,
Timeout: timeout,
ServerAddressProvider: &raftAddressProvider{db: db},
}
transport := raft.NewNetworkTransportWithConfig(config)
return transport, handler, layer, nil
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/object.go#L256-L271
|
func (p *Process) ForEachPtr(x Object, fn func(int64, Object, int64) bool) {
size := p.Size(x)
for i := int64(0); i < size; i += p.proc.PtrSize() {
a := core.Address(x).Add(i)
if !p.isPtrFromHeap(a) {
continue
}
ptr := p.proc.ReadPtr(a)
y, off := p.FindObject(ptr)
if y != 0 {
if !fn(i, y, off) {
return
}
}
}
}
|
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/atomic_rbuf.go#L45-L52
|
func (b *AtomicFixedSizeRingBuf) ContigLen() int {
b.tex.Lock()
defer b.tex.Unlock()
extent := b.Beg + b.readable
firstContigLen := intMin2(extent, b.N) - b.Beg
return firstContigLen
}
|
https://github.com/brankas/sentinel/blob/0ff081867c31a45cb71f5976ea6144fd06a557b5/sentinel.go#L38-L66
|
func New(opts ...Option) (*Sentinel, error) {
s := &Sentinel{
shutdownDuration: DefaultShutdownDuration,
logf: func(string, ...interface{}) {},
}
var err error
// apply options
for _, o := range opts {
if err = o(s); err != nil {
return nil, err
}
}
// ensure sigs set
if s.shutdownSigs == nil {
s.shutdownSigs = []os.Signal{os.Interrupt}
}
// ensure errf set
if s.errf == nil {
s.errf = func(str string, v ...interface{}) {
s.logf("ERROR: "+str, v...)
}
}
return s, nil
}
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/codec.go#L257-L303
|
func (cdc *Codec) PrintTypes(out io.Writer) error {
cdc.mtx.RLock()
defer cdc.mtx.RUnlock()
// print header
if _, err := io.WriteString(out, "| Type | Name | Prefix | Length | Notes |\n"); err != nil {
return err
}
if _, err := io.WriteString(out, "| ---- | ---- | ------ | ----- | ------ |\n"); err != nil {
return err
}
// only print concrete types for now (if we want everything, we can iterate over the typeInfos map instead)
for _, i := range cdc.concreteInfos {
io.WriteString(out, "| ")
// TODO(ismail): optionally create a link to code on github:
if _, err := io.WriteString(out, i.Type.Name()); err != nil {
return err
}
if _, err := io.WriteString(out, " | "); err != nil {
return err
}
if _, err := io.WriteString(out, i.Name); err != nil {
return err
}
if _, err := io.WriteString(out, " | "); err != nil {
return err
}
if _, err := io.WriteString(out, fmt.Sprintf("0x%X", i.Prefix)); err != nil {
return err
}
if _, err := io.WriteString(out, " | "); err != nil {
return err
}
if _, err := io.WriteString(out, getLengthStr(i)); err != nil {
return err
}
if _, err := io.WriteString(out, " | "); err != nil {
return err
}
// empty notes table data by default // TODO(ismail): make this configurable
io.WriteString(out, " |\n")
}
// finish table
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L2241-L2245
|
func (v *SetBypassServiceWorkerParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork17(&r, v)
return r.Error()
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/transport/tls.go#L25-L49
|
func ValidateSecureEndpoints(tlsInfo TLSInfo, eps []string) ([]string, error) {
t, err := NewTransport(tlsInfo, 5*time.Second)
if err != nil {
return nil, err
}
var errs []string
var endpoints []string
for _, ep := range eps {
if !strings.HasPrefix(ep, "https://") {
errs = append(errs, fmt.Sprintf("%q is insecure", ep))
continue
}
conn, cerr := t.Dial("tcp", ep[len("https://"):])
if cerr != nil {
errs = append(errs, fmt.Sprintf("%q failed to dial (%v)", ep, cerr))
continue
}
conn.Close()
endpoints = append(endpoints, ep)
}
if len(errs) != 0 {
err = fmt.Errorf("%s", strings.Join(errs, ","))
}
return endpoints, err
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcec2manager/tcec2manager.go#L289-L292
|
func (eC2Manager *EC2Manager) Regions_SignedURL(duration time.Duration) (*url.URL, error) {
cd := tcclient.Client(*eC2Manager)
return (&cd).SignedURL("/internal/regions", nil, duration)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/fetcher/issue-events.go#L54-L70
|
func UpdateIssueEvents(issueID int, db *gorm.DB, client ClientInterface) {
latest, err := findLatestEvent(issueID, db, client.RepositoryName())
if err != nil {
glog.Error("Failed to find last event: ", err)
return
}
c := make(chan *github.IssueEvent, 500)
go client.FetchIssueEvents(issueID, latest, c)
for event := range c {
eventOrm, err := NewIssueEvent(event, issueID, client.RepositoryName())
if err != nil {
glog.Error("Failed to create issue-event", err)
}
db.Create(eventOrm)
}
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/transaction.go#L56-L77
|
func RunInTransaction(c context.Context, f func(tc context.Context) error, opts *TransactionOptions) error {
xg := false
if opts != nil {
xg = opts.XG
}
readOnly := false
if opts != nil {
readOnly = opts.ReadOnly
}
attempts := 3
if opts != nil && opts.Attempts > 0 {
attempts = opts.Attempts
}
var t *pb.Transaction
var err error
for i := 0; i < attempts; i++ {
if t, err = internal.RunTransactionOnce(c, f, xg, readOnly, t); err != internal.ErrConcurrentTransaction {
return err
}
}
return ErrConcurrentTransaction
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L728-L731
|
func (p PrintToPDFParams) WithMarginBottom(marginBottom float64) *PrintToPDFParams {
p.MarginBottom = marginBottom
return &p
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/highgui.go#L505-L508
|
func (capture *Capture) RetrieveFrame(streamIdx int) *IplImage {
rv := C.cvRetrieveFrame((*C.CvCapture)(capture), C.int(streamIdx))
return (*IplImage)(rv)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domdebugger/domdebugger.go#L90-L95
|
func RemoveDOMBreakpoint(nodeID cdp.NodeID, typeVal DOMBreakpointType) *RemoveDOMBreakpointParams {
return &RemoveDOMBreakpointParams{
NodeID: nodeID,
Type: typeVal,
}
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5269-L5278
|
func (u BucketEntry) GetLiveEntry() (result LedgerEntry, ok bool) {
armName, _ := u.ArmForSwitch(int32(u.Type))
if armName == "LiveEntry" {
result = *u.LiveEntry
ok = true
}
return
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/state.go#L142-L148
|
func (r *raftState) goFunc(f func()) {
r.routinesGroup.Add(1)
go func() {
defer r.routinesGroup.Done()
f()
}()
}
|
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/version/version.go#L48-L57
|
func GetVersion() *Version {
return &Version{
Version: KubicornVersion,
GitCommit: GitSha,
BuildDate: time.Now().UTC().String(),
GoVersion: runtime.Version(),
GOOS: runtime.GOOS,
GOArch: runtime.GOARCH,
}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs/pfs.go#L17-L19
|
func (c *Commit) FullID() string {
return fmt.Sprintf("%s/%s", c.Repo.Name, c.ID)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage.go#L606-L608
|
func getImageMountPoint(poolName string, fingerprint string) string {
return shared.VarPath("storage-pools", poolName, "images", fingerprint)
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/urlfetch/urlfetch.go#L127-L205
|
func (t *Transport) RoundTrip(req *http.Request) (res *http.Response, err error) {
methNum, ok := pb.URLFetchRequest_RequestMethod_value[req.Method]
if !ok {
return nil, fmt.Errorf("urlfetch: unsupported HTTP method %q", req.Method)
}
method := pb.URLFetchRequest_RequestMethod(methNum)
freq := &pb.URLFetchRequest{
Method: &method,
Url: proto.String(urlString(req.URL)),
FollowRedirects: proto.Bool(false), // http.Client's responsibility
MustValidateServerCertificate: proto.Bool(!t.AllowInvalidServerCertificate),
}
if deadline, ok := t.Context.Deadline(); ok {
freq.Deadline = proto.Float64(deadline.Sub(time.Now()).Seconds())
}
for k, vals := range req.Header {
for _, val := range vals {
freq.Header = append(freq.Header, &pb.URLFetchRequest_Header{
Key: proto.String(k),
Value: proto.String(val),
})
}
}
if methodAcceptsRequestBody[req.Method] && req.Body != nil {
// Avoid a []byte copy if req.Body has a Bytes method.
switch b := req.Body.(type) {
case interface {
Bytes() []byte
}:
freq.Payload = b.Bytes()
default:
freq.Payload, err = ioutil.ReadAll(req.Body)
if err != nil {
return nil, err
}
}
}
fres := &pb.URLFetchResponse{}
if err := internal.Call(t.Context, "urlfetch", "Fetch", freq, fres); err != nil {
return nil, err
}
res = &http.Response{}
res.StatusCode = int(*fres.StatusCode)
res.Status = fmt.Sprintf("%d %s", res.StatusCode, statusCodeToText(res.StatusCode))
res.Header = make(http.Header)
res.Request = req
// Faked:
res.ProtoMajor = 1
res.ProtoMinor = 1
res.Proto = "HTTP/1.1"
res.Close = true
for _, h := range fres.Header {
hkey := http.CanonicalHeaderKey(*h.Key)
hval := *h.Value
if hkey == "Content-Length" {
// Will get filled in below for all but HEAD requests.
if req.Method == "HEAD" {
res.ContentLength, _ = strconv.ParseInt(hval, 10, 64)
}
continue
}
res.Header.Add(hkey, hval)
}
if req.Method != "HEAD" {
res.ContentLength = int64(len(fres.Content))
}
truncated := fres.GetContentWasTruncated()
res.Body = &bodyReader{content: fres.Content, truncated: truncated}
return
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/auth.go#L155-L190
|
func changePassword(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
managed, ok := app.AuthScheme.(auth.ManagedScheme)
if !ok {
return &errors.HTTP{Code: http.StatusBadRequest, Message: nonManagedSchemeMsg}
}
evt, err := event.New(&event.Opts{
Target: userTarget(t.GetUserName()),
Kind: permission.PermUserUpdatePassword,
Owner: t,
Allowed: event.Allowed(permission.PermUserReadEvents, permission.Context(permTypes.CtxUser, t.GetUserName())),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
oldPassword := InputValue(r, "old")
newPassword := InputValue(r, "new")
confirmPassword := InputValue(r, "confirm")
if oldPassword == "" || newPassword == "" {
return &errors.HTTP{
Code: http.StatusBadRequest,
Message: "Both the old and the new passwords are required.",
}
}
if newPassword != confirmPassword {
return &errors.HTTP{
Code: http.StatusBadRequest,
Message: "New password and password confirmation didn't match.",
}
}
err = managed.ChangePassword(t, oldPassword, newPassword)
if err != nil {
return handleAuthError(err)
}
return nil
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/value.go#L51-L156
|
func ExprFromValue(val interface{}) bzl.Expr {
if e, ok := val.(bzl.Expr); ok {
return e
}
rv := reflect.ValueOf(val)
switch rv.Kind() {
case reflect.Bool:
tok := "False"
if rv.Bool() {
tok = "True"
}
return &bzl.LiteralExpr{Token: tok}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return &bzl.LiteralExpr{Token: fmt.Sprintf("%d", val)}
case reflect.Float32, reflect.Float64:
return &bzl.LiteralExpr{Token: fmt.Sprintf("%f", val)}
case reflect.String:
return &bzl.StringExpr{Value: val.(string)}
case reflect.Slice, reflect.Array:
var list []bzl.Expr
for i := 0; i < rv.Len(); i++ {
elem := ExprFromValue(rv.Index(i).Interface())
list = append(list, elem)
}
return &bzl.ListExpr{List: list}
case reflect.Map:
rkeys := rv.MapKeys()
sort.Sort(byString(rkeys))
args := make([]bzl.Expr, len(rkeys))
for i, rk := range rkeys {
label := fmt.Sprintf("@io_bazel_rules_go//go/platform:%s", mapKeyString(rk))
k := &bzl.StringExpr{Value: label}
v := ExprFromValue(rv.MapIndex(rk).Interface())
if l, ok := v.(*bzl.ListExpr); ok {
l.ForceMultiLine = true
}
args[i] = &bzl.KeyValueExpr{Key: k, Value: v}
}
args = append(args, &bzl.KeyValueExpr{
Key: &bzl.StringExpr{Value: "//conditions:default"},
Value: &bzl.ListExpr{},
})
sel := &bzl.CallExpr{
X: &bzl.Ident{Name: "select"},
List: []bzl.Expr{&bzl.DictExpr{List: args, ForceMultiLine: true}},
}
return sel
case reflect.Struct:
switch val := val.(type) {
case GlobValue:
patternsValue := ExprFromValue(val.Patterns)
globArgs := []bzl.Expr{patternsValue}
if len(val.Excludes) > 0 {
excludesValue := ExprFromValue(val.Excludes)
globArgs = append(globArgs, &bzl.KeyValueExpr{
Key: &bzl.StringExpr{Value: "excludes"},
Value: excludesValue,
})
}
return &bzl.CallExpr{
X: &bzl.LiteralExpr{Token: "glob"},
List: globArgs,
}
case PlatformStrings:
var pieces []bzl.Expr
if len(val.Generic) > 0 {
pieces = append(pieces, ExprFromValue(val.Generic))
}
if len(val.OS) > 0 {
pieces = append(pieces, ExprFromValue(val.OS))
}
if len(val.Arch) > 0 {
pieces = append(pieces, ExprFromValue(val.Arch))
}
if len(val.Platform) > 0 {
pieces = append(pieces, ExprFromValue(val.Platform))
}
if len(pieces) == 0 {
return &bzl.ListExpr{}
} else if len(pieces) == 1 {
return pieces[0]
} else {
e := pieces[0]
if list, ok := e.(*bzl.ListExpr); ok {
list.ForceMultiLine = true
}
for _, piece := range pieces[1:] {
e = &bzl.BinaryExpr{X: e, Y: piece, Op: "+"}
}
return e
}
}
}
log.Panicf("type not supported: %T", val)
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/sys/fs.go#L37-L67
|
func (s *OS) initDirs() error {
dirs := []struct {
path string
mode os.FileMode
}{
{s.VarDir, 0711},
{filepath.Join(s.VarDir, "backups"), 0700},
{s.CacheDir, 0700},
{filepath.Join(s.VarDir, "containers"), 0711},
{filepath.Join(s.VarDir, "database"), 0700},
{filepath.Join(s.VarDir, "devices"), 0711},
{filepath.Join(s.VarDir, "devlxd"), 0755},
{filepath.Join(s.VarDir, "disks"), 0700},
{filepath.Join(s.VarDir, "images"), 0700},
{s.LogDir, 0700},
{filepath.Join(s.VarDir, "networks"), 0711},
{filepath.Join(s.VarDir, "security"), 0700},
{filepath.Join(s.VarDir, "shmounts"), 0711},
{filepath.Join(s.VarDir, "snapshots"), 0700},
{filepath.Join(s.VarDir, "storage-pools"), 0711},
}
for _, dir := range dirs {
err := os.Mkdir(dir.path, dir.mode)
if err != nil && !os.IsExist(err) {
return errors.Wrapf(err, "failed to init dir %s", dir.path)
}
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/types.go#L187-L199
|
func (t *BreakLocationType) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch BreakLocationType(in.String()) {
case BreakLocationTypeDebuggerStatement:
*t = BreakLocationTypeDebuggerStatement
case BreakLocationTypeCall:
*t = BreakLocationTypeCall
case BreakLocationTypeReturn:
*t = BreakLocationTypeReturn
default:
in.AddError(errors.New("unknown BreakLocationType value"))
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L1713-L1717
|
func (v Rect) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom18(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcawsprovisioner/tcawsprovisioner.go#L119-L123
|
func (awsProvisioner *AwsProvisioner) ListWorkerTypeSummaries() (*ListWorkerTypeSummariesResponse, error) {
cd := tcclient.Client(*awsProvisioner)
responseObject, _, err := (&cd).APICall(nil, "GET", "/list-worker-type-summaries", new(ListWorkerTypeSummariesResponse), nil)
return responseObject.(*ListWorkerTypeSummariesResponse), err
}
|
https://github.com/mota/klash/blob/ca6c37a4c8c2e69831c428cf0c6daac80ab56c22/parameter.go#L31-L55
|
func (p *Parameter) DiscoverProperties(tag reflect.StructTag) error {
if len(tag) > 0 {
paramtype := reflect.TypeOf((*Parameter)(nil))
prefix := "Tag"
paramvalue := reflect.ValueOf(p)
for idx := 0; idx < paramtype.NumMethod(); idx++ {
method := paramtype.Method(idx)
if !strings.HasPrefix(method.Name, prefix) {
continue
}
tagname := "klash-" + strings.ToLower(method.Name[len(prefix):])
if tagval := tag.Get(tagname); tagval != "" {
methodValue := paramvalue.MethodByName(method.Name)
err := methodValue.Call([]reflect.Value{reflect.ValueOf(tagval)})[0].Interface()
if err != nil {
return (err).(error)
}
}
}
}
return nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/dag/dag.go#L78-L86
|
func (d *DAG) Ghosts() []string {
var result []string
for id := range d.children {
if _, ok := d.parents[id]; !ok {
result = append(result, id)
}
}
return result
}
|
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/host.go#L55-L81
|
func (h *Host) FindItems(options SearchType) ([]string, error) {
var jobHandle C.VixHandle = C.VIX_INVALID_HANDLE
var err C.VixError = C.VIX_OK
jobHandle = C.VixHost_FindItems(h.handle,
C.VixFindItemType(options), //searchType
C.VIX_INVALID_HANDLE, //searchCriteria
-1, //timeout
(*C.VixEventProc)(C.find_items_callback), //callbackProc
unsafe.Pointer(h)) //clientData
defer func() {
h.items = []string{}
C.Vix_ReleaseHandle(jobHandle)
}()
err = C.vix_job_wait(jobHandle)
if C.VIX_OK != err {
return nil, &Error{
Operation: "host.FindItems",
Code: int(err & 0xFFFF),
Text: C.GoString(C.Vix_GetErrorText(err, nil)),
}
}
return h.items, nil
}
|
https://github.com/btcsuite/btclog/blob/84c8d2346e9fc8c7b947e243b9c24e6df9fd206a/log.go#L204-L233
|
func formatHeader(buf *[]byte, t time.Time, lvl, tag string, file string, line int) {
year, month, day := t.Date()
hour, min, sec := t.Clock()
ms := t.Nanosecond() / 1e6
itoa(buf, year, 4)
*buf = append(*buf, '-')
itoa(buf, int(month), 2)
*buf = append(*buf, '-')
itoa(buf, day, 2)
*buf = append(*buf, ' ')
itoa(buf, hour, 2)
*buf = append(*buf, ':')
itoa(buf, min, 2)
*buf = append(*buf, ':')
itoa(buf, sec, 2)
*buf = append(*buf, '.')
itoa(buf, ms, 3)
*buf = append(*buf, " ["...)
*buf = append(*buf, lvl...)
*buf = append(*buf, "] "...)
*buf = append(*buf, tag...)
if file != "" {
*buf = append(*buf, ' ')
*buf = append(*buf, file...)
*buf = append(*buf, ':')
itoa(buf, line, -1)
}
*buf = append(*buf, ": "...)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/label/label.go#L87-L95
|
func getLabelsFromREMatches(matches [][]string) (labels []string) {
for _, match := range matches {
for _, label := range strings.Split(match[0], " ")[1:] {
label = strings.ToLower(match[1] + "/" + strings.TrimSpace(label))
labels = append(labels, label)
}
}
return
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/approve/approvers/owners.go#L185-L193
|
func (o Owners) GetShuffledApprovers() []string {
approversList := o.GetAllPotentialApprovers()
order := rand.New(rand.NewSource(o.seed)).Perm(len(approversList))
people := make([]string, 0, len(approversList))
for _, i := range order {
people = append(people, approversList[i])
}
return people
}
|
https://github.com/geoffgarside/ber/blob/27a1aff36ce64dbe5d93c08cc5f161983134ddc5/ber.go#L160-L196
|
func parseObjectIdentifier(bytes []byte) (s []int, err error) {
if len(bytes) == 0 {
err = asn1.SyntaxError{Msg: "zero length OBJECT IDENTIFIER"}
return
}
// In the worst case, we get two elements from the first byte (which is
// encoded differently) and then every varint is a single byte long.
s = make([]int, len(bytes)+1)
// The first varint is 40*value1 + value2:
// According to this packing, value1 can take the values 0, 1 and 2 only.
// When value1 = 0 or value1 = 1, then value2 is <= 39. When value1 = 2,
// then there are no restrictions on value2.
v, offset, err := _parseBase128Int(bytes, 0)
if err != nil {
return
}
if v < 80 {
s[0] = v / 40
s[1] = v % 40
} else {
s[0] = 2
s[1] = v - 80
}
i := 2
for ; offset < len(bytes); i++ {
v, offset, err = _parseBase128Int(bytes, offset)
if err != nil {
return
}
s[i] = v
}
s = s[0:i]
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/applicationcache/easyjson.go#L830-L834
|
func (v *EventApplicationCacheStatusUpdated) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoApplicationcache9(&r, v)
return r.Error()
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/loadbalancer.go#L54-L60
|
func (c *Client) ListLoadbalancers(dcid string) (*Loadbalancers, error) {
url := lbalColPath(dcid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty)
ret := &Loadbalancers{}
err := c.client.Get(url, ret, http.StatusOK)
return ret, err
}
|
https://github.com/kjk/lzmadec/blob/4c61f00ce86f6f11ed9630fa16b771889b08147b/lzmadec.go#L238-L268
|
func (a *Archive) GetFileReader(name string) (io.ReadCloser, error) {
found := false
for _, e := range a.Entries {
if e.Path == name {
found = true
break
}
}
if !found {
return nil, errors.New("file not in the archive")
}
params := []string{"x", "-so"}
if a.password != nil {
params = append(params, fmt.Sprintf("-p%s", *a.password))
}
params = append(params, a.Path, name)
cmd := exec.Command("7z", params...)
stdout, err := cmd.StdoutPipe()
rc := &readCloser{
rc: stdout,
cmd: cmd,
}
err = cmd.Start()
if err != nil {
stdout.Close()
return nil, err
}
return rc, nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L6723-L6731
|
func (u StellarMessage) MustEnvelope() ScpEnvelope {
val, ok := u.GetEnvelope()
if !ok {
panic("arm Envelope is not set")
}
return val
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/cmdutil/cobra.go#L177-L180
|
func (r *RepeatedStringArg) Set(s string) error {
*r = append(*r, s)
return nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3426-L3433
|
func (u AllowTrustResult) ArmForSwitch(sw int32) (string, bool) {
switch AllowTrustResultCode(sw) {
case AllowTrustResultCodeAllowTrustSuccess:
return "", true
default:
return "", true
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/deck/pr_history.go#L204-L239
|
func getGCSDirsForPR(config *config.Config, org, repo string, pr int) (map[string]sets.String, error) {
toSearch := make(map[string]sets.String)
fullRepo := org + "/" + repo
presubmits, ok := config.Presubmits[fullRepo]
if !ok {
return toSearch, fmt.Errorf("couldn't find presubmits for %q in config", fullRepo)
}
for _, presubmit := range presubmits {
var gcsConfig *v1.GCSConfiguration
if presubmit.DecorationConfig != nil && presubmit.DecorationConfig.GCSConfiguration != nil {
gcsConfig = presubmit.DecorationConfig.GCSConfiguration
} else {
// for undecorated jobs assume the default
gcsConfig = config.Plank.DefaultDecorationConfig.GCSConfiguration
}
gcsPath, _, _ := gcsupload.PathsForJob(gcsConfig, &downwardapi.JobSpec{
Type: v1.PresubmitJob,
Job: presubmit.Name,
Refs: &v1.Refs{
Repo: repo,
Org: org,
Pulls: []v1.Pull{
{Number: pr},
},
},
}, "")
gcsPath, _ = path.Split(path.Clean(gcsPath))
if _, ok := toSearch[gcsConfig.Bucket]; !ok {
toSearch[gcsConfig.Bucket] = sets.String{}
}
toSearch[gcsConfig.Bucket].Insert(gcsPath)
}
return toSearch, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/types.go#L296-L298
|
func (t Type) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/server.go#L1424-L1461
|
func (s *EtcdServer) TransferLeadership() error {
if !s.isLeader() {
if lg := s.getLogger(); lg != nil {
lg.Info(
"skipped leadership transfer; local server is not leader",
zap.String("local-member-id", s.ID().String()),
zap.String("current-leader-member-id", types.ID(s.Lead()).String()),
)
} else {
plog.Printf("skipped leadership transfer for stopping non-leader member")
}
return nil
}
if !s.isMultiNode() {
if lg := s.getLogger(); lg != nil {
lg.Info(
"skipped leadership transfer; it's a single-node cluster",
zap.String("local-member-id", s.ID().String()),
zap.String("current-leader-member-id", types.ID(s.Lead()).String()),
)
} else {
plog.Printf("skipped leadership transfer for single member cluster")
}
return nil
}
transferee, ok := longestConnected(s.r.transport, s.cluster.MemberIDs())
if !ok {
return ErrUnhealthy
}
tm := s.Cfg.ReqTimeout()
ctx, cancel := context.WithTimeout(s.ctx, tm)
err := s.MoveLeader(ctx, s.Lead(), uint64(transferee))
cancel()
return err
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/fileutil/dir_windows.go#L25-L31
|
func OpenDir(path string) (*os.File, error) {
fd, err := openDir(path)
if err != nil {
return nil, err
}
return os.NewFile(uintptr(fd), path), nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/serviceenv/service_env.go#L166-L171
|
func (env *ServiceEnv) GetPachClient(ctx context.Context) *client.APIClient {
if err := env.pachEg.Wait(); err != nil {
panic(err) // If env can't connect, there's no sensible way to recover
}
return env.pachClient.WithCtx(ctx)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domstorage/domstorage.go#L52-L54
|
func (p *DisableParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandDisable, nil, nil)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_volumes.go#L441-L634
|
func storagePoolVolumeTypePost(d *Daemon, r *http.Request, volumeTypeName string) Response {
// Get the name of the storage volume.
var volumeName string
fields := strings.Split(mux.Vars(r)["name"], "/")
if len(fields) == 3 && fields[1] == "snapshots" {
// Handle volume snapshots
volumeName = fmt.Sprintf("%s%s%s", fields[0], shared.SnapshotDelimiter, fields[2])
} else if len(fields) > 1 {
volumeName = fmt.Sprintf("%s%s%s", fields[0], shared.SnapshotDelimiter, fields[1])
} else if len(fields) > 0 {
// Handle volume
volumeName = fields[0]
} else {
return BadRequest(fmt.Errorf("invalid storage volume %s", mux.Vars(r)["name"]))
}
// Get the name of the storage pool the volume is supposed to be
// attached to.
poolName := mux.Vars(r)["pool"]
req := api.StorageVolumePost{}
// Parse the request.
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
return BadRequest(err)
}
// Sanity checks.
if req.Name == "" {
return BadRequest(fmt.Errorf("No name provided"))
}
if strings.Contains(req.Name, "/") {
return BadRequest(fmt.Errorf("Storage volume names may not contain slashes"))
}
// We currently only allow to create storage volumes of type
// storagePoolVolumeTypeCustom. So check, that nothing else was
// requested.
if volumeTypeName != storagePoolVolumeTypeNameCustom {
return BadRequest(fmt.Errorf("Renaming storage volumes of type %s is not allowed", volumeTypeName))
}
// Retrieve ID of the storage pool (and check if the storage pool
// exists).
var poolID int64
if req.Pool != "" {
poolID, err = d.cluster.StoragePoolGetID(req.Pool)
} else {
poolID, err = d.cluster.StoragePoolGetID(poolName)
}
if err != nil {
return SmartError(err)
}
// We need to restore the body of the request since it has already been
// read, and if we forwarded it now no body would be written out.
buf := bytes.Buffer{}
err = json.NewEncoder(&buf).Encode(req)
if err != nil {
return SmartError(err)
}
r.Body = shared.BytesReadCloser{Buf: &buf}
response := ForwardedResponseIfTargetIsRemote(d, r)
if response != nil {
return response
}
// Convert the volume type name to our internal integer representation.
volumeType, err := storagePoolVolumeTypeNameToType(volumeTypeName)
if err != nil {
return BadRequest(err)
}
response = ForwardedResponseIfVolumeIsRemote(d, r, poolID, volumeName, volumeType)
if response != nil {
return response
}
s, err := storagePoolVolumeInit(d.State(), "default", poolName, volumeName, storagePoolVolumeTypeCustom)
if err != nil {
return InternalError(err)
}
// This is a migration request so send back requested secrets
if req.Migration {
ws, err := NewStorageMigrationSource(s, req.VolumeOnly)
if err != nil {
return InternalError(err)
}
resources := map[string][]string{}
resources["storage_volumes"] = []string{fmt.Sprintf("%s/volumes/custom/%s", poolName, volumeName)}
if req.Target != nil {
// Push mode
err := ws.ConnectStorageTarget(*req.Target)
if err != nil {
return InternalError(err)
}
op, err := operationCreate(d.cluster, "", operationClassTask, db.OperationVolumeMigrate, resources, nil, ws.DoStorage, nil, nil)
if err != nil {
return InternalError(err)
}
return OperationResponse(op)
}
// Pull mode
op, err := operationCreate(d.cluster, "", operationClassWebsocket, db.OperationVolumeMigrate, resources, ws.Metadata(), ws.DoStorage, nil, ws.Connect)
if err != nil {
return InternalError(err)
}
return OperationResponse(op)
}
// Check that the name isn't already in use.
_, err = d.cluster.StoragePoolNodeVolumeGetTypeID(req.Name,
storagePoolVolumeTypeCustom, poolID)
if err != db.ErrNoSuchObject {
if err != nil {
return InternalError(err)
}
return Conflict(fmt.Errorf("Name '%s' already in use", req.Name))
}
doWork := func() error {
ctsUsingVolume, err := storagePoolVolumeUsedByRunningContainersWithProfilesGet(d.State(), poolName, volumeName, storagePoolVolumeTypeNameCustom, true)
if err != nil {
return err
}
if len(ctsUsingVolume) > 0 {
return fmt.Errorf("Volume is still in use by running containers")
}
err = storagePoolVolumeUpdateUsers(d, poolName, volumeName, req.Pool, req.Name)
if err != nil {
return err
}
if req.Pool == "" || req.Pool == poolName {
err := s.StoragePoolVolumeRename(req.Name)
if err != nil {
storagePoolVolumeUpdateUsers(d, req.Pool, req.Name, poolName, volumeName)
return err
}
} else {
moveReq := api.StorageVolumesPost{}
moveReq.Name = req.Name
moveReq.Type = "custom"
moveReq.Source.Name = volumeName
moveReq.Source.Pool = poolName
err := storagePoolVolumeCreateInternal(d.State(), req.Pool, &moveReq)
if err != nil {
storagePoolVolumeUpdateUsers(d, req.Pool, req.Name, poolName, volumeName)
return err
}
err = s.StoragePoolVolumeDelete()
if err != nil {
return err
}
}
return nil
}
if req.Pool == "" {
err = doWork()
if err != nil {
return SmartError(err)
}
return SyncResponseLocation(true, nil, fmt.Sprintf("/%s/storage-pools/%s/volumes/%s", version.APIVersion, poolName, storagePoolVolumeAPIEndpointCustom))
}
run := func(op *operation) error {
return doWork()
}
op, err := operationCreate(d.cluster, "", operationClassTask, db.OperationVolumeMove, nil, nil, run, nil, nil)
if err != nil {
return InternalError(err)
}
return OperationResponse(op)
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/raft.go#L475-L485
|
func (r *Raft) configurationChangeChIfStable() chan *configurationChangeFuture {
// Have to wait until:
// 1. The latest configuration is committed, and
// 2. This leader has committed some entry (the noop) in this term
// https://groups.google.com/forum/#!msg/raft-dev/t4xj6dJTP6E/d2D9LrWRza8J
if r.configurations.latestIndex == r.configurations.committedIndex &&
r.getCommitIndex() >= r.leaderState.commitment.startIndex {
return r.configurationChangeCh
}
return nil
}
|
https://github.com/codemodus/kace/blob/e3ecf78ee2a5e58652cb2be34d3159ad9c89acf8/kace.go#L69-L87
|
func New(initialisms map[string]bool) (*Kace, error) {
ci := initialisms
if ci == nil {
ci = map[string]bool{}
}
ci = sanitizeCI(ci)
t, err := ktrie.NewKTrie(ci)
if err != nil {
return nil, fmt.Errorf("kace: cannot create trie: %s", err)
}
k := &Kace{
t: t,
}
return k, nil
}
|
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/fakes/fake.go#L186-L191
|
func (s *MockMongo) Collection() pezdispenser.Persistence {
return &MockPersistence{
Err: s.Err,
Result: s.Result,
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.