_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/easyjson.go#L470-L474
|
func (v *RequestDataReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoIndexeddb4(&r, v)
return r.Error()
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/auth/server/api_server.go#L2266-L2280
|
func canonicalizeGitHubUsername(ctx context.Context, user string) (string, error) {
if strings.Index(user, ":") >= 0 {
return "", fmt.Errorf("invalid username has multiple prefixes: %s%s", authclient.GitHubPrefix, user)
}
if os.Getenv(DisableAuthenticationEnvVar) == "true" {
// authentication is off -- user might not even be real
return authclient.GitHubPrefix + user, nil
}
gclient := github.NewClient(http.DefaultClient)
u, _, err := gclient.Users.Get(ctx, strings.ToLower(user))
if err != nil {
return "", fmt.Errorf("error canonicalizing \"%s\": %v", user, err)
}
return authclient.GitHubPrefix + u.GetLogin(), nil
}
|
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/header.go#L237-L283
|
func fixMangledMediaType(mtype, sep string) string {
if mtype == "" {
return ""
}
parts := strings.Split(mtype, sep)
mtype = ""
for i, p := range parts {
switch i {
case 0:
if p == "" {
// The content type is completely missing. Put in a placeholder.
p = ctPlaceholder
}
default:
if !strings.Contains(p, "=") {
p = p + "=" + pvPlaceholder
}
// RFC-2047 encoded attribute name
p = rfc2047AttributeName(p)
pair := strings.Split(p, "=")
if strings.Contains(mtype, pair[0]+"=") {
// Ignore repeated parameters.
continue
}
if strings.ContainsAny(pair[0], "()<>@,;:\"\\/[]?") {
// attribute is a strict token and cannot be a quoted-string
// if any of the above characters are present in a token it
// must be quoted and is therefor an invalid attribute.
// Discard the pair.
continue
}
}
mtype += p
// Only terminate with semicolon if not the last parameter and if it doesn't already have a
// semicolon.
if i != len(parts)-1 && !strings.HasSuffix(mtype, ";") {
mtype += ";"
}
}
if strings.HasSuffix(mtype, ";") {
mtype = mtype[:len(mtype)-1]
}
return mtype
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L141-L144
|
func (img *IplImage) GetROI() Rect {
r := C.cvGetImageROI((*C.IplImage)(img))
return Rect(r)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/mvcc/key_index.go#L224-L253
|
func (ki *keyIndex) compact(lg *zap.Logger, atRev int64, available map[revision]struct{}) {
if ki.isEmpty() {
if lg != nil {
lg.Panic(
"'compact' got an unexpected empty keyIndex",
zap.String("key", string(ki.key)),
)
} else {
plog.Panicf("store.keyindex: unexpected compact on empty keyIndex %s", string(ki.key))
}
}
genIdx, revIndex := ki.doCompact(atRev, available)
g := &ki.generations[genIdx]
if !g.isEmpty() {
// remove the previous contents.
if revIndex != -1 {
g.revs = g.revs[revIndex:]
}
// remove any tombstone
if len(g.revs) == 1 && genIdx != len(ki.generations)-1 {
delete(available, g.revs[0])
genIdx++
}
}
// remove the previous generations.
ki.generations = ki.generations[genIdx:]
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/etcdserverpb/gw/rpc.pb.gw.go#L1737-L2204
|
func RegisterAuthHandlerClient(ctx context.Context, mux *runtime.ServeMux, client etcdserverpb.AuthClient) error {
mux.Handle("POST", pattern_Auth_AuthEnable_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Auth_AuthEnable_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Auth_AuthEnable_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Auth_AuthDisable_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Auth_AuthDisable_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Auth_AuthDisable_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Auth_Authenticate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Auth_Authenticate_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Auth_Authenticate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Auth_UserAdd_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Auth_UserAdd_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Auth_UserAdd_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Auth_UserGet_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Auth_UserGet_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Auth_UserGet_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Auth_UserList_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Auth_UserList_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Auth_UserList_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Auth_UserDelete_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Auth_UserDelete_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Auth_UserDelete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Auth_UserChangePassword_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Auth_UserChangePassword_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Auth_UserChangePassword_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Auth_UserGrantRole_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Auth_UserGrantRole_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Auth_UserGrantRole_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Auth_UserRevokeRole_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Auth_UserRevokeRole_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Auth_UserRevokeRole_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Auth_RoleAdd_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Auth_RoleAdd_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Auth_RoleAdd_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Auth_RoleGet_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Auth_RoleGet_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Auth_RoleGet_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Auth_RoleList_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Auth_RoleList_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Auth_RoleList_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Auth_RoleDelete_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Auth_RoleDelete_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Auth_RoleDelete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Auth_RoleGrantPermission_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Auth_RoleGrantPermission_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Auth_RoleGrantPermission_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Auth_RoleRevokePermission_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Auth_RoleRevokePermission_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Auth_RoleRevokePermission_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/obj/obj.go#L523-L530
|
func NewExponentialBackOffConfig() *backoff.ExponentialBackOff {
config := backoff.NewExponentialBackOff()
// We want to backoff more aggressively (i.e. wait longer) than the default
config.InitialInterval = 1 * time.Second
config.Multiplier = 2
config.MaxInterval = 15 * time.Minute
return config
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/jobs.go#L523-L534
|
func (c *JobConfig) AllPeriodics() []Periodic {
var listPeriodic func(ps []Periodic) []Periodic
listPeriodic = func(ps []Periodic) []Periodic {
var res []Periodic
for _, p := range ps {
res = append(res, p)
}
return res
}
return listPeriodic(c.Periodics)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pkg/require/require.go#L307-L312
|
func NoError(tb testing.TB, err error, msgAndArgs ...interface{}) {
tb.Helper()
if err != nil {
fatal(tb, msgAndArgs, "No error is expected but got %s", err.Error())
}
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/daemon/client.go#L18-L51
|
func newDockerClient(sys *types.SystemContext) (*dockerclient.Client, error) {
host := dockerclient.DefaultDockerHost
if sys != nil && sys.DockerDaemonHost != "" {
host = sys.DockerDaemonHost
}
// Sadly, unix:// sockets don't work transparently with dockerclient.NewClient.
// They work fine with a nil httpClient; with a non-nil httpClient, the transport’s
// TLSClientConfig must be nil (or the client will try using HTTPS over the PF_UNIX socket
// regardless of the values in the *tls.Config), and we would have to call sockets.ConfigureTransport.
//
// We don't really want to configure anything for unix:// sockets, so just pass a nil *http.Client.
//
// Similarly, if we want to communicate over plain HTTP on a TCP socket, we also need to set
// TLSClientConfig to nil. This can be achieved by using the form `http://`
url, err := dockerclient.ParseHostURL(host)
if err != nil {
return nil, err
}
var httpClient *http.Client
if url.Scheme != "unix" {
if url.Scheme == "http" {
httpClient = httpConfig()
} else {
hc, err := tlsConfig(sys)
if err != nil {
return nil, err
}
httpClient = hc
}
}
return dockerclient.NewClient(host, defaultAPIVersion, httpClient, nil)
}
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/access_log_apache.go#L175-L180
|
func (u *accessLogUtil) RemoteUser() string {
if u.R.Env["REMOTE_USER"] != nil {
return u.R.Env["REMOTE_USER"].(string)
}
return ""
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v3rpc/watch.go#L48-L61
|
func NewWatchServer(s *etcdserver.EtcdServer) pb.WatchServer {
return &watchServer{
lg: s.Cfg.Logger,
clusterID: int64(s.Cluster().ID()),
memberID: int64(s.ID()),
maxRequestBytes: int(s.Cfg.MaxRequestBytes + grpcOverheadBytes),
sg: s,
watchable: s.Watchable(),
ag: s,
}
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L3482-L3489
|
func (r *IdentityProvider) Locator(api *API) *IdentityProviderLocator {
for _, l := range r.Links {
if l["rel"] == "self" {
return api.IdentityProviderLocator(l["href"])
}
}
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/raft.go#L69-L80
|
func (n *NodeTx) RaftNodeFirst(address string) error {
columns := []string{"id", "address"}
values := []interface{}{int64(1), address}
id, err := query.UpsertObject(n.tx, "raft_nodes", columns, values)
if err != nil {
return err
}
if id != 1 {
return fmt.Errorf("could not set raft node ID to 1")
}
return nil
}
|
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cmd/completion.go#L44-L87
|
func CompletionCmd() *cobra.Command {
return &cobra.Command{
Use: "completion",
Short: "Generate completion code for bash and zsh shells.",
Long: `completion is used to output completion code for bash and zsh shells.
Before using completion features, you have to source completion code
from your .profile. This is done by adding following line to one of above files:
source <(kubicorn completion SHELL)
Valid arguments for SHELL are: "bash" and "zsh".
Notes:
1) zsh completions requires zsh 5.2 or newer.
2) macOS users have to install bash-completion framework to utilize
completion features. This can be done using homebrew:
brew install bash-completion
Once installed, you must load bash_completion by adding following
line to your .profile or .bashrc/.zshrc:
source $(brew --prefix)/etc/bash_completion`,
RunE: func(cmd *cobra.Command, args []string) error {
if logger.Fabulous {
cmd.SetOutput(logger.FabulousWriter)
}
if viper.GetString(keyTrueColor) != "" {
cmd.SetOutput(logger.FabulousWriter)
}
switch len(args) {
case 0:
return fmt.Errorf("shell argument is not specified")
default:
switch args[0] {
case "bash":
return runBashGeneration()
case "zsh":
return runZshGeneration()
default:
return fmt.Errorf("invalid shell argument")
}
}
},
}
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L278-L283
|
func (it *inclusiveRangeIt) IsDone() bool {
if it.pos >= it.ptr.Len() {
return true
}
return false
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L2066-L2075
|
func (u OperationBody) GetManageDataOp() (result ManageDataOp, ok bool) {
armName, _ := u.ArmForSwitch(int32(u.Type))
if armName == "ManageDataOp" {
result = *u.ManageDataOp
ok = true
}
return
}
|
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vmx.go#L46-L64
|
func (vmxfile *VMXFile) Write() error {
file, err := os.Create(vmxfile.path)
if err != nil {
return err
}
defer file.Close()
data, err := vmx.Marshal(vmxfile.model)
if err != nil {
return err
}
_, err = file.Write(data)
if err != nil {
return err
}
return nil
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/outbound.go#L191-L194
|
func (call *OutboundCall) writeMethod(method []byte) error {
call.statsReporter.IncCounter("outbound.calls.send", call.commonStatsTags, 1)
return NewArgWriter(call.arg1Writer()).Write(method)
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/handlers/elasticsearch/elasticsearch.go#L96-L103
|
func (h *Handler) Flush() {
h.mu.Lock()
defer h.mu.Unlock()
if h.batch != nil {
go h.flush(h.batch)
h.batch = nil
}
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/core/mapping.go#L115-L133
|
func (p *Process) findMapping(a Address) *Mapping {
t3 := p.pageTable[a>>52]
if t3 == nil {
return nil
}
t2 := t3[a>>42%(1<<10)]
if t2 == nil {
return nil
}
t1 := t2[a>>32%(1<<10)]
if t1 == nil {
return nil
}
t0 := t1[a>>22%(1<<10)]
if t0 == nil {
return nil
}
return t0[a>>12%(1<<10)]
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/meshconn/peer.go#L46-L58
|
func NewPeer(name mesh.PeerName, uid mesh.PeerUID, logger mesh.Logger) *Peer {
p := &Peer{
name: name,
uid: uid,
gossip: nil, // initially no gossip
recv: make(chan pkt),
actions: make(chan func()),
quit: make(chan struct{}),
logger: logger,
}
go p.loop()
return p
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/directory/directory_src.go#L40-L49
|
func (s *dirImageSource) GetManifest(ctx context.Context, instanceDigest *digest.Digest) ([]byte, string, error) {
if instanceDigest != nil {
return nil, "", errors.Errorf(`Getting target manifest not supported by "dir:"`)
}
m, err := ioutil.ReadFile(s.ref.manifestPath())
if err != nil {
return nil, "", err
}
return m, manifest.GuessMIMEType(m), err
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L572-L579
|
func (r *AlertSpec) Locator(api *API) *AlertSpecLocator {
for _, l := range r.Links {
if l["rel"] == "self" {
return api.AlertSpecLocator(l["href"])
}
}
return nil
}
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gbytes/buffer.go#L114-L121
|
func (b *Buffer) Close() error {
b.lock.Lock()
defer b.lock.Unlock()
b.closed = true
return nil
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/models/apps_wrapper.go#L82-L87
|
func (m *AppsWrapper) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
|
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/decode.go#L1197-L1212
|
func (d Decoder) DecodeMap(f func(Decoder, Decoder) error) (err error) {
var typ Type
if d.off != 0 {
if d.off, err = 0, d.Parser.ParseMapValue(d.off-1); err != nil {
return
}
}
if typ, err = d.Parser.ParseType(); err != nil {
return
}
err = d.decodeMapImpl(typ, f)
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L6004-L6008
|
func (v EventAttributeRemoved) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom67(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/migrate_container.go#L181-L215
|
func readCriuStatsDump(path string) (uint64, uint64, error) {
statsDump := shared.AddSlash(path) + "stats-dump"
in, err := ioutil.ReadFile(statsDump)
if err != nil {
logger.Errorf("Error reading CRIU's 'stats-dump' file: %s", err.Error())
return 0, 0, err
}
// According to the CRIU file image format it starts with two magic values.
// First magic IMG_SERVICE: 1427134784
if binary.LittleEndian.Uint32(in[0:4]) != 1427134784 {
msg := "IMG_SERVICE(1427134784) criu magic not found"
logger.Errorf(msg)
return 0, 0, fmt.Errorf(msg)
}
// Second magic STATS: 1460220678
if binary.LittleEndian.Uint32(in[4:8]) != 1460220678 {
msg := "STATS(1460220678) criu magic not found"
logger.Errorf(msg)
return 0, 0, fmt.Errorf(msg)
}
// Next, read the size of the image payload
size := binary.LittleEndian.Uint32(in[8:12])
statsEntry := &migration.StatsEntry{}
if err = proto.Unmarshal(in[12:12+size], statsEntry); err != nil {
logger.Errorf("Failed to parse CRIU's 'stats-dump' file: %s", err.Error())
return 0, 0, err
}
written := statsEntry.GetDump().GetPagesWritten()
skipped := statsEntry.GetDump().GetPagesSkippedParent()
return written, skipped, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/plugins/multiplexer_wrapper.go#L38-L46
|
func (m *MultiplexerPluginWrapper) ReceiveIssue(issue sql.Issue) []Point {
points := []Point{}
for _, plugin := range m.plugins {
points = append(points, plugin.ReceiveIssue(issue)...)
}
return points
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logging/log.go#L16-L82
|
func GetLogger(syslog string, logfile string, verbose bool, debug bool, customHandler log.Handler) (logger.Logger, error) {
Log := log.New()
var handlers []log.Handler
var syshandler log.Handler
// System specific handler
syshandler = getSystemHandler(syslog, debug, LogfmtFormat())
if syshandler != nil {
handlers = append(handlers, syshandler)
}
// FileHandler
if logfile != "" {
if !pathExists(filepath.Dir(logfile)) {
return nil, fmt.Errorf("Log file path doesn't exist: %s", filepath.Dir(logfile))
}
if !debug {
handlers = append(
handlers,
log.LvlFilterHandler(
log.LvlInfo,
log.Must.FileHandler(logfile, LogfmtFormat()),
),
)
} else {
handlers = append(handlers, log.Must.FileHandler(logfile, LogfmtFormat()))
}
}
// StderrHandler
format := LogfmtFormat()
if term.IsTty(os.Stderr.Fd()) {
format = TerminalFormat()
}
if verbose || debug {
if !debug {
handlers = append(
handlers,
log.LvlFilterHandler(
log.LvlInfo,
log.StreamHandler(os.Stderr, format),
),
)
} else {
handlers = append(handlers, log.StreamHandler(os.Stderr, format))
}
} else {
handlers = append(
handlers,
log.LvlFilterHandler(
log.LvlWarn,
log.StreamHandler(os.Stderr, format),
),
)
}
if customHandler != nil {
handlers = append(handlers, customHandler)
}
Log.SetHandler(log.MultiHandler(handlers...))
return Log, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/clonerefs/run.go#L37-L100
|
func (o Options) Run() error {
var env []string
if len(o.KeyFiles) > 0 {
var err error
env, err = addSSHKeys(o.KeyFiles)
if err != nil {
logrus.WithError(err).Error("Failed to add SSH keys.")
// Continue on error. Clones will fail with an appropriate error message
// that initupload can consume whereas quitting without writing the clone
// record log is silent and results in an errored prow job instead of a
// failed one.
}
}
if len(o.HostFingerprints) > 0 {
if err := addHostFingerprints(o.HostFingerprints); err != nil {
logrus.WithError(err).Error("failed to add host fingerprints")
}
}
var numWorkers int
if o.MaxParallelWorkers != 0 {
numWorkers = o.MaxParallelWorkers
} else {
numWorkers = len(o.GitRefs)
}
wg := &sync.WaitGroup{}
wg.Add(numWorkers)
input := make(chan prowapi.Refs)
output := make(chan clone.Record, len(o.GitRefs))
for i := 0; i < numWorkers; i++ {
go func() {
defer wg.Done()
for ref := range input {
output <- cloneFunc(ref, o.SrcRoot, o.GitUserName, o.GitUserEmail, o.CookiePath, env)
}
}()
}
for _, ref := range o.GitRefs {
input <- ref
}
close(input)
wg.Wait()
close(output)
var results []clone.Record
for record := range output {
results = append(results, record)
}
logData, err := json.Marshal(results)
if err != nil {
return fmt.Errorf("failed to marshal clone records: %v", err)
}
if err := ioutil.WriteFile(o.Log, logData, 0755); err != nil {
return fmt.Errorf("failed to write clone records: %v", err)
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L1061-L1065
|
func (v *ResolveNodeReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom10(&r, v)
return r.Error()
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/servers/simple.go#L14-L18
|
func (s *Simple) SetAddr(addr string) {
if s.Server.Addr == "" {
s.Server.Addr = addr
}
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L468-L559
|
func (app *App) Update(updateData App, w io.Writer) (err error) {
description := updateData.Description
planName := updateData.Plan.Name
poolName := updateData.Pool
teamOwner := updateData.TeamOwner
platform := updateData.Platform
tags := processTags(updateData.Tags)
oldApp := *app
if description != "" {
app.Description = description
}
if poolName != "" {
app.Pool = poolName
app.provisioner = nil
_, err = app.getPoolForApp(app.Pool)
if err != nil {
return err
}
}
newProv, err := app.getProvisioner()
if err != nil {
return err
}
oldProv, err := oldApp.getProvisioner()
if err != nil {
return err
}
if planName != "" {
plan, errFind := servicemanager.Plan.FindByName(planName)
if errFind != nil {
return errFind
}
app.Plan = *plan
}
if teamOwner != "" {
team, errTeam := servicemanager.Team.FindByName(teamOwner)
if errTeam != nil {
return errTeam
}
app.TeamOwner = team.Name
defer func() {
if err == nil {
app.Grant(team)
}
}()
}
if tags != nil {
app.Tags = tags
}
if platform != "" {
var p, v string
p, v, err = getPlatformNameAndVersion(platform)
if err != nil {
return err
}
if app.Platform != p || app.PlatformVersion != v {
app.UpdatePlatform = true
}
app.Platform = p
app.PlatformVersion = v
}
if updateData.UpdatePlatform {
app.UpdatePlatform = true
}
err = app.validate()
if err != nil {
return err
}
actions := []*action.Action{
&saveApp,
}
if newProv.GetName() == oldProv.GetName() {
actions = append(actions, &updateAppProvisioner)
}
if newProv.GetName() != oldProv.GetName() {
defer func() {
rebuild.RoutesRebuildOrEnqueue(app.Name)
}()
err = validateVolumes(app)
if err != nil {
return err
}
actions = append(actions,
&provisionAppNewProvisioner,
&provisionAppAddUnits,
&destroyAppOldProvisioner)
} else if app.Plan != oldApp.Plan {
actions = append(actions, &restartApp)
}
return action.NewPipeline(actions...).Execute(app, &oldApp, w)
}
|
https://github.com/geoffgarside/ber/blob/27a1aff36ce64dbe5d93c08cc5f161983134ddc5/ber.go#L256-L269
|
func parseGeneralizedTime(bytes []byte) (ret time.Time, err error) {
const formatStr = "20060102150405Z0700"
s := string(bytes)
if ret, err = time.Parse(formatStr, s); err != nil {
return
}
if serialized := ret.Format(formatStr); serialized != s {
err = fmt.Errorf("asn1: time did not serialize back to the original value and may be invalid: given %q, but serialized as %q", s, serialized)
}
return
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/checkconfig/main.go#L724-L737
|
func ensureValidConfiguration(plugin, label, verb string, tideSubSet, tideSuperSet, pluginsSubSet *orgRepoConfig) error {
notEnabled := tideSubSet.difference(pluginsSubSet).items()
notRequired := pluginsSubSet.intersection(tideSuperSet).difference(tideSubSet).items()
var configErrors []error
if len(notEnabled) > 0 {
configErrors = append(configErrors, fmt.Errorf("the following orgs or repos %s the %s label for merging but do not enable the %s plugin: %v", verb, label, plugin, notEnabled))
}
if len(notRequired) > 0 {
configErrors = append(configErrors, fmt.Errorf("the following orgs or repos enable the %s plugin but do not %s the %s label for merging: %v", plugin, verb, label, notRequired))
}
return errorutil.NewAggregate(configErrors...)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/repoowners/repoowners.go#L119-L136
|
func NewClient(
gc *git.Client,
ghc *github.Client,
mdYAMLEnabled func(org, repo string) bool,
skipCollaborators func(org, repo string) bool,
ownersDirBlacklist func() prowConf.OwnersDirBlacklist,
) *Client {
return &Client{
git: gc,
ghc: ghc,
logger: logrus.WithField("client", "repoowners"),
cache: make(map[string]cacheEntry),
mdYAMLEnabled: mdYAMLEnabled,
skipCollaborators: skipCollaborators,
ownersDirBlacklist: ownersDirBlacklist,
}
}
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L253-L256
|
func (l *Logger) Fatalf(format string, args ...interface{}) {
l.Output(2, LevelFatal, fmt.Sprintf(format, args...))
os.Exit(1)
}
|
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/snowballword/snowballword.go#L138-L140
|
func (w *SnowballWord) FitsInRV(x int) bool {
return w.RVstart <= len(w.RS)-x
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selection_actions.go#L39-L49
|
func (s *Selection) DoubleClick() error {
return s.forEachElement(func(selectedElement element.Element) error {
if err := s.session.MoveTo(selectedElement.(*api.Element), nil); err != nil {
return fmt.Errorf("failed to move mouse to %s: %s", s, err)
}
if err := s.session.DoubleClick(); err != nil {
return fmt.Errorf("failed to double-click on %s: %s", s, err)
}
return nil
})
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/rpclog/grpc.go#L23-L28
|
func ServerOptions(log ttnlog.Interface) []grpc.ServerOption {
return []grpc.ServerOption{
grpc.UnaryInterceptor(UnaryServerInterceptor(log)),
grpc.StreamInterceptor(StreamServerInterceptor(log)),
}
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/inmem_store.go#L32-L36
|
func (i *InmemStore) FirstIndex() (uint64, error) {
i.l.RLock()
defer i.l.RUnlock()
return i.lowIndex, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/election.go#L148-L158
|
func (e *Election) Leader(ctx context.Context) (*v3.GetResponse, error) {
client := e.session.Client()
resp, err := client.Get(ctx, e.keyPrefix, v3.WithFirstCreate()...)
if err != nil {
return nil, err
} else if len(resp.Kvs) == 0 {
// no leader currently elected
return nil, ErrElectionNoLeader
}
return resp, nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_volumes.go#L38-L52
|
func (r *ProtocolLXD) GetStoragePoolVolumes(pool string) ([]api.StorageVolume, error) {
if !r.HasExtension("storage") {
return nil, fmt.Errorf("The server is missing the required \"storage\" API extension")
}
volumes := []api.StorageVolume{}
// Fetch the raw value
_, err := r.queryStruct("GET", fmt.Sprintf("/storage-pools/%s/volumes?recursion=1", url.QueryEscape(pool)), nil, "", &volumes)
if err != nil {
return nil, err
}
return volumes, nil
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/skiplist/item.go#L46-L49
|
func NewByteKeyItem(k []byte) unsafe.Pointer {
itm := byteKeyItem(k)
return unsafe.Pointer(&itm)
}
|
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/view/template.go#L53-L67
|
func Html(name, contentType, charSet string) template {
if htmlTemp.Template == nil {
panic("Function `InitHtmlTemplates` should be called first.")
}
if contentType == "" {
contentType = ContentTypeHTML
}
if charSet == "" {
charSet = CharSetUTF8
}
header := make(http.Header)
header.Set("Content-Type",
fmt.Sprintf("%s; charset=%s", contentType, charSet))
return template{&htmlTemp, name, header}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/raft.go#L1348-L1378
|
func (r *raft) restore(s pb.Snapshot) bool {
if s.Metadata.Index <= r.raftLog.committed {
return false
}
if r.raftLog.matchTerm(s.Metadata.Index, s.Metadata.Term) {
r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] fast-forwarded commit to snapshot [index: %d, term: %d]",
r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
r.raftLog.commitTo(s.Metadata.Index)
return false
}
// The normal peer can't become learner.
if !r.isLearner {
for _, id := range s.Metadata.ConfState.Learners {
if id == r.id {
r.logger.Errorf("%x can't become learner when restores snapshot [index: %d, term: %d]", r.id, s.Metadata.Index, s.Metadata.Term)
return false
}
}
}
r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] starts to restore snapshot [index: %d, term: %d]",
r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
r.raftLog.restore(s)
r.prs = make(map[uint64]*Progress)
r.learnerPrs = make(map[uint64]*Progress)
r.restoreNode(s.Metadata.ConfState.Nodes, false)
r.restoreNode(s.Metadata.ConfState.Learners, true)
return true
}
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/log.go#L32-L35
|
func Fatalf(format string, args ...interface{}) {
logger.Output(2, LevelFatal, fmt.Sprintf(format, args...))
os.Exit(1)
}
|
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/helper.go#L25-L35
|
func Chain(h ...HandlerFunc) HandlerFunc {
f := func(ctx *Context) error {
for _, v := range h {
if err := v(ctx); err != nil {
return err
}
}
return nil
}
return f
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L3463-L3467
|
func (v *EventExecutionContextCreated) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime32(&r, v)
return r.Error()
}
|
https://github.com/emersion/go-sasl/blob/7e096a0a6197b89989e8cc31016daa67c8c62051/plain.go#L30-L32
|
func NewPlainClient(identity, username, password string) Client {
return &plainClient{identity, username, password}
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L912-L918
|
func CustomLogFunc(level string, f func() string) error {
lv := TagStringToLevel(level)
if isModeEnable(lv) {
return glg.out(lv, "%s", f())
}
return nil
}
|
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/model.go#L30-L34
|
func (m *Model) Check() error {
validate = validator.New()
err := validate.Struct(m)
return err
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container.go#L1477-L1494
|
func containerLoadNodeProjectAll(s *state.State, project string) ([]container, error) {
// Get all the container arguments
var cts []db.Container
err := s.Cluster.Transaction(func(tx *db.ClusterTx) error {
var err error
cts, err = tx.ContainerNodeProjectList(project)
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, err
}
return containerLoadAllInternal(cts, s)
}
|
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/page.go#L116-L123
|
func (f Font) Widths() []float64 {
x := f.V.Key("Widths")
var out []float64
for i := 0; i < x.Len(); i++ {
out = append(out, x.Index(i).Float64())
}
return out
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/easyjson.go#L601-L605
|
func (v *SetPageScaleFactorParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoEmulation6(&r, v)
return r.Error()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/repoowners/repoowners.go#L596-L598
|
func (o *RepoOwners) IsNoParentOwners(path string) bool {
return o.options[path].NoParentOwners
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/maintenance/maintenance.go#L212-L230
|
func (s Service) HTMLHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
on, err := s.store.Status()
if err != nil {
s.logger.Errorf("maintenance status: %v", err)
}
if on || err != nil {
if s.HTML.Handler != nil {
s.HTML.Handler.ServeHTTP(w, r)
return
}
w.Header().Set("Content-Type", HTMLContentType)
w.WriteHeader(http.StatusServiceUnavailable)
fmt.Fprintln(w, s.HTML.Body)
return
}
h.ServeHTTP(w, r)
})
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/location.go#L47-L52
|
func (c *Client) GetRegionalLocations(regid string) (*Locations, error) {
url := locationRegPath(regid) + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty)
ret := &Locations{}
err := c.client.Get(url, ret, http.StatusOK)
return ret, err
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/raft.go#L84-L88
|
func (n *NodeTx) RaftNodeAdd(address string) (int64, error) {
columns := []string{"address"}
values := []interface{}{address}
return query.UpsertObject(n.tx, "raft_nodes", columns, values)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pps/hash.go#L14-L19
|
func NewHasher(jobModulus uint64, pipelineModulus uint64) *Hasher {
return &Hasher{
JobModulus: jobModulus,
PipelineModulus: pipelineModulus,
}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/admin/cmds/cmds.go#L15-L102
|
func Cmds(noMetrics *bool, noPortForwarding *bool) []*cobra.Command {
var commands []*cobra.Command
var noObjects bool
var url string
extract := &cobra.Command{
Short: "Extract Pachyderm state to stdout or an object store bucket.",
Long: "Extract Pachyderm state to stdout or an object store bucket.",
Example: `
# Extract into a local file:
$ {{alias}} > backup
# Extract to s3:
$ {{alias}} -u s3://bucket/backup`,
Run: cmdutil.RunFixedArgs(0, func(args []string) (retErr error) {
c, err := client.NewOnUserMachine(!*noMetrics, !*noPortForwarding, "user")
if err != nil {
return err
}
defer c.Close()
if url != "" {
return c.ExtractURL(url)
}
w := snappy.NewBufferedWriter(os.Stdout)
defer func() {
if err := w.Close(); err != nil && retErr == nil {
retErr = err
}
}()
return c.ExtractWriter(!noObjects, w)
}),
}
extract.Flags().BoolVar(&noObjects, "no-objects", false, "don't extract from object storage, only extract data from etcd")
extract.Flags().StringVarP(&url, "url", "u", "", "An object storage url (i.e. s3://...) to extract to.")
commands = append(commands, cmdutil.CreateAlias(extract, "extract"))
restore := &cobra.Command{
Short: "Restore Pachyderm state from stdin or an object store.",
Long: "Restore Pachyderm state from stdin or an object store.",
Example: `
# Restore from a local file:
$ {{alias}} < backup
# Restore from s3:
$ {{alias}} -u s3://bucket/backup`,
Run: cmdutil.RunFixedArgs(0, func(args []string) error {
c, err := client.NewOnUserMachine(!*noMetrics, !*noPortForwarding, "user")
if err != nil {
return err
}
defer c.Close()
if url != "" {
err = c.RestoreURL(url)
} else {
err = c.RestoreReader(snappy.NewReader(os.Stdin))
}
if err != nil {
return fmt.Errorf("%v\nWARNING: Your cluster might be in an invalid "+
"state--consider deleting partially-restored data before continuing",
err)
}
return nil
}),
}
restore.Flags().StringVarP(&url, "url", "u", "", "An object storage url (i.e. s3://...) to restore from.")
commands = append(commands, cmdutil.CreateAlias(restore, "restore"))
inspectCluster := &cobra.Command{
Short: "Returns info about the pachyderm cluster",
Long: "Returns info about the pachyderm cluster",
Run: cmdutil.RunFixedArgs(0, func(args []string) error {
c, err := client.NewOnUserMachine(!*noMetrics, !*noPortForwarding, "user")
if err != nil {
return err
}
defer c.Close()
ci, err := c.InspectCluster()
if err != nil {
return err
}
fmt.Println(ci.ID)
return nil
}),
}
commands = append(commands, cmdutil.CreateAlias(inspectCluster, "inspect cluster"))
return commands
}
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/options.go#L497-L506
|
func normalizeOption(src Option) Option {
switch opts := flattenOptions(nil, Options{src}); len(opts) {
case 0:
return nil
case 1:
return opts[0]
default:
return opts
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/network.go#L57-L128
|
func (e *Endpoints) NetworkUpdateAddress(address string) error {
if address != "" {
address = util.CanonicalNetworkAddress(address)
}
oldAddress := e.NetworkAddress()
if address == oldAddress {
return nil
}
clusterAddress := e.ClusterAddress()
logger.Infof("Update network address")
e.mu.Lock()
defer e.mu.Unlock()
// Close the previous socket
e.closeListener(network)
// If turning off listening, we're done.
if address == "" {
return nil
}
// If the new address covers the cluster one, turn off the cluster
// listener.
if clusterAddress != "" && util.IsAddressCovered(clusterAddress, address) {
e.closeListener(cluster)
}
// Attempt to setup the new listening socket
getListener := func(address string) (*net.Listener, error) {
var err error
var listener net.Listener
for i := 0; i < 10; i++ { // Ten retries over a second seems reasonable.
listener, err = net.Listen("tcp", address)
if err == nil {
break
}
time.Sleep(100 * time.Millisecond)
}
if err != nil {
return nil, fmt.Errorf("cannot listen on https socket: %v", err)
}
return &listener, nil
}
// If setting a new address, setup the listener
if address != "" {
listener, err := getListener(address)
if err != nil {
// Attempt to revert to the previous address
listener, err1 := getListener(oldAddress)
if err1 == nil {
e.listeners[network] = networkTLSListener(*listener, e.cert)
e.serveHTTP(network)
}
return err
}
e.listeners[network] = networkTLSListener(*listener, e.cert)
e.serveHTTP(network)
}
return nil
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L161-L168
|
func (r *InclusiveRange) Min() int {
start := r.Start()
end := r.End()
if start < end {
return start
}
return end
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/local_peer.go#L24-L33
|
func newLocalPeer(name PeerName, nickName string, router *Router) *localPeer {
actionChan := make(chan localPeerAction, ChannelSize)
peer := &localPeer{
Peer: newPeer(name, nickName, randomPeerUID(), 0, randomPeerShortID()),
router: router,
actionChan: actionChan,
}
go peer.actorLoop(actionChan)
return peer
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pkg/tracing/tracing.go#L78-L128
|
func InstallJaegerTracerFromEnv() {
jaegerOnce.Do(func() {
jaegerEndpoint, onUserMachine := os.LookupEnv(jaegerEndpointEnvVar)
if !onUserMachine {
if host, ok := os.LookupEnv("JAEGER_COLLECTOR_SERVICE_HOST"); ok {
port := os.Getenv("JAEGER_COLLECTOR_SERVICE_PORT_JAEGER_COLLECTOR_HTTP")
jaegerEndpoint = fmt.Sprintf("%s:%s", host, port)
}
}
if jaegerEndpoint == "" {
return // break early -- not using Jaeger
}
// canonicalize jaegerEndpoint as http://<hostport>/api/traces
jaegerEndpoint = strings.TrimPrefix(jaegerEndpoint, "http://")
jaegerEndpoint = strings.TrimSuffix(jaegerEndpoint, "/api/traces")
jaegerEndpoint = fmt.Sprintf("http://%s/api/traces", jaegerEndpoint)
cfg := jaegercfg.Configuration{
// Configure Jaeger to sample every call, but use the SpanInclusionFunc
// addTraceIfTracingEnabled (defined below) to skip sampling every RPC
// unless the PACH_ENABLE_TRACING environment variable is set
Sampler: &jaegercfg.SamplerConfig{
Type: "const",
Param: 1,
},
Reporter: &jaegercfg.ReporterConfig{
LogSpans: true,
BufferFlushInterval: 1 * time.Second,
CollectorEndpoint: jaegerEndpoint,
},
}
// configure jaeger logger
logger := jaeger.Logger(jaeger.NullLogger)
if !onUserMachine {
logger = jaeger.StdLogger
}
// Hack: ignore second argument (io.Closer) because the Jaeger
// implementation of opentracing.Tracer also implements io.Closer (i.e. the
// first and second return values from cfg.New(), here, are two interfaces
// that wrap the same underlying type). Instead of storing the second return
// value here, just cast the tracer to io.Closer in CloseAndReportTraces()
// (below) and call 'Close()' on it there.
tracer, _, err := cfg.New(JaegerServiceName, jaegercfg.Logger(logger))
if err != nil {
panic(fmt.Sprintf("could not install Jaeger tracer: %v", err))
}
opentracing.SetGlobalTracer(tracer)
})
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L736-L739
|
func (p RunScriptParams) WithSilent(silent bool) *RunScriptParams {
p.Silent = silent
return &p
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/data_types.go#L263-L280
|
func (p *ActionParam) Signature() (sig string) {
switch t := p.Type.(type) {
case *BasicDataType:
sig = string(*t)
case *ArrayDataType:
cs := t.ElemType.Signature()
sig = fmt.Sprintf("[]%s", cs)
case *ObjectDataType:
sig = fmt.Sprintf("*%s", t.TypeName)
case *EnumerableDataType:
sig = "map[string]interface{}"
case *UploadDataType:
sig = "*rsapi.FileUpload"
case *SourceUploadDataType:
sig = "*rsapi.SourceUpload"
}
return
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/loadbalancer.go#L72-L77
|
func (c *Client) GetLoadbalancer(dcid, lbalid string) (*Loadbalancer, error) {
url := lbalPath(dcid, lbalid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty)
ret := &Loadbalancer{}
err := c.client.Get(url, ret, http.StatusOK)
return ret, err
}
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/filehandler.go#L222-L225
|
func (h *TimeRotatingFileHandler) Write(b []byte) (n int, err error) {
h.doRollover()
return h.fd.Write(b)
}
|
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/read.go#L670-L685
|
func (v Value) Keys() []string {
x, ok := v.data.(dict)
if !ok {
strm, ok := v.data.(stream)
if !ok {
return nil
}
x = strm.hdr
}
keys := []string{} // not nil
for k := range x {
keys = append(keys, string(k))
}
sort.Strings(keys)
return keys
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/main.go#L44-L57
|
func SafeUnmarshal(data []byte, dest interface{}) error {
r := bytes.NewReader(data)
n, err := Unmarshal(r, dest)
if err != nil {
return err
}
if n != len(data) {
return fmt.Errorf("input not fully consumed. expected to read: %d, actual: %d", len(data), n)
}
return nil
}
|
https://github.com/brankas/sentinel/blob/0ff081867c31a45cb71f5976ea6144fd06a557b5/opts.go#L83-L95
|
func Sigs(sigs ...os.Signal) Option {
return func(s *Sentinel) error {
s.Lock()
defer s.Unlock()
if s.started {
return ErrAlreadyStarted
}
s.shutdownSigs = sigs
return nil
}
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/datastore.go#L369-L375
|
func Delete(c context.Context, key *Key) error {
err := DeleteMulti(c, []*Key{key})
if me, ok := err.(appengine.MultiError); ok {
return me[0]
}
return err
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssc/codegen_client.go#L1474-L1476
|
func (r *UserPreferenceInfo) Locator(api *API) *UserPreferenceInfoLocator {
return api.UserPreferenceInfoLocator(r.Href)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/fetch.go#L133-L136
|
func (p FulfillRequestParams) WithResponsePhrase(responsePhrase string) *FulfillRequestParams {
p.ResponsePhrase = responsePhrase
return &p
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L6255-L6259
|
func (v *EventFrameAttached) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage66(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/heapprofiler.go#L320-L323
|
func (p TakeHeapSnapshotParams) WithReportProgress(reportProgress bool) *TakeHeapSnapshotParams {
p.ReportProgress = reportProgress
return &p
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/images.go#L394-L463
|
func (c *Cluster) imageFill(id int, image *api.Image, create, expire, used, upload *time.Time, arch int) error {
// Some of the dates can be nil in the DB, let's process them.
if create != nil {
image.CreatedAt = *create
} else {
image.CreatedAt = time.Time{}
}
if expire != nil {
image.ExpiresAt = *expire
} else {
image.ExpiresAt = time.Time{}
}
if used != nil {
image.LastUsedAt = *used
} else {
image.LastUsedAt = time.Time{}
}
image.Architecture, _ = osarch.ArchitectureName(arch)
// The upload date is enforced by NOT NULL in the schema, so it can never be nil.
image.UploadedAt = *upload
// Get the properties
q := "SELECT key, value FROM images_properties where image_id=?"
var key, value, name, desc string
inargs := []interface{}{id}
outfmt := []interface{}{key, value}
results, err := queryScan(c.db, q, inargs, outfmt)
if err != nil {
return err
}
properties := map[string]string{}
for _, r := range results {
key = r[0].(string)
value = r[1].(string)
properties[key] = value
}
image.Properties = properties
// Get the aliases
q = "SELECT name, description FROM images_aliases WHERE image_id=?"
inargs = []interface{}{id}
outfmt = []interface{}{name, desc}
results, err = queryScan(c.db, q, inargs, outfmt)
if err != nil {
return err
}
aliases := []api.ImageAlias{}
for _, r := range results {
name = r[0].(string)
desc = r[1].(string)
a := api.ImageAlias{Name: name, Description: desc}
aliases = append(aliases, a)
}
image.Aliases = aliases
_, source, err := c.ImageSourceGet(id)
if err == nil {
image.UpdateSource = &source
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/easyjson.go#L1094-L1098
|
func (v *HighlightNodeParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoOverlay11(&r, v)
return r.Error()
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/surrogate_gossiper.go#L44-L69
|
func (s *surrogateGossiper) OnGossip(update []byte) (GossipData, error) {
hash := fnv.New64a()
_, _ = hash.Write(update)
updateHash := hash.Sum64()
s.Lock()
defer s.Unlock()
for _, p := range s.prevUpdates {
if updateHash == p.hash && bytes.Equal(update, p.update) {
return nil, nil
}
}
// Delete anything that's older than the gossip interval, so we don't grow forever
// (this time limit is arbitrary; surrogateGossiper should pass on new gossip immediately
// so there should be no reason for a duplicate to show up after a long time)
updateTime := now()
deleteBefore := updateTime.Add(-gossipInterval)
keepFrom := len(s.prevUpdates)
for i, p := range s.prevUpdates {
if p.t.After(deleteBefore) {
keepFrom = i
break
}
}
s.prevUpdates = append(s.prevUpdates[keepFrom:], prevUpdate{update, updateHash, updateTime})
return newSurrogateGossipData(update), nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L455-L458
|
func (p GetDocumentParams) WithPierce(pierce bool) *GetDocumentParams {
p.Pierce = pierce
return &p
}
|
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/s3gof3r.go#L31-L51
|
func (s *S3) Region() string {
region := os.Getenv("AWS_REGION")
switch s.Domain {
case "s3.amazonaws.com", "s3-external-1.amazonaws.com":
return "us-east-1"
case "s3-accelerate.amazonaws.com":
if region == "" {
panic("can't find endpoint region")
}
return region
default:
regions := regionMatcher.FindStringSubmatch(s.Domain)
if len(regions) < 2 {
if region == "" {
panic("can't find endpoint region")
}
return region
}
return regions[1]
}
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/route_mappings.go#L92-L98
|
func (a *App) ServeFiles(p string, root http.FileSystem) {
path := path.Join(a.Prefix, p)
a.filepaths = append(a.filepaths, path)
h := stripAsset(path, a.fileServer(root), a)
a.router.PathPrefix(path).Handler(h)
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/compression/compression.go#L25-L27
|
func Bzip2Decompressor(r io.Reader) (io.ReadCloser, error) {
return ioutil.NopCloser(bzip2.NewReader(r)), nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/balancer/resolver/endpoint/endpoint.go#L82-L90
|
func (e *ResolverGroup) SetEndpoints(endpoints []string) {
addrs := epsToAddrs(endpoints...)
e.mu.Lock()
e.endpoints = endpoints
for _, r := range e.resolvers {
r.cc.NewAddress(addrs)
}
e.mu.Unlock()
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/replication.go#L488-L500
|
func (r *Raft) setupAppendEntries(s *followerReplication, req *AppendEntriesRequest, nextIndex, lastIndex uint64) error {
req.RPCHeader = r.getRPCHeader()
req.Term = s.currentTerm
req.Leader = r.trans.EncodePeer(r.localID, r.localAddr)
req.LeaderCommitIndex = r.getCommitIndex()
if err := r.setPreviousLog(req, nextIndex); err != nil {
return err
}
if err := r.setNewLogs(req, nextIndex, lastIndex); err != nil {
return err
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L7340-L7344
|
func (v BringToFrontParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage81(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/iterator.go#L100-L104
|
func (it *Iterator) Close() {
it.snap.Close()
it.snap.db.store.FreeBuf(it.buf)
it.iter.Close()
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/volume.go#L74-L79
|
func (c *Client) UpdateVolume(dcid string, volid string, request VolumeProperties) (*Volume, error) {
url := volumePath(dcid, volid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty)
ret := &Volume{}
err := c.client.Patch(url, request, ret, http.StatusAccepted)
return ret, err
}
|
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/view/template.go#L70-L84
|
func Text(name, contentType, charSet string) template {
if textTemp.Template == nil {
panic("Function `InitTextTemplates` should be called first.")
}
if contentType == "" {
contentType = ContentTypePlain
}
if charSet == "" {
charSet = CharSetUTF8
}
header := make(http.Header)
header.Set("Content-Type",
fmt.Sprintf("%s; charset=%s", contentType, charSet))
return template{&textTemp, name, header}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L629-L637
|
func (r *ProtocolLXD) DeleteImage(fingerprint string) (Operation, error) {
// Send the request
op, _, err := r.queryOperation("DELETE", fmt.Sprintf("/images/%s", url.QueryEscape(fingerprint)), nil, "")
if err != nil {
return nil, err
}
return op, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/watch.go#L651-L659
|
func (w *watchGrpcStream) nextResume() *watcherStream {
for len(w.resuming) != 0 {
if w.resuming[0] != nil {
return w.resuming[0]
}
w.resuming = w.resuming[1:len(w.resuming)]
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L2166-L2170
|
func (v ScriptPosition) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDebugger22(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/delicb/gstring/blob/77637d5e476b8e22d81f6a7bc5311a836dceb1c2/gstring.go#L116-L119
|
func Fprintm(w io.Writer, format string, args map[string]interface{}) (n int, err error) {
f, a := gformat(format, args)
return fmt.Fprintf(w, f, a...)
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/rsapi.go#L107-L163
|
func FromCommandLine(cmdLine *cmd.CommandLine) (*API, error) {
var client *API
ss := strings.HasPrefix(cmdLine.Command, "ss")
if cmdLine.RL10 {
var err error
if client, err = NewRL10(); err != nil {
return nil, err
}
} else if cmdLine.OAuthToken != "" {
auth := NewOAuthAuthenticator(cmdLine.OAuthToken, cmdLine.Account)
if ss {
auth = NewSSAuthenticator(auth, cmdLine.Account)
}
client = New(cmdLine.Host, auth)
} else if cmdLine.OAuthAccessToken != "" {
auth := NewTokenAuthenticator(cmdLine.OAuthAccessToken, cmdLine.Account)
if ss {
auth = NewSSAuthenticator(auth, cmdLine.Account)
}
client = New(cmdLine.Host, auth)
} else if cmdLine.APIToken != "" {
auth := NewInstanceAuthenticator(cmdLine.APIToken, cmdLine.Account)
if ss {
auth = NewSSAuthenticator(auth, cmdLine.Account)
}
client = New(cmdLine.Host, auth)
} else if cmdLine.Username != "" && cmdLine.Password != "" {
auth := NewBasicAuthenticator(cmdLine.Username, cmdLine.Password, cmdLine.Account)
if ss {
auth = NewSSAuthenticator(auth, cmdLine.Account)
}
client = New(cmdLine.Host, auth)
} else {
// No auth, used by tests
client = New(cmdLine.Host, nil)
httpclient.Insecure = true
}
if !cmdLine.ShowHelp && !cmdLine.NoAuth {
if cmdLine.OAuthToken == "" && cmdLine.OAuthAccessToken == "" && cmdLine.APIToken == "" && cmdLine.Username == "" && !cmdLine.RL10 {
return nil, fmt.Errorf("Missing authentication information, use '--email EMAIL --password PWD', '--token TOKEN' or 'setup'")
}
if cmdLine.Verbose || cmdLine.Dump == "debug" {
httpclient.DumpFormat = httpclient.Debug
}
if cmdLine.Dump == "json" {
httpclient.DumpFormat = httpclient.JSON
}
if cmdLine.Dump == "record" {
httpclient.DumpFormat = httpclient.JSON | httpclient.Record
}
if cmdLine.Verbose {
httpclient.DumpFormat |= httpclient.Verbose
}
client.FetchLocationResource = cmdLine.FetchResource
}
return client, nil
}
|
https://github.com/olorin/nagiosplugin/blob/893f9702af4ea1e2dc4cd6528cbdcdb3dc7ca064/perfdata.go#L110-L121
|
func RenderPerfdata(perfdata []PerfDatum) string {
value := ""
if len(perfdata) == 0 {
return value
}
// Demarcate start of perfdata in check output.
value += " |"
for _, datum := range perfdata {
value += fmt.Sprintf(" %v", datum)
}
return value
}
|
https://github.com/jayeshsolanki93/devgorant/blob/69fb03e5c3b1da904aacf77240e04d85dd8e1c3c/devrant.go#L84-L96
|
func (c *Client) Search(term string) ([]RantModel, error) {
url := fmt.Sprintf(SEARCH_PATH, API, term, APP_VERSION)
res, err := http.Get(url)
if err != nil {
return nil, err
}
var data SearchResponse
json.NewDecoder(res.Body).Decode(&data)
if !data.Success && data.Error != "" {
return nil, errors.New(data.Error)
}
return data.Rants, nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.