_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/snapshot.go#L103-L117
|
func (r *Raft) shouldSnapshot() bool {
// Check the last snapshot index
lastSnap, _ := r.getLastSnapshot()
// Check the last log index
lastIdx, err := r.logs.LastIndex()
if err != nil {
r.logger.Error(fmt.Sprintf("Failed to get last log index: %v", err))
return false
}
// Compare the delta to the threshold
delta := lastIdx - lastSnap
return delta >= r.conf.SnapshotThreshold
}
|
https://github.com/brankas/sentinel/blob/0ff081867c31a45cb71f5976ea6144fd06a557b5/opts.go#L52-L65
|
func Shutdown(shutdownFuncs ...interface{}) Option {
return func(s *Sentinel) error {
s.Lock()
defer s.Unlock()
if s.started {
return ErrAlreadyStarted
}
var err error
s.shutdownFuncs, err = convertAndAppendContextFuncs(s.shutdownFuncs, shutdownFuncs...)
return err
}
}
|
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vm.go#L226-L247
|
func (v *VM) IsRunning() (bool, error) {
var err C.VixError = C.VIX_OK
running := C.VIX_PROPERTY_NONE
err = C.get_property(v.handle,
C.VIX_PROPERTY_VM_IS_RUNNING,
unsafe.Pointer(&running))
if C.VIX_OK != err {
return false, &Error{
Operation: "vm.IsRunning",
Code: int(err & 0xFFFF),
Text: C.GoString(C.Vix_GetErrorText(err, nil)),
}
}
if running == 0 {
return false, nil
}
return true, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/contrib/recipes/double_barrier.go#L46-L75
|
func (b *DoubleBarrier) Enter() error {
client := b.s.Client()
ek, err := newUniqueEphemeralKey(b.s, b.key+"/waiters")
if err != nil {
return err
}
b.myKey = ek
resp, err := client.Get(b.ctx, b.key+"/waiters", clientv3.WithPrefix())
if err != nil {
return err
}
if len(resp.Kvs) > b.count {
return ErrTooManyClients
}
if len(resp.Kvs) == b.count {
// unblock waiters
_, err = client.Put(b.ctx, b.key+"/ready", "")
return err
}
_, err = WaitEvents(
client,
b.key+"/ready",
ek.Revision(),
[]mvccpb.Event_EventType{mvccpb.PUT})
return err
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/service.go#L137-L174
|
func serviceUpdate(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
d := service.Service{
Username: InputValue(r, "username"),
Endpoint: map[string]string{"production": InputValue(r, "endpoint")},
Password: InputValue(r, "password"),
Name: r.URL.Query().Get(":name"),
}
team := InputValue(r, "team")
s, err := getService(d.Name)
if err != nil {
return err
}
allowed := permission.Check(t, permission.PermServiceUpdate,
contextsForServiceProvision(&s)...,
)
if !allowed {
return permission.ErrUnauthorized
}
delete(r.Form, "password")
evt, err := event.New(&event.Opts{
Target: serviceTarget(s.Name),
Kind: permission.PermServiceUpdate,
Owner: t,
CustomData: event.FormToCustomData(InputFields(r)),
Allowed: event.Allowed(permission.PermServiceReadEvents, contextsForServiceProvision(&s)...),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
s.Endpoint = d.Endpoint
s.Password = d.Password
s.Username = d.Username
if team != "" {
s.OwnerTeams = []string{team}
}
return service.Update(s)
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L857-L862
|
func (g *Glg) WarnFunc(f func() string) error {
if g.isModeEnable(WARN) {
return g.out(WARN, "%s", f())
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L3375-L3379
|
func (v GetNodeForLocationReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom38(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/routes/routes_client.go#L152-L175
|
func (a *Client) PostAppsAppRoutes(params *PostAppsAppRoutesParams) (*PostAppsAppRoutesOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewPostAppsAppRoutesParams()
}
result, err := a.transport.Submit(&runtime.ClientOperation{
ID: "PostAppsAppRoutes",
Method: "POST",
PathPattern: "/apps/{app}/routes",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"http", "https"},
Params: params,
Reader: &PostAppsAppRoutesReader{formats: a.formats},
Context: params.Context,
Client: params.HTTPClient,
})
if err != nil {
return nil, err
}
return result.(*PostAppsAppRoutesOK), nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/worker/api_server.go#L1019-L1046
|
func HashDatum15(pipelineInfo *pps.PipelineInfo, data []*Input) (string, error) {
hash := sha256.New()
for _, datum := range data {
hash.Write([]byte(datum.Name))
hash.Write([]byte(datum.FileInfo.File.Path))
hash.Write(datum.FileInfo.Hash)
}
// We set env to nil because if env contains more than one elements,
// since it's a map, the output of Marshal() can be non-deterministic.
env := pipelineInfo.Transform.Env
pipelineInfo.Transform.Env = nil
defer func() {
pipelineInfo.Transform.Env = env
}()
bytes, err := pipelineInfo.Transform.Marshal()
if err != nil {
return "", err
}
hash.Write(bytes)
hash.Write([]byte(pipelineInfo.Pipeline.Name))
hash.Write([]byte(pipelineInfo.ID))
hash.Write([]byte(strconv.Itoa(int(pipelineInfo.Version))))
// Note in 1.5.0 this function was called HashPipelineID, it's now called
// HashPipelineName but it has the same implementation.
return client.DatumTagPrefix(pipelineInfo.ID) + hex.EncodeToString(hash.Sum(nil)), nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/payment.go#L101-L121
|
func (m NativeAmount) MutatePayment(o interface{}) (err error) {
switch o := o.(type) {
default:
err = errors.New("Unexpected operation type")
case *xdr.PaymentOp:
o.Amount, err = amount.Parse(m.Amount)
if err != nil {
return
}
o.Asset, err = xdr.NewAsset(xdr.AssetTypeAssetTypeNative, nil)
case *xdr.PathPaymentOp:
o.DestAmount, err = amount.Parse(m.Amount)
if err != nil {
return
}
o.DestAsset, err = xdr.NewAsset(xdr.AssetTypeAssetTypeNative, nil)
}
return
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/fetcher/client.go#L75-L96
|
func (client *Client) getGitHubClient() (*github.Client, error) {
if client.githubClient != nil {
return client.githubClient, nil
}
token := client.Token
if len(token) == 0 && len(client.TokenFile) != 0 {
data, err := ioutil.ReadFile(client.TokenFile)
if err != nil {
return nil, err
}
token = strings.TrimSpace(string(data))
}
if len(token) > 0 {
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
tc := oauth2.NewClient(oauth2.NoContext, ts)
client.githubClient = github.NewClient(tc)
} else {
client.githubClient = github.NewClient(nil)
}
return client.githubClient, nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/ppsutil/util.go#L51-L53
|
func PipelineRepo(pipeline *ppsclient.Pipeline) *pfs.Repo {
return &pfs.Repo{Name: pipeline.Name}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/deploy/assets/assets.go#L787-L812
|
func EtcdStorageClass(opts *AssetOpts, backend backend) (interface{}, error) {
sc := map[string]interface{}{
"apiVersion": "storage.k8s.io/v1beta1",
"kind": "StorageClass",
"metadata": map[string]interface{}{
"name": defaultEtcdStorageClassName,
"labels": labels(etcdName),
"namespace": opts.Namespace,
},
}
switch backend {
case googleBackend:
sc["provisioner"] = "kubernetes.io/gce-pd"
sc["parameters"] = map[string]string{
"type": "pd-ssd",
}
case amazonBackend:
sc["provisioner"] = "kubernetes.io/aws-ebs"
sc["parameters"] = map[string]string{
"type": "gp2",
}
default:
return nil, nil
}
return sc, nil
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/models.go#L219-L247
|
func (u *User) Validate() error {
// hash password if available
err := u.HashPassword()
if err != nil {
return err
}
// check id
if !u.ID().Valid() {
return fire.E("invalid id")
}
// check name
if u.Name == "" {
return fire.E("name not set")
}
// check email
if u.Email == "" || !govalidator.IsEmail(u.Email) {
return fire.E("invalid email")
}
// check password hash
if len(u.PasswordHash) == 0 {
return fire.E("password hash not set")
}
return nil
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/file_snapshot.go#L482-L509
|
func (s *FileSnapshotSink) writeMeta() error {
// Open the meta file
metaPath := filepath.Join(s.dir, metaFilePath)
fh, err := os.Create(metaPath)
if err != nil {
return err
}
defer fh.Close()
// Buffer the file IO
buffered := bufio.NewWriter(fh)
// Write out as JSON
enc := json.NewEncoder(buffered)
if err := enc.Encode(&s.meta); err != nil {
return err
}
if err = buffered.Flush(); err != nil {
return err
}
if err = fh.Sync(); err != nil {
return err
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L6421-L6425
|
func (v *EventDomContentEventFired) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage68(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/indexeddb.go#L30-L36
|
func ClearObjectStore(securityOrigin string, databaseName string, objectStoreName string) *ClearObjectStoreParams {
return &ClearObjectStoreParams{
SecurityOrigin: securityOrigin,
DatabaseName: databaseName,
ObjectStoreName: objectStoreName,
}
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/transaction.go#L37-L49
|
func (b *TransactionBuilder) Mutate(muts ...TransactionMutator) {
if b.TX == nil {
b.TX = &xdr.Transaction{}
}
for _, m := range muts {
err := m.MutateTransaction(b)
if err != nil {
b.Err = err
return
}
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L1568-L1572
|
func (v EventReceivedMessageFromTarget) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoTarget17(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/bitgoin/lyra2rev2/blob/bae9ad2043bb55facb14c4918e909f88a7d3ed84/bmw.go#L131-L152
|
func bmw256(input []byte) []byte {
b := new()
buf := make([]byte, 64)
copy(buf, input)
buf[len(input)] = 0x80
bitLen := uint64(len(input)) << 3
binary.LittleEndian.PutUint64(buf[56:], bitLen)
for i := 0; i < 16; i++ {
b.m[i] = binary.LittleEndian.Uint32(buf[i*4:])
}
b.compress(b.m)
b.h, b.h2 = b.h2, b.h
copy(b.h, final)
b.compress(b.h2)
output := make([]byte, 32)
outlen := len(output) >> 2
for i := 0; i < outlen; i++ {
j := 16 - outlen + i
binary.LittleEndian.PutUint32(output[4*i:], b.h[j])
}
return output
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcauth/tcauth.go#L539-L546
|
func (auth *Auth) AzureTables_SignedURL(account, continuationToken string, duration time.Duration) (*url.URL, error) {
v := url.Values{}
if continuationToken != "" {
v.Add("continuationToken", continuationToken)
}
cd := tcclient.Client(*auth)
return (&cd).SignedURL("/azure/"+url.QueryEscape(account)+"/tables", v, duration)
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/directory/directory_transport.go#L40-L54
|
func (t dirTransport) ValidatePolicyConfigurationScope(scope string) error {
if !strings.HasPrefix(scope, "/") {
return errors.Errorf("Invalid scope %s: Must be an absolute path", scope)
}
// Refuse also "/", otherwise "/" and "" would have the same semantics,
// and "" could be unexpectedly shadowed by the "/" entry.
if scope == "/" {
return errors.New(`Invalid scope "/": Use the generic default scope ""`)
}
cleaned := filepath.Clean(scope)
if cleaned != scope {
return errors.Errorf(`Invalid scope %s: Uses non-canonical format, perhaps try %s`, scope, cleaned)
}
return nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/workload/workload.go#L217-L223
|
func RandString(r *rand.Rand, n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letters[r.Intn(len(letters))]
}
return string(b)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/ppsutil/util.go#L127-L136
|
func getNumNodes(kubeClient *kube.Clientset) (int, error) {
nodeList, err := kubeClient.CoreV1().Nodes().List(metav1.ListOptions{})
if err != nil {
return 0, fmt.Errorf("unable to retrieve node list from k8s to determine parallelism: %v", err)
}
if len(nodeList.Items) == 0 {
return 0, fmt.Errorf("pachyderm.pps.jobserver: no k8s nodes found")
}
return len(nodeList.Items), nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/mason/client.go#L37-L42
|
func NewClient(boskosClient boskosClient) *Client {
return &Client{
basic: boskosClient,
resources: map[string]common.Resource{},
}
}
|
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/objutil/duration.go#L112-L125
|
func fmtInt(buf []byte, v uint64) int {
w := len(buf)
if v == 0 {
w--
buf[w] = '0'
} else {
for v > 0 {
w--
buf[w] = byte(v%10) + '0'
v /= 10
}
}
return w
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L576-L585
|
func (p *GlobalLexicalScopeNamesParams) Do(ctx context.Context) (names []string, err error) {
// execute
var res GlobalLexicalScopeNamesReturns
err = cdp.Execute(ctx, CommandGlobalLexicalScopeNames, p, &res)
if err != nil {
return nil, err
}
return res.Names, nil
}
|
https://github.com/anmitsu/go-shlex/blob/648efa622239a2f6ff949fed78ee37b48d499ba4/shlex.go#L79-L81
|
func Split(s string, posix bool) ([]string, error) {
return NewLexerString(s, posix, true).Split()
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/manifest/docker_schema1.go#L102-L116
|
func (m *Schema1) initialize() error {
if len(m.FSLayers) != len(m.History) {
return errors.New("length of history not equal to number of layers")
}
if len(m.FSLayers) == 0 {
return errors.New("no FSLayers in manifest")
}
m.ExtractedV1Compatibility = make([]Schema1V1Compatibility, len(m.History))
for i, h := range m.History {
if err := json.Unmarshal([]byte(h.V1Compatibility), &m.ExtractedV1Compatibility[i]); err != nil {
return errors.Wrapf(err, "Error parsing v2s1 history entry %d", i)
}
}
return nil
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/pseudorandom/random.go#L21-L27
|
func New(seed int64) random.Interface {
return &TTNRandom{
Interface: &random.TTNRandom{
Source: rand.New(rand.NewSource(seed)),
},
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/flags/strings.go#L50-L52
|
func StringsFromFlag(fs *flag.FlagSet, flagName string) []string {
return []string(*fs.Lookup(flagName).Value.(*StringsValue))
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/tackle/main.go#L93-L99
|
func projects(max int) ([]string, error) {
out, err := output("gcloud", "projects", "list", fmt.Sprintf("--limit=%d", max), "--format=value(project_id)")
if err != nil {
return nil, err
}
return strings.Split(out, "\n"), nil
}
|
https://github.com/jpillora/overseer/blob/ce9055846616cf7e1ab91bb8a0bcbb1d7fa3d11a/fetcher/fetcher_http.go#L29-L42
|
func (h *HTTP) Init() error {
//apply defaults
if h.URL == "" {
return fmt.Errorf("URL required")
}
h.lasts = map[string]string{}
if h.Interval == 0 {
h.Interval = 5 * time.Minute
}
if h.CheckHeaders == nil {
h.CheckHeaders = defaultHTTPCheckHeaders
}
return nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/metrics/segment.go#L50-L57
|
func identifyUser(client *analytics.Client, userID string) {
err := client.Identify(&analytics.Identify{
UserId: userID,
})
if err != nil {
log.Errorf("error reporting user identity to Segment: %s", err.Error())
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L4269-L4273
|
func (v *GetContentQuadsReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom48(&r, v)
return r.Error()
}
|
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/storage/storagemock/storage.go#L163-L183
|
func (_m *Storage) Start(_a0 context.Context, _a1 string, _a2 string, _a3 string, _a4 string, _a5 map[string]string) (*mnemosynerpc.Session, error) {
ret := _m.Called(_a0, _a1, _a2, _a3, _a4, _a5)
var r0 *mnemosynerpc.Session
if rf, ok := ret.Get(0).(func(context.Context, string, string, string, string, map[string]string) *mnemosynerpc.Session); ok {
r0 = rf(_a0, _a1, _a2, _a3, _a4, _a5)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*mnemosynerpc.Session)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(context.Context, string, string, string, string, map[string]string) 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/db/db.go#L328-L332
|
func (c *Cluster) ExitExclusive(f func(*ClusterTx) error) error {
logger.Debug("Releasing exclusive lock on cluster db")
defer c.mu.Unlock()
return c.transaction(f)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/robots/issue-creator/sources/triage-filer.go#L347-L361
|
func (c *Cluster) topJobsFailed(count int) []*Job {
slice := make([]*Job, len(c.jobs))
i := 0
for jobName, builds := range c.jobs {
slice[i] = &Job{Name: jobName, Builds: builds}
i++
}
less := func(i, j int) bool { return len(slice[i].Builds) > len(slice[j].Builds) }
sort.SliceStable(slice, less)
if len(slice) < count {
count = len(slice)
}
return slice[0:count]
}
|
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/security/controller.go#L84-L115
|
func (c *OAuth2Controller) Refresh(w http.ResponseWriter, r *http.Request) {
grantType := r.URL.Query().Get("grant_type")
refreshToken := r.URL.Query().Get("refresh_token")
if strings.Compare(grantType, "refresh_token") != 0 {
http.Error(w, errors.New("Parameter grant_type is required").Error(), http.StatusBadRequest)
return
}
if strings.Compare(refreshToken, "") == 0 {
http.Error(w, errors.New("Parameter refreshToken is required").Error(), http.StatusBadRequest)
return
}
token, err := jwt.Parse(refreshToken, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return []byte(c.cnf.Jwt.Key), nil
})
if err == nil && token.Valid {
token := jwt.New(jwt.GetSigningMethod("HS256"))
claims := token.Claims.(jwt.MapClaims)
claims["exp"] = time.Now().Add(time.Hour * 1).Unix()
tokenString, _ := token.SignedString([]byte(c.cnf.Jwt.Key))
data := map[string]string{
"access_token": tokenString,
"token_type": "bearer",
"expires_in": "3600",
}
js, _ := json.Marshal(data)
w.Write(js)
}
}
|
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/rawoption.go#L192-L197
|
func (o *ListRawTypeOption) Set(value string) error {
val := RawTypeOption{}
val.Set(value)
*o = append(*o, val)
return nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/goav2gen/definition.go#L52-L102
|
func (a *APIAnalyzer) guessType(ec EvalCtx, d *Definition, refID string) string {
// First get the type name and and view from the swagger reference definition
// name -- are a few cases where that's the only place that has the view
if t, ok := a.TypeOverrides[refID]; ok {
return t
}
var name, view string
if strings.Contains(refID, "RequestBody") {
bits := strings.Split(refID, "RequestBody")
name = bits[0]
if len(bits) > 1 {
view = strings.ToLower(bits[1])
}
} else if strings.Contains(refID, "ResponseBody") {
bits := strings.Split(refID, "ResponseBody")
name = bits[0]
if len(bits) > 1 {
view = strings.ToLower(bits[1])
}
} else {
name = refID
}
// Now try and get it from the media type -- this is preferred if its set.
if mt := mediaType(d.Title); mt != "" {
if strings.Contains(mt, "application") {
bits := strings.Split(mt, ".")
name := bits[len(bits)-1]
attrs := mediaTypeAttrs(d.Title)
if attrs["type"] != "" {
name += "_" + attrs["type"]
}
if attrs["view"] != "" && attrs["view"] != "default" {
name += "_" + attrs["view"]
} else if view != "" {
name += "_" + view
}
dbg("DEBUG media type refID:%#v title:%#v name:%#v view:%#v -> type:%#v\n", refID, d.Title, name, view, name)
return toTypeName(name)
} else if strings.Contains(mt, "text/") {
return "string"
} else {
fail("Don't know how to handle media type %s", mt)
}
}
if view != "" {
return name + "_" + view
}
return name
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/catalog.go#L15-L25
|
func NewCatalog(models ...Model) *Catalog {
// create catalog
c := &Catalog{
models: make(map[string]Model),
}
// add models
c.Add(models...)
return c
}
|
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/template.go#L176-L189
|
func NewTemplateMsg(timestamp time.Time, level LogLevel, m map[string]interface{}, msg string) *TemplateMsg {
msgAttrs := m
if msgAttrs == nil {
msgAttrs = make(map[string]interface{})
}
tplMsg := &TemplateMsg{
Timestamp: timestamp,
Message: msg,
Level: level,
LevelName: level.String(),
Attrs: msgAttrs,
}
return tplMsg
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/directory/directory_transport.go#L155-L161
|
func (ref dirReference) NewImageDestination(ctx context.Context, sys *types.SystemContext) (types.ImageDestination, error) {
compress := false
if sys != nil {
compress = sys.DirForceCompress
}
return newImageDestination(ref, compress)
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/mechanism_openpgp.go#L26-L51
|
func newGPGSigningMechanismInDirectory(optionalDir string) (SigningMechanism, error) {
m := &openpgpSigningMechanism{
keyring: openpgp.EntityList{},
}
gpgHome := optionalDir
if gpgHome == "" {
gpgHome = os.Getenv("GNUPGHOME")
if gpgHome == "" {
gpgHome = path.Join(homedir.Get(), ".gnupg")
}
}
pubring, err := ioutil.ReadFile(path.Join(gpgHome, "pubring.gpg"))
if err != nil {
if !os.IsNotExist(err) {
return nil, err
}
} else {
_, err := m.importKeysFromBytes(pubring)
if err != nil {
return nil, err
}
}
return m, nil
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/worker/simple.go#L23-L37
|
func NewSimpleWithContext(ctx context.Context) *Simple {
ctx, cancel := context.WithCancel(ctx)
l := logrus.New()
l.Level = logrus.InfoLevel
l.Formatter = &logrus.TextFormatter{}
return &Simple{
Logger: l,
ctx: ctx,
cancel: cancel,
handlers: map[string]Handler{},
moot: &sync.Mutex{},
}
}
|
https://github.com/mailgun/iptools/blob/ba8d5743f6788db9906c07c292a033f194849563/ip.go#L32-L55
|
func GetHostIPs() ([]net.IP, error) {
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
var ips []net.IP
for _, iface := range ifaces {
if strings.HasPrefix(iface.Name, "docker") {
continue
}
addrs, err := iface.Addrs()
if err != nil {
continue
}
for _, addr := range addrs {
if ipnet, ok := addr.(*net.IPNet); ok {
ips = append(ips, ipnet.IP)
}
}
}
return ips, nil
}
|
https://github.com/geoffgarside/ber/blob/27a1aff36ce64dbe5d93c08cc5f161983134ddc5/ber.go#L275-L284
|
func parsePrintableString(bytes []byte) (ret string, err error) {
for _, b := range bytes {
if !isPrintable(b) {
err = asn1.SyntaxError{Msg: "PrintableString contains invalid character"}
return
}
}
ret = string(bytes)
return
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/dominator.go#L179-L187
|
func (d *ltDom) findVertexByName(n vName) (*Root, Object) {
if n == 0 {
return nil, 0
}
if int(n) < len(d.p.rootIdx)+1 {
return d.p.rootIdx[n-1], 0
}
return nil, d.objs[int(n)-len(d.p.rootIdx)-1]
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cast/cast.go#L109-L111
|
func (p *StartTabMirroringParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandStartTabMirroring, p, nil)
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/db.go#L1192-L1256
|
func (db *DB) Flatten(workers int) error {
db.stopCompactions()
defer db.startCompactions()
compactAway := func(cp compactionPriority) error {
db.opt.Infof("Attempting to compact with %+v\n", cp)
errCh := make(chan error, 1)
for i := 0; i < workers; i++ {
go func() {
errCh <- db.lc.doCompact(cp)
}()
}
var success int
var rerr error
for i := 0; i < workers; i++ {
err := <-errCh
if err != nil {
rerr = err
db.opt.Warningf("While running doCompact with %+v. Error: %v\n", cp, err)
} else {
success++
}
}
if success == 0 {
return rerr
}
// We could do at least one successful compaction. So, we'll consider this a success.
db.opt.Infof("%d compactor(s) succeeded. One or more tables from level %d compacted.\n",
success, cp.level)
return nil
}
hbytes := func(sz int64) string {
return humanize.Bytes(uint64(sz))
}
for {
db.opt.Infof("\n")
var levels []int
for i, l := range db.lc.levels {
sz := l.getTotalSize()
db.opt.Infof("Level: %d. %8s Size. %8s Max.\n",
i, hbytes(l.getTotalSize()), hbytes(l.maxTotalSize))
if sz > 0 {
levels = append(levels, i)
}
}
if len(levels) <= 1 {
prios := db.lc.pickCompactLevels()
if len(prios) == 0 || prios[0].score <= 1.0 {
db.opt.Infof("All tables consolidated into one level. Flattening done.\n")
return nil
}
if err := compactAway(prios[0]); err != nil {
return err
}
continue
}
// Create an artificial compaction priority, to ensure that we compact the level.
cp := compactionPriority{level: levels[0], score: 1.71}
if err := compactAway(cp); err != nil {
return err
}
}
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/matchers/page_matchers.go#L22-L24
|
func HavePopupText(text string) types.GomegaMatcher {
return &internal.ValueMatcher{Method: "PopupText", Property: "popup text", Expected: text}
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/context.go#L85-L87
|
func NewContext(timeout time.Duration) (context.Context, context.CancelFunc) {
return NewContextBuilder(timeout).Build()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/easyjson.go#L679-L683
|
func (v SamplingHeapProfileNode) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoHeapprofiler7(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssc/codegen_client.go#L1010-L1064
|
func (loc *NotificationRuleLocator) Create(minSeverity string, source string, target string, options rsapi.APIParams) (*NotificationRuleLocator, error) {
var res *NotificationRuleLocator
if minSeverity == "" {
return res, fmt.Errorf("minSeverity is required")
}
if source == "" {
return res, fmt.Errorf("source is required")
}
if target == "" {
return res, fmt.Errorf("target is required")
}
var params rsapi.APIParams
params = rsapi.APIParams{}
var filterOpt = options["filter"]
if filterOpt != nil {
params["filter[]"] = filterOpt
}
var p rsapi.APIParams
p = rsapi.APIParams{
"min_severity": minSeverity,
"source": source,
"target": target,
}
var categoryOpt = options["category"]
if categoryOpt != nil {
p["category"] = categoryOpt
}
uri, err := loc.ActionPath("NotificationRule", "create")
if err != nil {
return res, err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return res, err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return res, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return res, fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
location := resp.Header.Get("Location")
if len(location) == 0 {
return res, fmt.Errorf("Missing location header in response")
} else {
return &NotificationRuleLocator{Href(location), loc.api}, nil
}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/cert/logging_conn.go#L150-L166
|
func (l *TestListener) Dial(context.Context, string, string) (net.Conn, error) {
l.connMu.Lock()
defer l.connMu.Unlock()
if l.conn != nil {
return nil, errors.New("Dial() has already been called on this TestListener")
}
// Initialize logging pipe
p := newLoggingPipe()
l.conn = p.serverConn()
// send serverConn to Accept() and close l.connCh (so future callers to
// Accept() get nothing)
l.connCh <- p.serverConn()
close(l.connCh)
return p.clientConn(), nil
}
|
https://github.com/abronan/leadership/blob/76df1b7fa3841b453d70d7183e8c02a87538c0ee/follower.go#L33-L37
|
func (f *Follower) Leader() string {
f.lock.Lock()
defer f.lock.Unlock()
return f.leader
}
|
https://github.com/auth0/go-jwt-middleware/blob/5493cabe49f7bfa6e2ec444a09d334d90cd4e2bd/jwtmiddleware.go#L64-L88
|
func New(options ...Options) *JWTMiddleware {
var opts Options
if len(options) == 0 {
opts = Options{}
} else {
opts = options[0]
}
if opts.UserProperty == "" {
opts.UserProperty = "user"
}
if opts.ErrorHandler == nil {
opts.ErrorHandler = OnError
}
if opts.Extractor == nil {
opts.Extractor = FromAuthHeader
}
return &JWTMiddleware{
Options: opts,
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/types.go#L104-L106
|
func (t VersionStatus) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/deviceorientation/deviceorientation.go#L46-L52
|
func SetDeviceOrientationOverride(alpha float64, beta float64, gamma float64) *SetDeviceOrientationOverrideParams {
return &SetDeviceOrientationOverrideParams{
Alpha: alpha,
Beta: beta,
Gamma: gamma,
}
}
|
https://github.com/blacklabeldata/namedtuple/blob/c341f1db44f30b8164294aa8605ede42be604aba/types.go#L31-L36
|
func New(namespace string, name string) (t TupleType) {
hash := syncHash.Hash([]byte(name))
ns_hash := syncHash.Hash([]byte(namespace))
t = TupleType{namespace, name, ns_hash, hash, make([][]Field, 0), make(map[string]int)}
return
}
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gstruct/errors/nested_types.go#L34-L52
|
func Nest(path string, err error) error {
if ag, ok := err.(AggregateError); ok {
var errs AggregateError
for _, e := range ag {
errs = append(errs, Nest(path, e))
}
return errs
}
if ne, ok := err.(*NestedError); ok {
return &NestedError{
Path: path + ne.Path,
Err: ne.Err,
}
}
return &NestedError{
Path: path,
Err: err,
}
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L1206-L1208
|
func (api *API) BackupLocator(href string) *BackupLocator {
return &BackupLocator{Href(href), api}
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/tracer.go#L72-L77
|
func NewTracer(root opentracing.Span) *Tracer {
return &Tracer{
root: root,
spans: make([]opentracing.Span, 0, 32),
}
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/connection.go#L584-L590
|
func (c *Connection) withStateLock(f func() error) error {
c.stateMut.Lock()
err := f()
c.stateMut.Unlock()
return err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L130-L135
|
func EvaluateOnCallFrame(callFrameID CallFrameID, expression string) *EvaluateOnCallFrameParams {
return &EvaluateOnCallFrameParams{
CallFrameID: callFrameID,
Expression: expression,
}
}
|
https://github.com/gopistolet/gospf/blob/a58dd1fcbf509d558a6809c54defbce6872c40c5/spf.go#L483-L519
|
func GetRanges(ips []string, ip4_cidr string, ip6_cidr string) ([]net.IPNet, error) {
net_out := make([]net.IPNet, 0)
for _, ip := range ips {
cidr := ""
if strings.Contains(ip, ":") {
// IPv6
cidr = ip6_cidr
if cidr == "" {
cidr = "128"
}
if c, err := strconv.ParseInt(cidr, 10, 16); err != nil || c < 0 || c > 128 {
return nil, &PermError{"Invalid IPv6 CIDR length: " + cidr}
}
} else {
// IPv4
cidr = ip4_cidr
if cidr == "" {
cidr = "32"
}
if c, err := strconv.ParseInt(cidr, 10, 16); err != nil || c < 0 || c > 32 {
return nil, &PermError{"Invalid IPv4 CIDR length: " + cidr}
}
}
ip += "/" + cidr
_, ipnet, err := net.ParseCIDR(ip)
if err != nil {
return nil, err
}
net_out = append(net_out, *ipnet)
}
return net_out, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L2901-L2905
|
func (v *GetSearchResultsReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom32(&r, v)
return r.Error()
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/relay.go#L135-L162
|
func (r *relayItems) Entomb(id uint32, deleteAfter time.Duration) (relayItem, bool) {
r.Lock()
if r.tombs > _maxRelayTombs {
r.Unlock()
r.logger.WithFields(LogField{"id", id}).Warn("Too many tombstones, deleting relay item immediately.")
return r.Delete(id)
}
item, ok := r.items[id]
if !ok {
r.Unlock()
r.logger.WithFields(LogField{"id", id}).Warn("Can't find relay item to entomb.")
return item, false
}
if item.tomb {
r.Unlock()
r.logger.WithFields(LogField{"id", id}).Warn("Re-entombing a tombstone.")
return item, false
}
r.tombs++
item.tomb = true
r.items[id] = item
r.Unlock()
// TODO: We should be clearing these out in batches, rather than creating
// individual timers for each item.
time.AfterFunc(deleteAfter, func() { r.Delete(id) })
return item, true
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/signature.go#L112-L120
|
func (s *untrustedSignature) UnmarshalJSON(data []byte) error {
err := s.strictUnmarshalJSON(data)
if err != nil {
if _, ok := err.(jsonFormatError); ok {
err = InvalidSignatureError{msg: err.Error()}
}
}
return err
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/object.go#L274-L276
|
func (p *Process) ForEachRootPtr(r *Root, fn func(int64, Object, int64) bool) {
edges1(p, r, 0, r.Type, fn)
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/auth/auth.go#L23-L25
|
func (c *TokenCredentials) WithInsecure() *TokenCredentials {
return &TokenCredentials{token: c.token, tokenFunc: c.tokenFunc, allowInsecure: true}
}
|
https://github.com/st3v/tracerr/blob/07f754d5ee02576c14a8272df820e8947d87e723/tracerr.go#L102-L112
|
func captureStack(skip, maxDepth int) []*stackFrame {
pcs := make([]uintptr, maxDepth)
count := runtime.Callers(skip+1, pcs)
frames := make([]*stackFrame, count)
for i, pc := range pcs[0:count] {
frames[i] = newStackFrame(pc)
}
return frames
}
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/interaction.go#L66-L84
|
func isJSONFormattedObject(stringOrObject interface{}) bool {
switch content := stringOrObject.(type) {
case []byte:
case string:
var obj interface{}
err := json.Unmarshal([]byte(content), &obj)
if err != nil {
return false
}
// Check if a map type
if _, ok := obj.(map[string]interface{}); ok {
return true
}
}
return false
}
|
https://github.com/mipearson/rfw/blob/6f0a6f3266ba1058df9ef0c94cda1cecd2e62852/rfw.go#L27-L33
|
func Open(path string, mode os.FileMode) (*Writer, error) {
var w Writer
w.path = path
w.mode = mode
err := w.open()
return &w, err
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nitro.go#L562-L573
|
func (s *Snapshot) Close() {
newRefcount := atomic.AddInt32(&s.refCount, -1)
if newRefcount == 0 {
buf := s.db.snapshots.MakeBuf()
defer s.db.snapshots.FreeBuf(buf)
// Move from live snapshot list to dead list
s.db.snapshots.Delete(unsafe.Pointer(s), CompareSnapshot, buf, &s.db.snapshots.Stats)
s.db.gcsnapshots.Insert(unsafe.Pointer(s), CompareSnapshot, buf, &s.db.gcsnapshots.Stats)
s.db.GC()
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L970-L974
|
func (v StopRuleUsageTrackingParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss7(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dgl/gc.go#L39-L80
|
func (p *Painter) Paint(ss []raster.Span, done bool) {
//gl.Begin(gl.LINES)
sslen := len(ss)
clenrequired := sslen * 8
vlenrequired := sslen * 4
if clenrequired >= (cap(p.colors) - len(p.colors)) {
p.Flush()
if clenrequired >= cap(p.colors) {
p.vertices = make([]int32, 0, vlenrequired+(vlenrequired/2))
p.colors = make([]uint8, 0, clenrequired+(clenrequired/2))
}
}
vi := len(p.vertices)
ci := len(p.colors)
p.vertices = p.vertices[0 : vi+vlenrequired]
p.colors = p.colors[0 : ci+clenrequired]
var (
colors []uint8
vertices []int32
)
for _, s := range ss {
a := uint8((s.Alpha * p.ca / M16) >> 8)
colors = p.colors[ci:]
colors[0] = p.cr
colors[1] = p.cg
colors[2] = p.cb
colors[3] = a
colors[4] = p.cr
colors[5] = p.cg
colors[6] = p.cb
colors[7] = a
ci += 8
vertices = p.vertices[vi:]
vertices[0] = int32(s.X0)
vertices[1] = int32(s.Y)
vertices[2] = int32(s.X1)
vertices[3] = int32(s.Y)
vi += 4
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L3324-L3328
|
func (v MediaQueryExpression) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss29(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/token-counter/influx.go#L36-L41
|
func (config *InfluxConfig) AddFlags(cmd *cobra.Command) {
cmd.PersistentFlags().StringVar(&config.User, "influx-user", "root", "InfluxDB user")
cmd.PersistentFlags().StringVar(&config.Password, "influx-password", "", "InfluxDB password")
cmd.PersistentFlags().StringVar(&config.Host, "influx-host", "http://localhost:8086", "InfluxDB http server")
cmd.PersistentFlags().StringVar(&config.DB, "influx-database", "monitoring", "InfluxDB database name")
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/etcdhttp/base.go#L87-L109
|
func logHandleFunc(w http.ResponseWriter, r *http.Request) {
if !allowMethod(w, r, "PUT") {
return
}
in := struct{ Level string }{}
d := json.NewDecoder(r.Body)
if err := d.Decode(&in); err != nil {
WriteError(nil, w, r, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid json body"))
return
}
logl, err := capnslog.ParseLevel(strings.ToUpper(in.Level))
if err != nil {
WriteError(nil, w, r, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid log level "+in.Level))
return
}
plog.Noticef("globalLogLevel set to %q", logl.String())
capnslog.SetGlobalLogLevel(logl)
w.WriteHeader(http.StatusNoContent)
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/context_header.go#L69-L74
|
func (c headerCtx) ResponseHeaders() map[string]string {
if h := c.headers(); h != nil {
return h.respHeaders
}
return nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/maintenance/aws-janitor/resources/route53.go#L61-L76
|
func resourceRecordSetIsManaged(rrs *route53.ResourceRecordSet) bool {
if "A" != aws.StringValue(rrs.Type) {
return false
}
name := aws.StringValue(rrs.Name)
for _, managedNameRegex := range managedNameRegexes {
if managedNameRegex.MatchString(name) {
return true
}
}
klog.Infof("Ignoring unmanaged name %q", name)
return false
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L1226-L1232
|
func SetAttributeValue(nodeID cdp.NodeID, name string, value string) *SetAttributeValueParams {
return &SetAttributeValueParams{
NodeID: nodeID,
Name: name,
Value: value,
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_networks.go#L53-L67
|
func (r *ProtocolLXD) GetNetwork(name string) (*api.Network, string, error) {
if !r.HasExtension("network") {
return nil, "", fmt.Errorf("The server is missing the required \"network\" API extension")
}
network := api.Network{}
// Fetch the raw value
etag, err := r.queryStruct("GET", fmt.Sprintf("/networks/%s", url.QueryEscape(name)), nil, "", &network)
if err != nil {
return nil, "", err
}
return &network, etag, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/easyjson.go#L1351-L1355
|
func (v ContinueWithAuthParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoFetch12(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L465-L469
|
func (v *StopLoadingParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage4(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/accessibility/types.go#L109-L111
|
func (t *ValueType) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/membership.go#L218-L422
|
func Join(state *state.State, gateway *Gateway, cert *shared.CertInfo, name string, nodes []db.RaftNode) error {
// Check parameters
if name == "" {
return fmt.Errorf("node name must not be empty")
}
var address string
err := state.Node.Transaction(func(tx *db.NodeTx) error {
// Fetch current network address and raft nodes
config, err := node.ConfigLoad(tx)
if err != nil {
return errors.Wrap(err, "failed to fetch node configuration")
}
address = config.ClusterAddress()
// Make sure node-local database state is in order.
err = membershipCheckNodeStateForBootstrapOrJoin(tx, address)
if err != nil {
return err
}
// Set the raft nodes list to the one that was returned by Accept().
err = tx.RaftNodesReplace(nodes)
if err != nil {
return errors.Wrap(err, "failed to set raft nodes")
}
return nil
})
if err != nil {
return err
}
// Get the local config keys for the cluster pools and networks. It
// assumes that the local storage pools and networks match the cluster
// networks, if not an error will be returned. Also get any outstanding
// operation, typically there will be just one, created by the POST
// /cluster/nodes request which triggered this code.
var pools map[string]map[string]string
var networks map[string]map[string]string
var operations []db.Operation
err = state.Cluster.Transaction(func(tx *db.ClusterTx) error {
pools, err = tx.StoragePoolsNodeConfig()
if err != nil {
return err
}
networks, err = tx.NetworksNodeConfig()
if err != nil {
return err
}
operations, err = tx.Operations()
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
// Lock regular access to the cluster database since we don't want any
// other database code to run while we're reconfiguring raft.
err = state.Cluster.EnterExclusive()
if err != nil {
return errors.Wrap(err, "failed to acquire cluster database lock")
}
// Shutdown the gateway and wipe any raft data. This will trash any
// gRPC SQL connection against our in-memory dqlite driver and shutdown
// the associated raft instance.
err = gateway.Shutdown()
if err != nil {
return errors.Wrap(err, "failed to shutdown gRPC SQL gateway")
}
err = os.RemoveAll(state.OS.GlobalDatabaseDir())
if err != nil {
return errors.Wrap(err, "failed to remove existing raft data")
}
// Re-initialize the gateway. This will create a new raft factory an
// dqlite driver instance, which will be exposed over gRPC by the
// gateway handlers.
gateway.cert = cert
err = gateway.init()
if err != nil {
return errors.Wrap(err, "failed to re-initialize gRPC SQL gateway")
}
// If we are listed among the database nodes, join the raft cluster.
id := ""
target := ""
for _, node := range nodes {
if node.Address == address {
id = strconv.Itoa(int(node.ID))
} else {
target = node.Address
}
}
if id != "" {
logger.Info(
"Joining dqlite raft cluster",
log15.Ctx{"id": id, "address": address, "target": target})
changer := gateway.raft.MembershipChanger()
err := changer.Join(raft.ServerID(id), raft.ServerAddress(target), 5*time.Second)
if err != nil {
return err
}
} else {
logger.Info("Joining cluster as non-database node")
}
// Make sure we can actually connect to the cluster database through
// the network endpoint. This also releases the previously acquired
// lock and makes the Go SQL pooling system invalidate the old
// connection, so new queries will be executed over the new gRPC
// network connection. Also, update the storage_pools and networks
// tables with our local configuration.
logger.Info("Migrate local data to cluster database")
err = state.Cluster.ExitExclusive(func(tx *db.ClusterTx) error {
node, err := tx.NodePendingByAddress(address)
if err != nil {
return errors.Wrap(err, "failed to get ID of joining node")
}
state.Cluster.NodeID(node.ID)
tx.NodeID(node.ID)
// Storage pools.
ids, err := tx.StoragePoolIDsNotPending()
if err != nil {
return errors.Wrap(err, "failed to get cluster storage pool IDs")
}
for name, id := range ids {
err := tx.StoragePoolNodeJoin(id, node.ID)
if err != nil {
return errors.Wrap(err, "failed to add joining node's to the pool")
}
driver, err := tx.StoragePoolDriver(id)
if err != nil {
return errors.Wrap(err, "failed to get storage pool driver")
}
if driver == "ceph" {
// For ceph pools we have to create volume
// entries for the joining node.
err := tx.StoragePoolNodeJoinCeph(id, node.ID)
if err != nil {
return errors.Wrap(err, "failed to create ceph volumes for joining node")
}
} else {
// For other pools we add the config provided by the joining node.
config, ok := pools[name]
if !ok {
return fmt.Errorf("joining node has no config for pool %s", name)
}
err = tx.StoragePoolConfigAdd(id, node.ID, config)
if err != nil {
return errors.Wrap(err, "failed to add joining node's pool config")
}
}
}
// Networks.
ids, err = tx.NetworkIDsNotPending()
if err != nil {
return errors.Wrap(err, "failed to get cluster network IDs")
}
for name, id := range ids {
config, ok := networks[name]
if !ok {
return fmt.Errorf("joining node has no config for network %s", name)
}
err := tx.NetworkNodeJoin(id, node.ID)
if err != nil {
return errors.Wrap(err, "failed to add joining node's to the network")
}
err = tx.NetworkConfigAdd(id, node.ID, config)
if err != nil {
return errors.Wrap(err, "failed to add joining node's network config")
}
}
// Migrate outstanding operations.
for _, operation := range operations {
_, err := tx.OperationAdd("", operation.UUID, operation.Type)
if err != nil {
return errors.Wrapf(err, "failed to migrate operation %s", operation.UUID)
}
}
// Remove the pending flag for ourselves
// notifications.
err = tx.NodePending(node.ID, false)
if err != nil {
return errors.Wrapf(err, "failed to unmark the node as pending")
}
return nil
})
if err != nil {
return errors.Wrap(err, "cluster database initialization failed")
}
return nil
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/parser/symbols.go#L39-L45
|
func (list LexSymbolList) Sort() LexSymbolList {
sorter := LexSymbolSorter{
list: list,
}
sort.Sort(sorter)
return sorter.list
}
|
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/cloudconfig_manifest_primatives.go#L49-L58
|
func (s *CloudConfigManifest) ContainsVMType(vmTypeName string) (result bool) {
result = false
for _, vmType := range s.VMTypes {
if vmType.Name == vmTypeName {
result = true
return
}
}
return
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/volume.go#L110-L146
|
func volumeCreate(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
var inputVolume volume.Volume
err = ParseInput(r, &inputVolume)
if err != nil {
return err
}
inputVolume.Plan.Opts = nil
inputVolume.Status = ""
canCreate := permission.Check(t, permission.PermVolumeCreate,
permission.Context(permTypes.CtxTeam, inputVolume.TeamOwner),
permission.Context(permTypes.CtxPool, inputVolume.Pool),
)
if !canCreate {
return permission.ErrUnauthorized
}
evt, err := event.New(&event.Opts{
Target: event.Target{Type: event.TargetTypeVolume, Value: inputVolume.Name},
Kind: permission.PermVolumeCreate,
Owner: t,
CustomData: event.FormToCustomData(InputFields(r)),
Allowed: event.Allowed(permission.PermVolumeReadEvents, contextsForVolume(&inputVolume)...),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
_, err = volume.Load(inputVolume.Name)
if err == nil {
return &errors.HTTP{Code: http.StatusConflict, Message: "volume already exists"}
}
err = inputVolume.Create()
if err != nil {
return err
}
w.WriteHeader(http.StatusCreated)
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/easyjson.go#L1129-L1133
|
func (v GetHistogramsReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoBrowser11(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/ext/tags.go#L178-L180
|
func (tag uint32TagName) Set(span opentracing.Span, value uint32) {
span.SetTag(string(tag), value)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L2575-L2579
|
func (v *PerformSearchParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom28(&r, v)
return r.Error()
}
|
https://github.com/ianschenck/envflag/blob/9111d830d133f952887a936367fb0211c3134f0d/envflag.go#L151-L153
|
func DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
EnvironmentFlags.DurationVar(p, name, value, usage)
}
|
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/base.go#L362-L364
|
func (b *Base) Log(level LogLevel, m *Attrs, msg string, a ...interface{}) error {
return b.LogWithTime(level, b.clock.Now(), m, msg, a...)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/types.go#L198-L200
|
func (t *ErrorReason) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/performance/easyjson.go#L277-L281
|
func (v *GetMetricsReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoPerformance2(&r, v)
return r.Error()
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/layout/oci_src.go#L27-L50
|
func newImageSource(sys *types.SystemContext, ref ociReference) (types.ImageSource, error) {
tr := tlsclientconfig.NewTransport()
tr.TLSClientConfig = tlsconfig.ServerDefault()
if sys != nil && sys.OCICertPath != "" {
if err := tlsclientconfig.SetupCertificates(sys.OCICertPath, tr.TLSClientConfig); err != nil {
return nil, err
}
tr.TLSClientConfig.InsecureSkipVerify = sys.OCIInsecureSkipTLSVerify
}
client := &http.Client{}
client.Transport = tr
descriptor, err := ref.getManifestDescriptor()
if err != nil {
return nil, err
}
d := &ociImageSource{ref: ref, descriptor: descriptor, client: client}
if sys != nil {
// TODO(jonboulle): check dir existence?
d.sharedBlobDir = sys.OCISharedBlobDirPath
}
return d, nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.