_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L210-L214
|
func (v *TypeObject) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoProfiler1(&r, v)
return r.Error()
}
|
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/pdclient/get_requestid_from_task.go#L10-L38
|
func GetRequestIDFromTaskResponse(taskResponse TaskResponse) (requestID string, err error) {
var provisionHostInfoBytes []byte
firstRecordIndex := 0
meta := taskResponse.MetaData
provisionHostInfo := ProvisionHostInfo{}
lo.G.Debug("taskResponse: ", taskResponse)
lo.G.Debug("metadata: ", meta)
if provisionHostInfoBytes, err = json.Marshal(meta[ProvisionHostInformationFieldname]); err == nil {
if err = json.Unmarshal(provisionHostInfoBytes, &provisionHostInfo); err == nil {
if len(provisionHostInfo.Data) > firstRecordIndex {
requestID = provisionHostInfo.Data[firstRecordIndex].RequestID
} else {
lo.G.Error("no request id found in: ", provisionHostInfo)
}
} else {
lo.G.Error("error unmarshalling: ", err, meta)
lo.G.Error("metadata: ", meta)
}
} else {
lo.G.Error("error marshalling: ", err)
}
return
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L280-L285
|
func (s *FileSequence) End() int {
if s.frameSet == nil {
return 0
}
return s.frameSet.End()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/jenkins/jenkins.go#L460-L480
|
func (c *Client) GetJobInfo(spec *prowapi.ProwJobSpec) (*JobInfo, error) {
path := getJobInfoPath(spec)
c.logger.Debugf("getJobInfoPath: %s", path)
data, err := c.Get(path)
if err != nil {
c.logger.Errorf("Failed to get job info: %v", err)
return nil, err
}
var jobInfo JobInfo
if err := json.Unmarshal(data, &jobInfo); err != nil {
return nil, fmt.Errorf("Cannot unmarshal job info from API: %v", err)
}
c.logger.Tracef("JobInfo: %+v", jobInfo)
return &jobInfo, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2auth/auth.go#L601-L638
|
func (rw RWPermission) Revoke(lg *zap.Logger, n RWPermission) (RWPermission, error) {
var out RWPermission
currentRead := types.NewUnsafeSet(rw.Read...)
for _, r := range n.Read {
if !currentRead.Contains(r) {
if lg != nil {
lg.Info(
"revoking ungranted read permission",
zap.String("read-permission", r),
)
} else {
plog.Noticef("revoking ungranted read permission %s", r)
}
continue
}
currentRead.Remove(r)
}
currentWrite := types.NewUnsafeSet(rw.Write...)
for _, w := range n.Write {
if !currentWrite.Contains(w) {
if lg != nil {
lg.Info(
"revoking ungranted write permission",
zap.String("write-permission", w),
)
} else {
plog.Noticef("revoking ungranted write permission %s", w)
}
continue
}
currentWrite.Remove(w)
}
out.Read = currentRead.Values()
out.Write = currentWrite.Values()
sort.Strings(out.Read)
sort.Strings(out.Write)
return out, nil
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nitro.go#L236-L265
|
func (w *Writer) DeleteNode(x *skiplist.Node) (success bool) {
defer func() {
if success {
w.count--
}
}()
x.GClink = nil
sn := w.getCurrSn()
gotItem := (*Item)(x.Item())
if gotItem.bornSn == sn {
success = w.store.DeleteNode(x, w.insCmp, w.buf, &w.slSts1)
barrier := w.store.GetAccesBarrier()
barrier.FlushSession(unsafe.Pointer(x))
return
}
success = atomic.CompareAndSwapUint32(&gotItem.deadSn, 0, sn)
if success {
if w.gctail == nil {
w.gctail = x
w.gchead = w.gctail
} else {
w.gctail.GClink = x
w.gctail = x
}
}
return
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/levels.go#L388-L417
|
func (s *levelsController) pickCompactLevels() (prios []compactionPriority) {
// This function must use identical criteria for guaranteeing compaction's progress that
// addLevel0Table uses.
// cstatus is checked to see if level 0's tables are already being compacted
if !s.cstatus.overlapsWith(0, infRange) && s.isLevel0Compactable() {
pri := compactionPriority{
level: 0,
score: float64(s.levels[0].numTables()) / float64(s.kv.opt.NumLevelZeroTables),
}
prios = append(prios, pri)
}
for i, l := range s.levels[1:] {
// Don't consider those tables that are already being compacted right now.
delSize := s.cstatus.delSize(i + 1)
if l.isCompactable(delSize) {
pri := compactionPriority{
level: i + 1,
score: float64(l.getTotalSize()-delSize) / float64(l.maxTotalSize),
}
prios = append(prios, pri)
}
}
sort.Slice(prios, func(i, j int) bool {
return prios[i].score > prios[j].score
})
return prios
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/portforwarder.go#L208-L223
|
func (f *PortForwarder) Close() {
defer f.logger.Close()
f.stopChansLock.Lock()
defer f.stopChansLock.Unlock()
if f.shutdown {
panic("port forwarder already shutdown")
}
f.shutdown = true
for _, stopChan := range f.stopChans {
close(stopChan)
}
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift-copies.go#L424-L435
|
func (config *directClientConfig) getAuthInfo() clientcmdAuthInfo {
authInfos := config.config.AuthInfos
authInfoName := config.getAuthInfoName()
var mergedAuthInfo clientcmdAuthInfo
if configAuthInfo, exists := authInfos[authInfoName]; exists {
mergo.Merge(&mergedAuthInfo, configAuthInfo)
}
// REMOVED: overrides support
return mergedAuthInfo
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/registry.go#L42-L51
|
func (r *registry) GetAll() []*ErrDescriptor {
r.RLock()
defer r.RUnlock()
res := make([]*ErrDescriptor, 0, len(r.byCode))
for _, d := range r.byCode {
res = append(res, d)
}
return res
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L7626-L7633
|
func (r *Preference) Locator(api *API) *PreferenceLocator {
for _, l := range r.Links {
if l["rel"] == "self" {
return api.PreferenceLocator(l["href"])
}
}
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/elect_command.go#L35-L43
|
func NewElectCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "elect <election-name> [proposal]",
Short: "Observes and participates in leader election",
Run: electCommandFunc,
}
cmd.Flags().BoolVarP(&electListen, "listen", "l", false, "observation mode")
return cmd
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/servers/simple.go#L21-L24
|
func (s *Simple) Start(c context.Context, h http.Handler) error {
s.Handler = h
return s.ListenAndServe()
}
|
https://github.com/omniscale/go-mapnik/blob/710dfcc5e486e5760d0a5c46be909d91968e1ffb/mapnik.go#L151-L155
|
func (m *Map) SetSRS(srs string) {
cs := C.CString(srs)
defer C.free(unsafe.Pointer(cs))
C.mapnik_map_set_srs(m.m, cs)
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/recovery/recovery.go#L77-L130
|
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
debugMsg := fmt.Sprintf(
"%s\n\n%#v\n\n%#v",
debug.Stack(),
r.URL,
r.Header,
)
if h.label != "" {
debugMsg = h.label + "\n\n" + debugMsg
}
h.logf("http recovery handler: %s %s: %s\n%s", r.Method, r.URL.String(), err, debugMsg)
if h.notifier != nil {
go func() {
defer func() {
if err := recover(); err != nil {
h.logf("http recovery handler: notify panic: %v", err)
}
}()
if err := h.notifier.Notify(
fmt.Sprint(
"Panic ",
r.Method,
" ",
r.URL.String(),
": ", err,
),
debugMsg,
); err != nil {
h.logf("http recovery handler: notify: %v", err)
}
}()
}
if h.panicResponseHandler != nil {
h.panicResponseHandler.ServeHTTP(w, r)
return
}
if h.panicContentType != "" {
w.Header().Set("Content-Type", h.panicContentType)
}
w.WriteHeader(http.StatusInternalServerError)
if h.panicBody != "" {
fmt.Fprintln(w, h.panicBody)
}
}
}()
h.handler.ServeHTTP(w, r)
}
|
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/logger.go#L127-L136
|
func Reset() {
// TODO make a global Init() method to be less magic? or make it such that
// if there's no backends at all configured, we could use some tricks to
// automatically setup backends based if we have a TTY or not.
sequenceNo = 0
b := SetBackend(NewLogBackend(os.Stderr, "", log.LstdFlags))
b.SetLevel(DEBUG, "")
SetFormatter(DefaultFormatter)
timeNow = time.Now
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/cmd/tsurud/checker.go#L108-L121
|
func checkScheduler() error {
if servers, err := config.Get("docker:servers"); err == nil && servers != nil {
return errors.Errorf(`Using docker:servers is deprecated, please remove it your config and use "tsuru docker-node-add" do add docker nodes.`)
}
isSegregate, err := config.GetBool("docker:segregate")
if err == nil {
if isSegregate {
return config.NewWarning(`Setting "docker:segregate" is not necessary anymore, this is the default behavior from now on.`)
} else {
return errors.Errorf(`You must remove "docker:segregate" from your config.`)
}
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/types.go#L349-L351
|
func (t CaptureScreenshotFormat) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/auth/server/saml.go#L101-L140
|
func fetchRawIDPMetadata(name string, mdURL *url.URL) ([]byte, error) {
c := http.DefaultClient
req, err := http.NewRequest("GET", mdURL.String(), nil)
if err != nil {
return nil, fmt.Errorf("could not retrieve IdP metadata for %q: %v", name, err)
}
req.Header.Set("User-Agent", "Golang; github.com/pachyderm/pachdyerm")
var rawMetadata []byte
b := backoff.NewInfiniteBackOff()
b.MaxElapsedTime = 30 * time.Second
b.MaxInterval = 2 * time.Second
if err := backoff.RetryNotify(func() error {
resp, err := c.Do(req)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("%d %s", resp.StatusCode, resp.Status)
}
rawMetadata, err = ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return fmt.Errorf("could not read IdP metadata response body: %v", err)
}
if len(rawMetadata) == 0 {
return fmt.Errorf("empty metadata from IdP")
}
return nil
}, b, func(err error, d time.Duration) error {
logrus.Printf("error retrieving IdP metadata: %v; retrying in %v", err, d)
return nil
}); err != nil {
return nil, err
}
// Successfully retrieved metadata
return rawMetadata, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/client/clientset/versioned/clientset.go#L83-L89
|
func NewForConfigOrDie(c *rest.Config) *Clientset {
var cs Clientset
cs.prowV1 = prowv1.NewForConfigOrDie(c)
cs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c)
return &cs
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/objects.go#L11-L30
|
func SelectObjects(stmt *sql.Stmt, dest Dest, args ...interface{}) error {
rows, err := stmt.Query(args...)
if err != nil {
return err
}
defer rows.Close()
for i := 0; rows.Next(); i++ {
err := rows.Scan(dest(i)...)
if err != nil {
return err
}
}
err = rows.Err()
if err != nil {
return err
}
return nil
}
|
https://github.com/fossapps/pushy/blob/4c6045d7a1d3c310d61168ff1ccd5421d5c162f6/pushy.go#L57-L63
|
func (p *Pushy) DevicePresence(deviceID ...string) (*DevicePresenceResponse, *Error, error) {
url := fmt.Sprintf("%s/devices/presence?api_key=%s", p.APIEndpoint, p.APIToken)
var devicePresenceResponse *DevicePresenceResponse
var pushyErr *Error
err := post(p.httpClient, url, DevicePresenceRequest{Tokens: deviceID}, &devicePresenceResponse, &pushyErr)
return devicePresenceResponse, pushyErr, err
}
|
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/datasource/mongo/mongo.go#L78-L85
|
func (m *Mongo) Disconnect() error {
err := m.Client.Disconnect(m.context)
if err != nil {
log.Printf("Impossible de fermer la connexion")
return err
}
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/election.go#L69-L107
|
func (e *Election) Campaign(ctx context.Context, val string) error {
s := e.session
client := e.session.Client()
k := fmt.Sprintf("%s%x", e.keyPrefix, s.Lease())
txn := client.Txn(ctx).If(v3.Compare(v3.CreateRevision(k), "=", 0))
txn = txn.Then(v3.OpPut(k, val, v3.WithLease(s.Lease())))
txn = txn.Else(v3.OpGet(k))
resp, err := txn.Commit()
if err != nil {
return err
}
e.leaderKey, e.leaderRev, e.leaderSession = k, resp.Header.Revision, s
if !resp.Succeeded {
kv := resp.Responses[0].GetResponseRange().Kvs[0]
e.leaderRev = kv.CreateRevision
if string(kv.Value) != val {
if err = e.Proclaim(ctx, val); err != nil {
e.Resign(ctx)
return err
}
}
}
_, err = waitDeletes(ctx, client, e.keyPrefix, e.leaderRev-1)
if err != nil {
// clean up in case of context cancel
select {
case <-ctx.Done():
e.Resign(client.Ctx())
default:
e.leaderSession = nil
}
return err
}
e.hdr = resp.Header
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/target.go#L503-L506
|
func (p SetAutoAttachParams) WithFlatten(flatten bool) *SetAutoAttachParams {
p.Flatten = flatten
return &p
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/client.go#L146-L153
|
func (c *Client) Endpoints() []string {
// copy the slice; protect original endpoints from being changed
c.mu.RLock()
defer c.mu.RUnlock()
eps := make([]string, len(c.cfg.Endpoints))
copy(eps, c.cfg.Endpoints)
return eps
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/flagutil/k8s_client.go#L69-L71
|
func (o *KubernetesClientOptions) ProwJobClient() (versioned.Interface, error) {
return kube.GetProwJobClient(o.masterURL, o.kubeConfig)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.mapper.go#L157-L319
|
func (c *ClusterTx) ContainerList(filter ContainerFilter) ([]Container, error) {
// Result slice.
objects := make([]Container, 0)
// Check which filter criteria are active.
criteria := map[string]interface{}{}
if filter.Project != "" {
criteria["Project"] = filter.Project
}
if filter.Name != "" {
criteria["Name"] = filter.Name
}
if filter.Node != "" {
criteria["Node"] = filter.Node
}
if filter.Parent != "" {
criteria["Parent"] = filter.Parent
}
if filter.Type != -1 {
criteria["Type"] = filter.Type
}
// Pick the prepared statement and arguments to use based on active criteria.
var stmt *sql.Stmt
var args []interface{}
if criteria["Project"] != nil && criteria["Name"] != nil && criteria["Type"] != nil {
stmt = c.stmt(containerObjectsByProjectAndNameAndType)
args = []interface{}{
filter.Project,
filter.Name,
filter.Type,
}
} else if criteria["Project"] != nil && criteria["Type"] != nil && criteria["Parent"] != nil {
stmt = c.stmt(containerObjectsByProjectAndTypeAndParent)
args = []interface{}{
filter.Project,
filter.Type,
len(filter.Parent) + 1,
filter.Parent + "/",
}
} else if criteria["Project"] != nil && criteria["Node"] != nil && criteria["Type"] != nil {
stmt = c.stmt(containerObjectsByProjectAndNodeAndType)
args = []interface{}{
filter.Project,
filter.Node,
filter.Type,
}
} else if criteria["Node"] != nil && criteria["Type"] != nil {
stmt = c.stmt(containerObjectsByNodeAndType)
args = []interface{}{
filter.Node,
filter.Type,
}
} else if criteria["Project"] != nil && criteria["Type"] != nil {
stmt = c.stmt(containerObjectsByProjectAndType)
args = []interface{}{
filter.Project,
filter.Type,
}
} else if criteria["Project"] != nil && criteria["Name"] != nil {
stmt = c.stmt(containerObjectsByProjectAndName)
args = []interface{}{
filter.Project,
filter.Name,
}
} else if criteria["Type"] != nil {
stmt = c.stmt(containerObjectsByType)
args = []interface{}{
filter.Type,
}
} else {
stmt = c.stmt(containerObjects)
args = []interface{}{}
}
// Dest function for scanning a row.
dest := func(i int) []interface{} {
objects = append(objects, Container{})
return []interface{}{
&objects[i].ID,
&objects[i].Project,
&objects[i].Name,
&objects[i].Node,
&objects[i].Type,
&objects[i].Architecture,
&objects[i].Ephemeral,
&objects[i].CreationDate,
&objects[i].Stateful,
&objects[i].LastUseDate,
&objects[i].Description,
&objects[i].ExpiryDate,
}
}
// Select.
err := query.SelectObjects(stmt, dest, args...)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch containers")
}
// Fill field Config.
configObjects, err := c.ContainerConfigRef(filter)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch field Config")
}
for i := range objects {
_, ok := configObjects[objects[i].Project]
if !ok {
subIndex := map[string]map[string]string{}
configObjects[objects[i].Project] = subIndex
}
value := configObjects[objects[i].Project][objects[i].Name]
if value == nil {
value = map[string]string{}
}
objects[i].Config = value
}
// Fill field Devices.
devicesObjects, err := c.ContainerDevicesRef(filter)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch field Devices")
}
for i := range objects {
_, ok := devicesObjects[objects[i].Project]
if !ok {
subIndex := map[string]map[string]map[string]string{}
devicesObjects[objects[i].Project] = subIndex
}
value := devicesObjects[objects[i].Project][objects[i].Name]
if value == nil {
value = map[string]map[string]string{}
}
objects[i].Devices = value
}
// Fill field Profiles.
profilesObjects, err := c.ContainerProfilesRef(filter)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch field Profiles")
}
for i := range objects {
_, ok := profilesObjects[objects[i].Project]
if !ok {
subIndex := map[string][]string{}
profilesObjects[objects[i].Project] = subIndex
}
value := profilesObjects[objects[i].Project][objects[i].Name]
if value == nil {
value = []string{}
}
objects[i].Profiles = value
}
return objects, nil
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/models/task_all_of1.go#L78-L90
|
func (m *TaskAllOf1) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateReason(formats); err != nil {
// prop
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/gitattributes/pattern.go#L41-L65
|
func parsePattern(p string) (Pattern, error) {
res := pattern{}
// negative patterns are forbidden
if strings.HasPrefix(p, negativePrefix) {
return nil, fmt.Errorf("negative patterns are forbidden: <%s>", p)
}
// trailing spaces are ignored unless they are quoted with backslash
if !strings.HasSuffix(p, `\ `) {
p = strings.TrimRight(p, " ")
}
// patterns that match a directory do not recursively match paths inside that directory
if strings.HasSuffix(p, patternDirSep) {
return nil, fmt.Errorf("directory patterns are not matched recursively, use path/** instead: <%s>", p)
}
if strings.Contains(p, patternDirSep) {
res.isPath = true
}
res.pattern = strings.Split(p, patternDirSep)
return &res, nil
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/calloptions.go#L72-L88
|
func (c *CallOptions) overrideHeaders(headers transportHeaders) {
if c.Format != "" {
headers[ArgScheme] = c.Format.String()
}
if c.ShardKey != "" {
headers[ShardKey] = c.ShardKey
}
if c.RoutingKey != "" {
headers[RoutingKey] = c.RoutingKey
}
if c.RoutingDelegate != "" {
headers[RoutingDelegate] = c.RoutingDelegate
}
if c.callerName != "" {
headers[CallerName] = c.callerName
}
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/maintenance/maintenance.go#L66-L71
|
func (s *MemoryStore) Status() (on bool, err error) {
s.mu.Lock()
on = s.on
s.mu.Unlock()
return
}
|
https://github.com/blacklabeldata/namedtuple/blob/c341f1db44f30b8164294aa8605ede42be604aba/schema/lexer.go#L153-L158
|
func (l *Lexer) skipWhitespace() {
for unicode.Is(unicode.White_Space, l.next()) {
}
l.backup()
l.ignore()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/headlessexperimental/easyjson.go#L480-L484
|
func (v *BeginFrameParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoHeadlessexperimental5(&r, v)
return r.Error()
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/mvcc/backend/batch_tx.go#L93-L95
|
func (t *batchTx) UnsafeSeqPut(bucketName []byte, key []byte, value []byte) {
t.unsafePut(bucketName, key, value, true)
}
|
https://github.com/insionng/martini/blob/2d0ba5dc75fe9549c10e2f71927803a11e5e4957/martini.go#L73-L85
|
func (m *Martini) Run() {
port := os.Getenv("PORT")
if port == "" {
port = "9000"
}
host := os.Getenv("HOST")
logger := m.Injector.Get(reflect.TypeOf(m.logger)).Interface().(*log.Logger)
logger.Printf("listening on %s:%s (%s)\n", host, port, Env)
logger.Fatalln(http.ListenAndServe(host+":"+port, m))
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/types.go#L320-L322
|
func (t *CookieSameSite) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cv.go#L116-L124
|
func Inpaint(src, inpaint_mask, dst *IplImage, inpaintRange float64, flags int) {
C.cvInpaint(
unsafe.Pointer(src),
unsafe.Pointer(inpaint_mask),
unsafe.Pointer(dst),
C.double(inpaintRange),
C.int(flags),
)
}
|
https://github.com/google/subcommands/blob/d47216cd17848d55a33e6f651cbe408243ed55b8/subcommands.go#L81-L90
|
func NewCommander(topLevelFlags *flag.FlagSet, name string) *Commander {
cdr := &Commander{
topFlags: topLevelFlags,
name: name,
Output: os.Stdout,
Error: os.Stderr,
}
topLevelFlags.Usage = func() { cdr.explain(cdr.Error) }
return cdr
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/levels.go#L265-L323
|
func (s *levelsController) dropPrefix(prefix []byte) error {
opt := s.kv.opt
for _, l := range s.levels {
l.RLock()
if l.level == 0 {
size := len(l.tables)
l.RUnlock()
if size > 0 {
cp := compactionPriority{
level: 0,
score: 1.74,
// A unique number greater than 1.0 does two things. Helps identify this
// function in logs, and forces a compaction.
dropPrefix: prefix,
}
if err := s.doCompact(cp); err != nil {
opt.Warningf("While compacting level 0: %v", err)
return nil
}
}
continue
}
var tables []*table.Table
for _, table := range l.tables {
var absent bool
switch {
case bytes.HasPrefix(table.Smallest(), prefix):
case bytes.HasPrefix(table.Biggest(), prefix):
case bytes.Compare(prefix, table.Smallest()) > 0 &&
bytes.Compare(prefix, table.Biggest()) < 0:
default:
absent = true
}
if !absent {
tables = append(tables, table)
}
}
l.RUnlock()
if len(tables) == 0 {
continue
}
cd := compactDef{
elog: trace.New(fmt.Sprintf("Badger.L%d", l.level), "Compact"),
thisLevel: l,
nextLevel: l,
top: []*table.Table{},
bot: tables,
dropPrefix: prefix,
}
if err := s.runCompactDef(l.level, cd); err != nil {
opt.Warningf("While running compact def: %+v. Error: %v", cd, err)
return err
}
}
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v3election/v3electionpb/gw/v3election.pb.gw.go#L141-L289
|
func RegisterElectionHandlerClient(ctx context.Context, mux *runtime.ServeMux, client v3electionpb.ElectionClient) error {
mux.Handle("POST", pattern_Election_Campaign_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_Election_Campaign_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Election_Campaign_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Election_Proclaim_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_Election_Proclaim_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Election_Proclaim_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Election_Leader_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_Election_Leader_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Election_Leader_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Election_Observe_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_Election_Observe_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Election_Observe_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Election_Resign_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_Election_Resign_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Election_Resign_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/object.go#L192-L208
|
func (p *Process) ForEachObject(fn func(x Object) bool) {
for _, k := range p.pages {
pt := p.pageTable[k]
for i := range pt {
h := &pt[i]
m := h.mark
for m != 0 {
j := bits.TrailingZeros64(m)
m &= m - 1
x := Object(k)*pageTableSize*heapInfoSize + Object(i)*heapInfoSize + Object(j)*8
if !fn(x) {
return
}
}
}
}
}
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/encoder.go#L109-L111
|
func EncodeFloat32(w io.Writer, f float32) (err error) {
return EncodeUint32(w, math.Float32bits(f))
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/cache.go#L157-L178
|
func (c *FileCache) Set(key string, entity *CacheEntity) error {
path := c.GetCachePath(key)
if err := os.MkdirAll(filepath.Dir(path), 0777); err != nil {
return errors.Wrap(err, "failed to create directory for cache file")
}
// Need to avoid race condition
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
return errors.Wrap(err, "failed to open/create a cache file")
}
defer file.Close()
f := bufio.NewWriter(file)
defer f.Flush()
enc := gob.NewEncoder(f)
if err = enc.Encode(entity); err != nil {
return errors.Wrap(err, "failed to encode Entity via gob")
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L6891-L6895
|
func (v EventLoadingFinished) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork53(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/worker/api_server.go#L240-L257
|
func (logger *taggedLogger) Logf(formatString string, args ...interface{}) {
logger.template.Message = fmt.Sprintf(formatString, args...)
if ts, err := types.TimestampProto(time.Now()); err == nil {
logger.template.Ts = ts
} else {
logger.stderrLog.Printf("could not generate logging timestamp: %s\n", err)
return
}
msg, err := logger.marshaler.MarshalToString(&logger.template)
if err != nil {
logger.stderrLog.Printf("could not marshal %v for logging: %s\n", &logger.template, err)
return
}
fmt.Println(msg)
if logger.putObjClient != nil {
logger.msgCh <- msg + "\n"
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cdp/types.go#L700-L708
|
func (fs FrameState) String() string {
var s []string
for k, v := range frameStateNames {
if fs&k != 0 {
s = append(s, v)
}
}
return "[" + strings.Join(s, " ") + "]"
}
|
https://github.com/antlinker/go-dirtyfilter/blob/533f538ffaa112776b1258c3db63e6f55648e18b/store/memory.go#L88-L96
|
func (ms *MemoryStore) ReadAll() ([]string, error) {
dataKeys := ms.dataStore.Keys()
dataLen := len(dataKeys)
result := make([]string, dataLen)
for i := 0; i < dataLen; i++ {
result[i] = dataKeys[i].(string)
}
return result, nil
}
|
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsAO.go#L235-L254
|
func IndexOf(s string, needle string, start int) int {
l := len(s)
if needle == "" {
if start < 0 {
return 0
} else if start < l {
return start
} else {
return l
}
}
if start < 0 || start > l-1 {
return -1
}
pos := strings.Index(s[start:], needle)
if pos == -1 {
return -1
}
return start + pos
}
|
https://github.com/libp2p/go-libp2p-net/blob/a60cde50df6872512892ca85019341d281f72a42/notifiee.go#L24-L28
|
func (nb *NotifyBundle) Listen(n Network, a ma.Multiaddr) {
if nb.ListenF != nil {
nb.ListenF(n, a)
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/store.go#L644-L668
|
func (s *store) internalGet(nodePath string) (*node, *v2error.Error) {
nodePath = path.Clean(path.Join("/", nodePath))
walkFunc := func(parent *node, name string) (*node, *v2error.Error) {
if !parent.IsDir() {
err := v2error.NewError(v2error.EcodeNotDir, parent.Path, s.CurrentIndex)
return nil, err
}
child, ok := parent.Children[name]
if ok {
return child, nil
}
return nil, v2error.NewError(v2error.EcodeKeyNotFound, path.Join(parent.Path, name), s.CurrentIndex)
}
f, err := s.walk(nodePath, walkFunc)
if err != nil {
return nil, err
}
return f, nil
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nitro.go#L592-L626
|
func (m *Nitro) NewSnapshot() (*Snapshot, error) {
buf := m.snapshots.MakeBuf()
defer m.snapshots.FreeBuf(buf)
// Stitch all local gclists from all writers to create snapshot gclist
var head, tail *skiplist.Node
for w := m.wlist; w != nil; w = w.next {
if tail == nil {
head = w.gchead
tail = w.gctail
} else if w.gchead != nil {
tail.GClink = w.gchead
tail = w.gctail
}
w.gchead = nil
w.gctail = nil
// Update global stats
m.store.Stats.Merge(&w.slSts1)
atomic.AddInt64(&m.itemsCount, w.count)
w.count = 0
}
snap := &Snapshot{db: m, sn: m.getCurrSn(), refCount: 1, count: m.ItemsCount()}
m.snapshots.Insert(unsafe.Pointer(snap), CompareSnapshot, buf, &m.snapshots.Stats)
snap.gclist = head
newSn := atomic.AddUint32(&m.currSn, 1)
if newSn == math.MaxUint32 {
return nil, ErrMaxSnapshotsLimitReached
}
return snap, nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/daemon/daemon_transport.go#L89-L112
|
func NewReference(id digest.Digest, ref reference.Named) (types.ImageReference, error) {
if id != "" && ref != nil {
return nil, errors.New("docker-daemon: reference must not have an image ID and a reference string specified at the same time")
}
if ref != nil {
if reference.IsNameOnly(ref) {
return nil, errors.Errorf("docker-daemon: reference %s has neither a tag nor a digest", reference.FamiliarString(ref))
}
// A github.com/distribution/reference value can have a tag and a digest at the same time!
// Most versions of docker/reference do not handle that (ignoring the tag), so reject such input.
// This MAY be accepted in the future.
// (Even if it were supported, the semantics of policy namespaces are unclear - should we drop
// the tag or the digest first?)
_, isTagged := ref.(reference.NamedTagged)
_, isDigested := ref.(reference.Canonical)
if isTagged && isDigested {
return nil, errors.Errorf("docker-daemon: references with both a tag and digest are currently not supported")
}
}
return daemonReference{
id: id,
ref: ref,
}, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/backgroundservice/easyjson.go#L403-L407
|
func (v *EventMetadata) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoBackgroundservice4(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/layertree/layertree.go#L272-L275
|
func (p ReplaySnapshotParams) WithToStep(toStep int64) *ReplaySnapshotParams {
p.ToStep = toStep
return &p
}
|
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vm.go#L2047-L2052
|
func (v *VM) SetAnnotation(text string) error {
return v.updateVMX(func(model *vmx.VirtualMachine) error {
model.Annotation = text
return nil
})
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/models/task_wrapper.go#L63-L68
|
func (m *TaskWrapper) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/integration/cluster.go#L1152-L1157
|
func (m *member) InjectPartition(t testing.TB, others ...*member) {
for _, other := range others {
m.s.CutPeer(other.s.ID())
other.s.CutPeer(m.s.ID())
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L2897-L2901
|
func (v GetResourceTreeReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage30(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5117-L5125
|
func (u LedgerKey) MustOffer() LedgerKeyOffer {
val, ok := u.GetOffer()
if !ok {
panic("arm Offer is not set")
}
return val
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4102-L4110
|
func (u OperationResultTr) MustSetOptionsResult() SetOptionsResult {
val, ok := u.GetSetOptionsResult()
if !ok {
panic("arm SetOptionsResult is not set")
}
return val
}
|
https://github.com/ipfs/go-ipfs-api/blob/a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32/options/dag.go#L15-L30
|
func DagPutOptions(opts ...DagPutOption) (*DagPutSettings, error) {
options := &DagPutSettings{
InputEnc: "json",
Kind: "cbor",
Pin: "false",
Hash: "sha2-256",
}
for _, opt := range opts {
err := opt(options)
if err != nil {
return nil, err
}
}
return options, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L1464-L1468
|
func (v RemoveNodeParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom15(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/target.go#L403-L412
|
func (p *GetTargetInfoParams) Do(ctx context.Context) (targetInfo *Info, err error) {
// execute
var res GetTargetInfoReturns
err = cdp.Execute(ctx, CommandGetTargetInfo, p, &res)
if err != nil {
return nil, err
}
return res.TargetInfo, nil
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/middleware.go#L70-L72
|
func (ms *MiddlewareStack) Use(mw ...MiddlewareFunc) {
ms.stack = append(ms.stack, mw...)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/util_linux_cgo.go#L311-L355
|
func UserId(name string) (int, error) {
var pw C.struct_passwd
var result *C.struct_passwd
bufSize := C.sysconf(C._SC_GETPW_R_SIZE_MAX)
if bufSize < 0 {
bufSize = 4096
}
buf := C.malloc(C.size_t(bufSize))
if buf == nil {
return -1, fmt.Errorf("allocation failed")
}
defer C.free(buf)
cname := C.CString(name)
defer C.free(unsafe.Pointer(cname))
again:
rv, errno := C.getpwnam_r(cname,
&pw,
(*C.char)(buf),
C.size_t(bufSize),
&result)
if rv < 0 {
// OOM killer will take care of us if we end up doing this too
// often.
if errno == syscall.ERANGE {
bufSize *= 2
tmp := C.realloc(buf, C.size_t(bufSize))
if tmp == nil {
return -1, fmt.Errorf("allocation failed")
}
buf = tmp
goto again
}
return -1, fmt.Errorf("failed user lookup: %s", syscall.Errno(rv))
}
if result == nil {
return -1, fmt.Errorf("unknown user %s", name)
}
return int(C.int(result.pw_uid)), nil
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/server.go#L144-L155
|
func (c *Client) AttachVolume(dcid string, srvid string, volid string) (*Volume, error) {
data := struct {
ID string `json:"id,omitempty"`
}{
volid,
}
url := serverVolumeColPath(dcid, srvid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty)
ret := &Volume{}
err := c.client.Post(url, data, ret, http.StatusAccepted)
return ret, err
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/raft.go#L1164-L1251
|
func (r *Raft) requestVote(rpc RPC, req *RequestVoteRequest) {
defer metrics.MeasureSince([]string{"raft", "rpc", "requestVote"}, time.Now())
r.observe(*req)
// Setup a response
resp := &RequestVoteResponse{
RPCHeader: r.getRPCHeader(),
Term: r.getCurrentTerm(),
Granted: false,
}
var rpcErr error
defer func() {
rpc.Respond(resp, rpcErr)
}()
// Version 0 servers will panic unless the peers is present. It's only
// used on them to produce a warning message.
if r.protocolVersion < 2 {
resp.Peers = encodePeers(r.configurations.latest, r.trans)
}
// Check if we have an existing leader [who's not the candidate]
candidate := r.trans.DecodePeer(req.Candidate)
if leader := r.Leader(); leader != "" && leader != candidate {
r.logger.Warn(fmt.Sprintf("Rejecting vote request from %v since we have a leader: %v",
candidate, leader))
return
}
// Ignore an older term
if req.Term < r.getCurrentTerm() {
return
}
// Increase the term if we see a newer one
if req.Term > r.getCurrentTerm() {
// Ensure transition to follower
r.setState(Follower)
r.setCurrentTerm(req.Term)
resp.Term = req.Term
}
// Check if we have voted yet
lastVoteTerm, err := r.stable.GetUint64(keyLastVoteTerm)
if err != nil && err.Error() != "not found" {
r.logger.Error(fmt.Sprintf("Failed to get last vote term: %v", err))
return
}
lastVoteCandBytes, err := r.stable.Get(keyLastVoteCand)
if err != nil && err.Error() != "not found" {
r.logger.Error(fmt.Sprintf("Failed to get last vote candidate: %v", err))
return
}
// Check if we've voted in this election before
if lastVoteTerm == req.Term && lastVoteCandBytes != nil {
r.logger.Info(fmt.Sprintf("Duplicate RequestVote for same term: %d", req.Term))
if bytes.Compare(lastVoteCandBytes, req.Candidate) == 0 {
r.logger.Warn(fmt.Sprintf("Duplicate RequestVote from candidate: %s", req.Candidate))
resp.Granted = true
}
return
}
// Reject if their term is older
lastIdx, lastTerm := r.getLastEntry()
if lastTerm > req.LastLogTerm {
r.logger.Warn(fmt.Sprintf("Rejecting vote request from %v since our last term is greater (%d, %d)",
candidate, lastTerm, req.LastLogTerm))
return
}
if lastTerm == req.LastLogTerm && lastIdx > req.LastLogIndex {
r.logger.Warn(fmt.Sprintf("Rejecting vote request from %v since our last index is greater (%d, %d)",
candidate, lastIdx, req.LastLogIndex))
return
}
// Persist a vote for safety
if err := r.persistVote(req.Term, req.Candidate); err != nil {
r.logger.Error(fmt.Sprintf("Failed to persist vote: %v", err))
return
}
resp.Granted = true
r.setLastContact()
return
}
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L311-L313
|
func (l *Logger) Debugln(args ...interface{}) {
l.Output(2, LevelDebug, fmt.Sprintln(args...))
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/error_registry.go#L48-L57
|
func (r *MapErrorRegistry) AddError(code int, err error) error {
if _, ok := r.errors[code]; ok {
return ErrErrorAlreadyRegistered
}
if _, ok := r.handlers[code]; ok {
return ErrErrorAlreadyRegistered
}
r.errors[code] = err
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/easyjson.go#L1652-L1656
|
func (v CrashGpuProcessParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoBrowser18(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/context_builder.go#L94-L98
|
func (cb *ContextBuilder) SetHeaders(headers map[string]string) *ContextBuilder {
cb.Headers = headers
cb.replaceParentHeaders = true
return cb
}
|
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/envelope.go#L275-L342
|
func parseMultiPartBody(root *Part, e *Envelope) error {
// Parse top-level multipart
ctype := root.Header.Get(hnContentType)
mediatype, params, _, err := parseMediaType(ctype)
if err != nil {
return fmt.Errorf("Unable to parse media type: %v", err)
}
if !strings.HasPrefix(mediatype, ctMultipartPrefix) {
return fmt.Errorf("Unknown mediatype: %v", mediatype)
}
boundary := params[hpBoundary]
if boundary == "" {
return fmt.Errorf("Unable to locate boundary param in Content-Type header")
}
// Locate text body
if mediatype == ctMultipartAltern {
p := root.BreadthMatchFirst(func(p *Part) bool {
return p.ContentType == ctTextPlain && p.Disposition != cdAttachment
})
if p != nil {
e.Text = string(p.Content)
}
} else {
// multipart is of a mixed type
parts := root.DepthMatchAll(func(p *Part) bool {
return p.ContentType == ctTextPlain && p.Disposition != cdAttachment
})
for i, p := range parts {
if i > 0 {
e.Text += "\n--\n"
}
e.Text += string(p.Content)
}
}
// Locate HTML body
p := root.BreadthMatchFirst(matchHTMLBodyPart)
if p != nil {
e.HTML += string(p.Content)
}
// Locate attachments
e.Attachments = root.BreadthMatchAll(func(p *Part) bool {
return p.Disposition == cdAttachment || p.ContentType == ctAppOctetStream
})
// Locate inlines
e.Inlines = root.BreadthMatchAll(func(p *Part) bool {
return p.Disposition == cdInline && !strings.HasPrefix(p.ContentType, ctMultipartPrefix)
})
// Locate others parts not considered in attachments or inlines
e.OtherParts = root.BreadthMatchAll(func(p *Part) bool {
if strings.HasPrefix(p.ContentType, ctMultipartPrefix) {
return false
}
if p.Disposition != "" {
return false
}
if p.ContentType == ctAppOctetStream {
return false
}
return p.ContentType != ctTextPlain && p.ContentType != ctTextHTML
})
return nil
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/genny/build/cleanup.go#L14-L46
|
func Cleanup(opts *Options) genny.RunFn {
return func(r *genny.Runner) error {
defer os.RemoveAll(filepath.Join(opts.Root, "a"))
if err := jam.Clean(); err != nil {
return err
}
var err error
opts.rollback.Range(func(k, v interface{}) bool {
f := genny.NewFileS(k.(string), v.(string))
r.Logger.Debugf("Rollback: %s", f.Name())
if err = r.File(f); err != nil {
return false
}
r.Disk.Remove(f.Name())
return true
})
if err != nil {
return err
}
for _, f := range r.Disk.Files() {
if err := r.Disk.Delete(f.Name()); err != nil {
return err
}
}
if envy.Mods() {
if err := r.Exec(exec.Command(genny.GoBin(), "mod", "tidy")); err != nil {
return err
}
}
return nil
}
}
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/status.go#L23-L52
|
func (mw *StatusMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc {
mw.start = time.Now()
mw.pid = os.Getpid()
mw.responseCounts = map[string]int{}
mw.totalResponseTime = time.Time{}
return func(w ResponseWriter, r *Request) {
// call the handler
h(w, r)
if r.Env["STATUS_CODE"] == nil {
log.Fatal("StatusMiddleware: Env[\"STATUS_CODE\"] is nil, " +
"RecorderMiddleware may not be in the wrapped Middlewares.")
}
statusCode := r.Env["STATUS_CODE"].(int)
if r.Env["ELAPSED_TIME"] == nil {
log.Fatal("StatusMiddleware: Env[\"ELAPSED_TIME\"] is nil, " +
"TimerMiddleware may not be in the wrapped Middlewares.")
}
responseTime := r.Env["ELAPSED_TIME"].(*time.Duration)
mw.lock.Lock()
mw.responseCounts[fmt.Sprintf("%d", statusCode)]++
mw.totalResponseTime = mw.totalResponseTime.Add(*responseTime)
mw.lock.Unlock()
}
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ca/cac/codegen_client.go#L2736-L2782
|
func (loc *ReservedInstancePurchaseLocator) Create(autoRenew bool, duration int, offeringType string, quantity int, startDate *time.Time, options rsapi.APIParams) (*ReservedInstancePurchaseLocator, error) {
var res *ReservedInstancePurchaseLocator
if offeringType == "" {
return res, fmt.Errorf("offeringType is required")
}
var params rsapi.APIParams
params = rsapi.APIParams{}
var viewOpt = options["view"]
if viewOpt != nil {
params["view"] = viewOpt
}
var p rsapi.APIParams
p = rsapi.APIParams{
"auto_renew": autoRenew,
"duration": duration,
"offering_type": offeringType,
"quantity": quantity,
"start_date": startDate,
}
uri, err := loc.ActionPath("ReservedInstancePurchase", "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 &ReservedInstancePurchaseLocator{Href(location), loc.api}, nil
}
}
|
https://github.com/gernest/mention/blob/d48aa4355f942e79e1a4ac2bd08c5c46371b78ca/mention.go#L66-L72
|
func GetTagsAsUniqueStrings(prefix rune, str string, terminator ...rune) (strs []string) {
tags := GetTags(prefix, str, terminator...)
for _, tag := range tags {
strs = append(strs, tag.Tag)
}
return uniquify(strs)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/cancel/canceler.go#L52-L73
|
func CancelableDownload(c *Canceler, client *http.Client, req *http.Request) (*http.Response, chan bool, error) {
chDone := make(chan bool)
chCancel := make(chan struct{})
if c != nil {
c.lock.Lock()
c.reqChCancel[req] = chCancel
c.lock.Unlock()
}
req.Cancel = chCancel
go func() {
<-chDone
if c != nil {
c.lock.Lock()
delete(c.reqChCancel, req)
c.lock.Unlock()
}
}()
resp, err := client.Do(req)
return resp, chDone, err
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L121-L127
|
func LimitFromMetadata(md metadata.MD) (uint64, error) {
limit, ok := md["limit"]
if !ok || len(limit) == 0 {
return 0, nil
}
return strconv.ParseUint(limit[0], 10, 64)
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/backup.go#L34-L38
|
func (db *DB) Backup(w io.Writer, since uint64) (uint64, error) {
stream := db.NewStream()
stream.LogPrefix = "DB.Backup"
return stream.Backup(w, since)
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/healthcheck.go#L21-L28
|
func healthcheck(w http.ResponseWriter, r *http.Request) {
var checks []string
values := r.URL.Query()
if values != nil {
checks = values["check"]
}
fullHealthcheck(w, checks)
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/service/service_instance.go#L562-L581
|
func ProxyInstance(instance *ServiceInstance, path string, evt *event.Event, requestID string, w http.ResponseWriter, r *http.Request) error {
service, err := Get(instance.ServiceName)
if err != nil {
return err
}
endpoint, err := service.getClient("production")
if err != nil {
return err
}
prefix := fmt.Sprintf("/resources/%s/", instance.GetIdentifier())
path = strings.Trim(strings.TrimPrefix(path+"/", prefix), "/")
for _, reserved := range reservedProxyPaths {
if path == reserved && r.Method != "GET" {
return &tsuruErrors.ValidationError{
Message: fmt.Sprintf("proxy request %s %q is forbidden", r.Method, path),
}
}
}
return endpoint.Proxy(fmt.Sprintf("%s%s", prefix, path), evt, requestID, w, r)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/balancer/picker/roundrobin_balanced.go#L54-L92
|
func (rb *rrBalanced) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) {
rb.mu.RLock()
n := len(rb.scs)
rb.mu.RUnlock()
if n == 0 {
return nil, nil, balancer.ErrNoSubConnAvailable
}
rb.mu.Lock()
cur := rb.next
sc := rb.scs[cur]
picked := rb.scToAddr[sc].Addr
rb.next = (rb.next + 1) % len(rb.scs)
rb.mu.Unlock()
rb.lg.Debug(
"picked",
zap.String("address", picked),
zap.Int("subconn-index", cur),
zap.Int("subconn-size", n),
)
doneFunc := func(info balancer.DoneInfo) {
// TODO: error handling?
fss := []zapcore.Field{
zap.Error(info.Err),
zap.String("address", picked),
zap.Bool("success", info.Err == nil),
zap.Bool("bytes-sent", info.BytesSent),
zap.Bool("bytes-received", info.BytesReceived),
}
if info.Err == nil {
rb.lg.Debug("balancer done", fss...)
} else {
rb.lg.Warn("balancer failed", fss...)
}
}
return sc, doneFunc, nil
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/fuzzy/cluster.go#L133-L140
|
func containsNode(nodes []*raftNode, n *raftNode) bool {
for _, rn := range nodes {
if rn == n {
return true
}
}
return false
}
|
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/nop.go#L21-L27
|
func (c Nop) Write(w *bufio.Writer) (err error) {
if _, err = w.WriteString("NOP\n"); err != nil {
err = errors.Wrap(err, "writing NOP command")
return
}
return
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_projects.go#L55-L69
|
func (r *ProtocolLXD) GetProject(name string) (*api.Project, string, error) {
if !r.HasExtension("projects") {
return nil, "", fmt.Errorf("The server is missing the required \"projects\" API extension")
}
project := api.Project{}
// Fetch the raw value
etag, err := r.queryStruct("GET", fmt.Sprintf("/projects/%s", url.QueryEscape(name)), nil, "", &project)
if err != nil {
return nil, "", err
}
return &project, etag, nil
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L110-L113
|
func ServiceInfoFromIncomingContext(ctx context.Context) (serviceName, serviceVersion, netAddress string, err error) {
md := MetadataFromIncomingContext(ctx)
return ServiceInfoFromMetadata(md)
}
|
https://github.com/armon/go-radix/blob/1a2de0c21c94309923825da3df33a4381872c795/radix.go#L517-L530
|
func recursiveWalk(n *node, fn WalkFn) bool {
// Visit the leaf values if any
if n.leaf != nil && fn(n.leaf.key, n.leaf.val) {
return true
}
// Recurse on the children
for _, e := range n.edges {
if recursiveWalk(e.node, fn) {
return true
}
}
return false
}
|
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/cluster/cluster.go#L164-L171
|
func (c *Cluster) GoString() string {
buf, _ := json.Marshal(map[string]interface{}{
"listen": c.listen,
"nodes": c.nodes,
"buckets": strconv.FormatInt(int64(c.buckets), 10),
})
return string(buf)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/easyjson.go#L779-L783
|
func (v *GetWindowBoundsReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoBrowser7(&r, v)
return r.Error()
}
|
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/decode.go#L1318-L1365
|
func (d *StreamDecoder) Decode(v interface{}) error {
if d.err != nil {
return d.err
}
err := error(nil)
cnt := d.cnt
max := d.max
dec := Decoder{
Parser: d.Parser,
MapType: d.MapType,
}
switch d.typ {
case Unknown:
err = d.init()
max = d.max
case Array:
if cnt == max {
err = dec.Parser.ParseArrayEnd(cnt)
} else if cnt != 0 {
err = dec.Parser.ParseArrayNext(cnt)
}
}
if err == nil {
if cnt == max {
err = End
} else {
switch err = dec.Decode(v); err {
case nil:
cnt++
case End:
cnt++
max = cnt
default:
if max < 0 && dec.Parser.ParseArrayEnd(cnt) == nil {
err = End
}
}
}
}
d.err = err
d.cnt = cnt
d.max = max
return err
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L1477-L1493
|
func (c *Client) GetCombinedStatus(org, repo, ref string) (*CombinedStatus, error) {
c.log("GetCombinedStatus", org, repo, ref)
var combinedStatus CombinedStatus
err := c.readPaginatedResults(
fmt.Sprintf("/repos/%s/%s/commits/%s/status", org, repo, ref),
"",
func() interface{} {
return &CombinedStatus{}
},
func(obj interface{}) {
cs := *(obj.(*CombinedStatus))
cs.Statuses = append(combinedStatus.Statuses, cs.Statuses...)
combinedStatus = cs
},
)
return &combinedStatus, err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L763-L766
|
func (p SetCookieParams) WithURL(url string) *SetCookieParams {
p.URL = url
return &p
}
|
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/read.go#L690-L696
|
func (v Value) Index(i int) Value {
x, ok := v.data.(array)
if !ok || i < 0 || i >= len(x) {
return Value{}
}
return v.r.resolve(v.ptr, x[i])
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L692-L695
|
func (p PrintToPDFParams) WithDisplayHeaderFooter(displayHeaderFooter bool) *PrintToPDFParams {
p.DisplayHeaderFooter = displayHeaderFooter
return &p
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L14758-L14765
|
func (r *VolumeSnapshot) Locator(api *API) *VolumeSnapshotLocator {
for _, l := range r.Links {
if l["rel"] == "self" {
return api.VolumeSnapshotLocator(l["href"])
}
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/types.go#L864-L866
|
func (t ReferrerPolicy) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/api.go#L638-L661
|
func (r *Raft) Barrier(timeout time.Duration) Future {
metrics.IncrCounter([]string{"raft", "barrier"}, 1)
var timer <-chan time.Time
if timeout > 0 {
timer = time.After(timeout)
}
// Create a log future, no index or term yet
logFuture := &logFuture{
log: Log{
Type: LogBarrier,
},
}
logFuture.init()
select {
case <-timer:
return errorFuture{ErrEnqueueTimeout}
case <-r.shutdownCh:
return errorFuture{ErrRaftShutdown}
case r.applyCh <- logFuture:
return logFuture
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/network.go#L44-L53
|
func (e *Endpoints) NetworkAddress() string {
e.mu.RLock()
defer e.mu.RUnlock()
listener := e.listeners[network]
if listener == nil {
return ""
}
return listener.Addr().String()
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/client/clientset/versioned/typed/tsuru/v1/app.go#L99-L109
|
func (c *apps) Update(app *v1.App) (result *v1.App, err error) {
result = &v1.App{}
err = c.client.Put().
Namespace(c.ns).
Resource("apps").
Name(app.Name).
Body(app).
Do().
Into(result)
return
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.