input
stringlengths
24
2.11k
output
stringlengths
7
948
package addrmgr import ( "time" "github.com/abcsuite/abcd/wire" ) func TstKnownAddressIsBad(ka *KnownAddress) bool { return ka.isBad() } func TstNewKnownAddress(na *wire.NetAddress, attempts int, lastattempt, lastsuccess time.Time, tried bool, refs int) *KnownAddress { return &KnownAddress{na: na, attempts: ...
{ return ka.chance() }
package unibyte import "unicode" func IsLower(b byte) bool { return b >= 'a' && b <= 'z' } func IsLetter(b byte) bool { return IsLower(b) || IsUpper(b) } func IsSpaceQuote(b byte) bool { return IsSpace(b) || b == '"' || b == '\'' } func IsSpace(b byte) bool { return unicode.IsSpace(rune(b)) } func ToL...
{ return b >= 'A' && b <= 'Z' }
package wire_test import ( "bytes" "io" ) type fixedWriter struct { b []byte pos int } func (w *fixedWriter) Write(p []byte) (n int, err error) { lenp := len(p) if w.pos+lenp > cap(w.b) { return 0, io.ErrShortWrite } n = lenp w.pos += copy(w.b[w.pos:], p) return } func (w *fixedWriter) Bytes()...
{ b := make([]byte, max, max) if buf != nil { copy(b[:], buf) } iobuf := bytes.NewBuffer(b) fr := fixedReader{b, 0, iobuf} return &fr }
package collector import ( "testing" "time" "github.com/google/cadvisor/info/v1" "github.com/stretchr/testify/assert" ) type fakeCollector struct { nextCollectionTime time.Time err error collectedFrom int } func (fc *fakeCollector) Name() string { return "fake-collector" } func (fc *f...
{ fc.collectedFrom++ return fc.nextCollectionTime, metric, fc.err }
package auth import ( "sync" "github.com/google/martian/session" ) const key = "auth.Context" type Context struct { mu sync.RWMutex id string err error } func FromContext(ctx *session.Context) *Context { if v, ok := ctx.GetSession().Get(key); ok { return v.(*Context) } actx := &Context{} ctx.GetSes...
{ ctx.mu.RLock() ctx.mu.RUnlock() return ctx.id }
package main import ( "fmt" ) func main() { methods() interfaces() typeAssertions() } func interfaces() { fmt.Println("Interfaces") fmt.Println("==========") person := Person{ Phrase: "Hello", Thought: "Cogito ergo sum", } dog := Dog{} var s...
{ fmt.Println("Methods") fmt.Println("=======") swedishChef := Person{ Phrase: "Bork bork bork!", } fmt.Printf("swedishChef says '%s'\n", swedishChef.Speak()) myFloat := MyFloat(16.0) myFloat.Square() fmt.Printf("myFloat -> value = %f, squared = %f\n", myFloat, myFloat.Square...
package influxdb import ( "fmt" "log" "net/url" "testing" "time" "github.com/fractalplatform/fractal/metrics" client "github.com/influxdata/influxdb1-client" ) const ( dburl = "http://localhost:8086" testdb = "testmetrics" username = "" password = "" namespace = "test/" prefix = "test" tabl...
{ go InfluxDBWithTags(metrics.DefaultRegistry, 1*time.Second, dburl, testdb, "", "", namespace, make(map[string]string)) tm := metrics.NewRegisteredTimer(prefix, nil) for i := 0; i < 5; i++ { tm.Update(100 * time.Second) } time.Sleep(time.Duration(10) * time.Second) }
package main import ( "fmt" "net/http" rice "github.com/GeertJohan/go.rice" "git.timschuster.info/rls.moe/catgi/logger" ) type handlerServeResources struct { rice *rice.Box } func newHandlerServeResources() http.Handler { return &handlerServeResources{ rice: (&rice.Config{ LocateOrder: []rice.LocateMeth...
{ log := logger.LogFromCtx("serverIndex", r.Context()) log.Info("Loading file from disk: ", r.RequestURI) dat, err := h.rice.Bytes(r.URL.String()) if err != nil { log.Error("Could not load file from disk: ", err) rw.WriteHeader(404) fmt.Fprint(rw, "index.html not found") return } rw.WriteHeader(200) rw.H...
package logutils import ( "github.com/stretchr/testify/mock" ) type MockLog struct { mock.Mock } func NewMockLog() *MockLog { return &MockLog{} } func (m *MockLog) Fatalf(format string, args ...interface{}) { mArgs := []interface{}{format} m.Called(append(mArgs, args...)...) } func (m *MockLog) Panicf(format ...
{ m.Called(level) }
package lock import ( "testing" . "gopkg.in/check.v1" ) func Test(t *testing.T) { TestingT(t) } type LockSuite struct{} var _ = Suite(&LockSuite{}) func (s *LockSuite) TestDebugLock(c *C) { var lock1 RWMutexDebug lock1.Lock() lock1.Unlock() lock1.RLock() lock1.RLock() lock1.RUnlock() lock1.RUnlock()...
{ var lock1 RWMutex lock1.Lock() lock1.Unlock() lock1.RLock() lock1.RLock() lock1.RUnlock() lock1.RUnlock() var lock2 Mutex lock2.Lock() lock2.Unlock() }
package models import "testing" func TestGetEntityName(t *testing.T) { _, err := GetEntityName(2) if err != nil { t.Error(err) return } } func TestGetTypeName(t *testing.T) { _, err := GetTypeName(2) if err != nil { t.Error(err) return } } func TestGetCelestialName(t *testing.T) { _, err := GetCeles...
{ _, err := GetSystemName(30000001) if err != nil { t.Error(err) return } }
package codegen import ( "os" "testing" "goa.design/goa/v3/codegen/service" "goa.design/goa/v3/expr" ) func makeGolden(t *testing.T, p string) *os.File { t.Helper() if os.Getenv("GOLDEN") == "" { return nil } f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY, 0600) if err != nil { t.Fatal(err) } ...
{ service.Services = make(service.ServicesData) HTTPServices = make(ServicesData) return expr.RunDSL(t, dsl) }
package rorm type rorm struct { redisQuerier *RedisQuerier } func NewROrm() ROrmer { return new(rorm).Using("default") } func (r *rorm) QueryHash(key string) HashQuerySeter { return &hashQuerySet{ querySet: &querySet{ rorm: r, key: key, }, } } func (r *rorm) QueryKeys(key string) KeysQuerySeter { re...
{ return &setQuerySet{ querySet: &querySet{ rorm: r, key: key, }, } }
package data_table import ( "bytes" "encoding/json" "fmt" "github.com/julienschmidt/httprouter" "net/http" "net/url" ) func TreePostFormValues(values url.Values) map[string]interface{} { res := make(map[string]interface{}) var currValue map[string]interface{} for rawKey, value := range values { if vs := ...
{ return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { request := newSearchRequest(r, ps) result := tableStore.QueryData(request) jsonBytes, _ := json.Marshal(result) fmt.Fprint(w, string(jsonBytes)) } }
package sharpen import ( "hawx.me/code/img/blur" "hawx.me/code/img/utils" "image" "image/color" "math" ) func UnsharpMask(in image.Image, radius int, sigma, amount, threshold float64) image.Image { blurred := blur.Gaussian(in, radius, sigma, blur.IGNORE) bounds := in.Bounds() out := image.NewRGBA(bou...
{ normalize := 0.0 f := func(u, v int) float64 { usq := float64(u * u) vsq := float64(v * v) val := -math.Exp(-(usq+vsq)/(2.0*sigma*sigma)) / (2.0 * math.Pi * sigma * sigma) normalize += val return val } k := blur.NewKernel(radius*2+1, radius*2+1, f) k[radius+1][radius+1] = -2.0 * normalize return bl...
package main import ( "crypto/tls" "crypto/x509" log "github.com/Sirupsen/logrus" "io" "io/ioutil" "time" ) type TLSConnection struct { host string certPool *x509.CertPool conn *tls.Conn } func (c *TLSConnection) Connect() (err error) { c.conn, err = tls.Dial("tcp", c.host, &tls.Config{ RootCAs...
{ c := &TLSConnection{} c.host = host c.getCerts() err := c.Connect() return c, err }
package pml_test import ( "encoding/xml" "testing" "baliance.com/gooxml/schema/soo/pml" ) func TestEG_TopLevelSlideConstructor(t *testing.T) { v := pml.NewEG_TopLevelSlide() if v == nil { t.Errorf("pml.NewEG_TopLevelSlide must return a non-nil value") } if err := v.Validate(); err != nil { t.Errorf("newly...
{ v := pml.NewEG_TopLevelSlide() buf, _ := xml.Marshal(v) v2 := pml.NewEG_TopLevelSlide() xml.Unmarshal(buf, v2) }
package testing import ( "github.com/markdaws/gohome/pkg/cmd" "github.com/markdaws/gohome/pkg/gohome" ) type extension struct { gohome.NullExtension } func (e *extension) Name() string { return "testing" } func (e *extension) NetworkForDevice(sys *gohome.System, d *gohome.Device) gohome.Network { return nil ...
{ switch d.ModelNumber { case "testing.hardware": return &cmdBuilder{ModelNumber: d.ModelNumber, Device: d} default: return nil } }
package hawkular import ( "net/url" "sync" "github.com/adfin/statster/metrics/core" hawkular "github.com/hawkular/hawkular-client-go/metrics" ) type Filter func(ms *core.MetricSet, metricName string) bool type FilterType int const ( Label FilterType = iota Name Unknown ) type hawkularSink struct { client...
{ switch s { case "label": return Label case "name": return Name default: return Unknown } }
package distsql import ( "errors" "runtime" "testing" "time" . "github.com/pingcap/check" "github.com/pingcap/tidb/model" "github.com/pingcap/tidb/mysql" "github.com/pingcap/tidb/util/testleak" "github.com/pingcap/tidb/util/types" "github.com/pingcap/tipb/go-tipb" goctx "golang.org/x/net/context" ) func T...
{ var sr SelectResult countBefore := runtime.NumGoroutine() sr = &selectResult{ resp: &mockResponse{}, results: make(chan resultWithErr, 5), closed: make(chan struct{}), } go sr.Fetch(goctx.TODO()) for { _, err := sr.Next() if err != nil { sr.Close() break } } tick := 10 * time.Milliseco...
package http import ( "strconv" "go-common/app/service/main/archive/api" "go-common/library/ecode" bm "go-common/library/net/http/blademaster" ) func pageList(c *bm.Context) { var ( aid int64 err error pages []*api.Page ) aidStr := c.Request.Form.Get("aid") if aid, err = strconv.ParseInt(aidStr, 10...
{ v := new(struct { Aid int64 `form:"aid" validate:"min=1"` Cid int64 `form:"cid"` Index bool `form:"index"` }) if err := c.Bind(v); err != nil { return } c.JSON(playSvr.VideoShot(c, v.Aid, v.Cid, v.Index)) }
package internal import ( "fmt" "log" "os" "gopkg.in/reform.v1" ) type Logger struct { printf reform.Printf debug bool } func NewLogger(prefix string, debug bool) *Logger { var flags int if debug { flags = log.Ldate | log.Lmicroseconds | log.Lshortfile } l := log.New(os.Stderr, prefix, flags) retur...
{ l.printf(format, args...) if l.debug { panic(fmt.Sprintf(format, args...)) } os.Exit(1) }
package timekeeper import "time" type TimeKeeper interface { After(d time.Duration) <-chan time.Time Sleep(d time.Duration) Now() time.Time } type realTime struct{} var rt realTime func (t *realTime) After(d time.Duration) <-chan time.Time { return time.After(d) } func (t *realTime) Sleep(d time.Durati...
{ return time.Now() }
package client import ( "fmt" "strings" "google.golang.org/grpc/status" "google.golang.org/protobuf/encoding/prototext" "google.golang.org/protobuf/proto" _ "google.golang.org/genproto/googleapis/rpc/errdetails" ) type StatusError struct { st *status.Status details string } func (e *StatusError) ...
{ var details []string for _, d := range st.Details() { s := fmt.Sprintf("%+v", d) if pb, ok := d.(proto.Message); ok { s = prototext.Format(pb) } details = append(details, s) } return &StatusError{st, strings.Join(details, "; ")} }
package cache import ( "context" "io" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/platform" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/tag" ) ty...
{ return buildAndTest(ctx, out, tags, artifacts, platforms) }
package http import ( "net/http" "reflect" ) type JSONErrorBuilder interface { Build() JSONError CustomError(code int, errorType, msg string) JSONErrorBuilder FromError(e error) JSONErrorBuilder Message(string) JSONErrorBuilder Status(int) JSONErrorBuilder URL(string) JSONErrorBuilder } type jsonErrorB...
{ b.instance.Message = msg return b }
package models import ( "context" "encoding/json" "github.com/go-openapi/errors" "github.com/go-openapi/strfmt" "github.com/go-openapi/validate" ) type RdmaProtocol string const ( RdmaProtocolRoce RdmaProtocol = "roce" ) var rdmaProtocolEnum []interface{} func init() { var res []RdmaProtocol if e...
{ return nil }
package db import ( "time" "github.com/jinzhu/gorm" _"github.com/mattn/go-sqlite3" ) var ( DB gorm.DB ) type User struct { Id int `json:"id"` Username string `json:"username"; unique` Password string `json:"password"` Created time.Time `json:"created_at"` } type Device struct { Id int ...
{ var err error DB, err = gorm.Open("sqlite3", *dbname) if err != nil { return err } DB.AutoMigrate(&User{}, &Device{}) return nil }
package com import ( "testing" . "github.com/smartystreets/goconvey/convey" ) func TestIsFile(t *testing.T) { if !IsFile("file.go") { t.Errorf("IsExist:\n Expect => %v\n Got => %v\n", true, false) } if IsFile("testdata") { t.Errorf("IsExist:\n Expect => %v\n Got => %v\n", false, true) } if IsFile("files...
{ for i := 0; i < b.N; i++ { IsFile("file.go") } }
package gtk import "C" import ( "unsafe" ) func (v *Menu) PopupAtMouseCursor(parentMenuShell IMenu, parentMenuItem IMenuItem, button int, activateTime uint32) { wshell := nullableWidget(parentMenuShell) witem := nullableWidget(parentMenuItem) C.gtk_menu_popup(v.native(), wshell, witem, nil, nil, C....
{ c := C.gtk_font_button_get_font_name(v.native()) return goString(c) }
package leafnodes_test import ( . "github.com/sinbad/git-lfs-ssh-serve/Godeps/_workspace/src/github.com/onsi/ginkgo" . "github.com/sinbad/git-lfs-ssh-serve/Godeps/_workspace/src/github.com/onsi/gomega" "testing" ) func TestLeafNode(t *testing.T)
{ RegisterFailHandler(Fail) RunSpecs(t, "LeafNode Suite") }
package timeutil import ( "time" ) func SetTimeout(t time.Duration, callback func()) { go func() { time.Sleep(t) callback() }() } func SetInterval(t time.Duration, callback func() bool) { go func() { for { time.Sleep(t) if !callback() { break } } }() } func Nanosecond() int64 { return...
{ return time.Now().Format("2006-01-02 15:04:05") }
package iso20022 type PartyIdentificationAndAccount77 struct { Identification *PartyIdentification32Choice `xml:"Id"` AlternateIdentification *AlternatePartyIdentification5 `xml:"AltrnId,omitempty"` SafekeepingAccount *Max35Text `xml:"SfkpgAcct,omitempty"` ProcessingIdentification *Max35Text `xml:"PrcgId,omit...
{ p.AdditionalInformation = new(PartyTextInformation1) return p.AdditionalInformation }
package armrecoveryservicesbackup_test import ( "context" "log" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/recoveryservices/armrecoveryservicesbackup" ) func ExampleBackupEnginesClient_Get() { cred, err := azidentity.NewDefaultAzureCredential(ni...
{ cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client := armrecoveryservicesbackup.NewBackupEnginesClient("<subscription-id>", cred, nil) pager := client.List("<vault-name>", "<resource-group-name>", ...
package replicationcontroller import ( "github.com/kubernetes/dashboard/src/app/backend/resource/common" "github.com/kubernetes/dashboard/src/app/backend/resource/dataselect" "github.com/kubernetes/dashboard/src/app/backend/resource/service" metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1" client "k8s.io/client-go/k...
{ replicationController, err := client.CoreV1().ReplicationControllers(namespace).Get(rcName, metaV1.GetOptions{}) if err != nil { return nil, err } channels := &common.ResourceChannels{ ServiceList: common.GetServiceListChannel(client, common.NewSameNamespaceQuery(namespace), 1), } services := <-channe...
package nodos import ( "unsafe" ) func progressPrintCallBack(totalL, totalH, transferL, transferH, c1, c2, d1, d2, e, f, g, h, this uintptr) uintptr
{ progressPrint(uint64(totalL)|(uint64(totalH)<<32), uint64(transferL)|(uint64(transferH)<<32), (*progressCopy)(unsafe.Pointer(this))) return 0 }
package engine import ( "time" "github.com/aws/amazon-ecs-agent/agent/api" ) type impossibleTransitionError struct { state api.ContainerStatus } func (err *impossibleTransitionError) Error() string { return "Cannot transition to " + err.state.String() } func (err *impossibleTransitionError) ErrorName() string...
{ return "OutOfMemoryError" }
package vision import ( "golang.org/x/net/context" "google.golang.org/grpc/metadata" ) func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) out = out.Copy() for _, md := range mds { for k, v := range md { out[k] = append(out[k], v...) ...
{ return []string{ "https:www.googleapis.com/auth/cloud-platform", "https:www.googleapis.com/auth/cloud-vision", } }
package msd import ( "encoding/base64" "github.com/bluefw/blued/discoverd/api" "github.com/gin-gonic/gin" "log" "net/http" ) type ServiceResource struct { repo *DiscoverdRepo logger *log.Logger } func (sr *ServiceResource) RegMicroApp(c *gin.Context) { var as api.MicroApp if err := c.Bind(&as); err != n...
{ return &ServiceResource{ repo: dr, logger: l, } }
package main import ( "io" "os" "text/template" ) func copyFile(dst, src string) (int64, error) { sf, err := os.Open(src) if err != nil { return 0, err } defer sf.Close() df, err := os.Create(dst) if err != nil { return 0, err } defer df.Close() return io.Copy(df, sf) } func writeTemplateToFile...
{ f, e := os.Create(path) if e != nil { return "", e } defer f.Close() e = t.Execute(f, data) if e != nil { return "", e } return f.Name(), nil }
package api import ( "fmt" "net/http" "github.com/NebulousLabs/Sia/build" "github.com/NebulousLabs/Sia/types" ) type ConsensusGET struct { Height types.BlockHeight `json:"height"` CurrentBlock types.BlockID `json:"currentblock"` Target types.Target `json:"target"` } func (srv *Serv...
{ id := srv.mu.RLock() defer srv.mu.RUnlock(id) curblockID := srv.currentBlock.ID() currentTarget, exists := srv.cs.ChildTarget(curblockID) if build.DEBUG { if !exists { fmt.Printf("Could not find block %s\n", curblockID) panic("server has nonexistent current block") } } writeJSON(w, ConsensusGET{ ...
package triton import ( "context" "encoding/json" "fmt" "net/http" "github.com/hashicorp/errwrap" ) type ConfigClient struct { *Client } func (c *Client) Config() *ConfigClient { return &ConfigClient{c} } type Config struct { DefaultNetwork string `json:"default_network"` } type GetConfigInput struct{}...
{ path := fmt.Sprintf("/%s/config", client.accountName) respReader, err := client.executeRequest(ctx, http.MethodPut, path, input) if respReader != nil { defer respReader.Close() } if err != nil { return nil, errwrap.Wrapf("Error executing UpdateConfig request: {{err}}", err) } var result *Config decoder :...
package xy type Group []Geometric func (g *Group) Add(shape Geometric) { *g = append(*g, shape) } func (g Group) Accept(visitor Visitor)
{ visitor.VisitGroup(g) }
package server import ( "fmt" "net/http" "github.com/localhots/shezmu/stats" ) type Server struct { port int ss *stats.Server mux *http.ServeMux } func (s *Server) Start() { addr := fmt.Sprintf(":%d", s.port) s.mux.HandleFunc("/stats.json", s.ss.History) go http.ListenAndServe(addr, s.mux) } func New...
{ return &Server{ port: port, ss: ss, mux: http.NewServeMux(), } }
package goapp import( "github.com/xaevman/goat/mod/log" ) import( "testing" "time" ) func waitForShutdown() { <-time.After(10 * time.Second) Stop() } func TestDefaultApp(t *testing.T)
{ log.DebugLogs = true SetHeartbeat(1 * 1000) go waitForShutdown() stopChan := Start("DefaultApp") <-stopChan }
package kasper import ( "testing" "github.com/stretchr/testify/assert" ) func TestTopicProcessorConfig_kafkaConsumerGroup(t *testing.T) { c := &Config{ TopicProcessorName: "hari-seldon", } assert.Equal(t, "kasper-topic-processor-hari-seldon", c.kafkaConsumerGroup()) } func TestTopicProcessorConfig_producer...
{ c := &Config{ TopicProcessorName: "ford-prefect", } assert.Equal(t, "kasper-topic-processor-ford-prefect", c.producerClientID()) }
package util import "fmt" func PanicOnError(err error, message string) { if err != nil { panic(fmt.Sprintf("%s: %s", message, err.Error())) } } func PanicIfNil(check interface{}, message string)
{ if check == nil { panic(message) } }
package client import ( "fmt" "strings" "google.golang.org/grpc/status" "google.golang.org/protobuf/encoding/prototext" "google.golang.org/protobuf/proto" _ "google.golang.org/genproto/googleapis/rpc/errdetails" ) type StatusError struct { st *status.Status details string } func StatusDetailedError...
{ msg := fmt.Sprintf("rpc error: code = %s desc = %s", e.st.Code(), e.st.Message()) if e.details != "" { msg += " details = " + e.details } return msg }
package lints import ( "github.com/zmap/zcrypto/x509" "github.com/zmap/zlint/util" ) type caKeyCertSignNotSet struct{} func (l *caKeyCertSignNotSet) Initialize() error { return nil } func (l *caKeyCertSignNotSet) Execute(c *x509.Certificate) *LintResult { if c.KeyUsage&x509.KeyUsageCertSign != 0 { retur...
{ return c.IsCA && util.IsExtInCert(c, util.KeyUsageOID) }
package transporttest import ( "context" "fmt" "testing" "time" ) type ContextMatcher struct { t *testing.T ttl time.Duration TTLDelta time.Duration } type ContextMatcherOption interface { run(*ContextMatcher) } type ContextTTL time.Duration func (ttl ContextTTL) run(c *ContextMatcher) { c.ttl = ...
{ return fmt.Sprintf("ContextMatcher(TTL:%v±%v)", c.ttl, c.TTLDelta) }
package identitymapper import ( "fmt" "k8s.io/klog" "k8s.io/apiserver/pkg/authentication/authenticator" "github.com/openshift/origin/pkg/oauthserver/api" ) func logf(format string, args ...interface{}) { if klog.V(4) { klog.InfoDepth(2, fmt.Sprintf("identitymapper: "+format, args...)) } } func Respons...
{ user, err := mapper.UserFor(identity) if err != nil { logf("error creating or updating mapping for: %#v due to %v", identity, err) return nil, false, err } logf("got userIdentityMapping: %#v", user) return &authenticator.Response{User: user}, true, nil }
package collector import ( "errors" "fmt" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/log" ) import "C" type loadavgCollector struct { metric prometheus.Gauge } func init() { Factories["loadavg"] = NewLoadavgCollector } func (c *loadavgCollector) Update(ch chan<- prometheus....
{ return &loadavgCollector{ metric: prometheus.NewGauge(prometheus.GaugeOpts{ Namespace: Namespace, Name: "load1", Help: "1m load average.", }), }, nil }
package library import ( "context" "flag" "fmt" "github.com/vmware/govmomi/govc/cli" "github.com/vmware/govmomi/govc/flags" "github.com/vmware/govmomi/vapi/library" "github.com/vmware/govmomi/vapi/rest" ) type rm struct { *flags.ClientFlag force bool } func (cmd *rm) Register(ctx context.Context, f *flag...
{ cli.Register("library.rm", &rm{}) }
package topovalidator import ( "fmt" "golang.org/x/net/context" "vitess.io/vitess/go/vt/topo" topodatapb "vitess.io/vitess/go/vt/proto/topodata" ) type KeyspaceValidator struct{} func (kv *KeyspaceValidator) Audit(ctx context.Context, ts *topo.Server, w *Workflow) error { keyspaces, err := ts.GetKe...
{ RegisterValidator("Keyspace Validator", &KeyspaceValidator{}) }
package graphdriver import "C" import ( "path/filepath" "unsafe" "github.com/docker/docker/pkg/mount" "github.com/sirupsen/logrus" ) const ( FsMagicZfs = FsMagic(0x2fc12fc1) ) var ( priority = []string{ "zfs", } FsNames = map[FsMagic]string{ FsMagicZfs: "zfs", } ) func GetFSMagic(rootpath string) (...
{ cs := C.CString(filepath.Dir(mountPath)) defer C.free(unsafe.Pointer(cs)) buf := C.getstatfs(cs) defer C.free(unsafe.Pointer(buf)) if (buf.f_basetype[0] != 122) || (buf.f_basetype[1] != 102) || (buf.f_basetype[2] != 115) || (buf.f_basetype[3] != 0) { logrus.Debugf("[zfs] no zfs dataset found for rootdir '%...
package blobstoredbstatesnapshotio import ( "fmt" "golang.org/x/net/context" "github.com/nyaxt/otaru/metadata" ) func generateBlobpath() string { return fmt.Sprintf("%s_SimpleSSLocator", metadata.INodeDBSnapshotBlobpathPrefix) } var simplesslocatorTxID int64 type SimpleSSLocator struct{} func (SimpleSSLocato...
{ return []string{}, nil }
package header import "github.com/google/netstack/tcpip" type NDPNeighborSolicit []byte const ( NDPNSMinimumSize = 20 ndpNSTargetAddessOffset = 4 ndpNSOptionsOffset = ndpNSTargetAddessOffset + IPv6AddressSize ) func (b NDPNeighborSolicit) SetTargetAddress(addr tcpip.Address) { copy(b[ndpNSTargetAddess...
{ return tcpip.Address(b[ndpNSTargetAddessOffset:][:IPv6AddressSize]) }
package format import ( "github.com/trivago/gollum/core" "os" ) type Hostname struct { core.SimpleFormatter `gollumdoc:"embed_type"` separator []byte `config:"Separator" default:":"` } func init() { core.TypeRegistry.Register(Hostname{}) } func (format *Hostname) Configure...
{ hostname, err := os.Hostname() if err != nil { format.Logger.Error(err) hostname = "unknown host" } dataSize := len(hostname) + len(format.separator) + len(content) payload := core.MessageDataPool.Get(dataSize) offset := copy(payload, []byte(hostname)) offset += copy(payload[offset:], format.separator) ...
package lifegame type Universe struct { aliveCells []Cell } type Cell struct{} func NewUniverse() *Universe { return &Universe{} } func (u *Universe) HasAliveCell() bool { return len(u.AliveCells()) != 0 } func (u *Universe) AliveCells() []Cell { return u.aliveCells } func (u *Universe) NextGeneration() { u....
{ return 0, 0 }
package backend import ( "sync" "github.com/docker/infrakit/pkg/run/scope" "github.com/spf13/cobra" "github.com/spf13/pflag" ) type ExecFunc func(script string, cmd *cobra.Command, args []string) error type FlagsFunc func(*pflag.FlagSet) type TemplateFunc func(scope scope.Scope, trial bool, opt ...interface...
{ lock.Lock() defer lock.Unlock() backends[funcName] = backend flags[funcName] = buildFlags }
package server import ( "net/http" "github.com/fnproject/fn/api" "github.com/gin-gonic/gin" ) func (s *Server) handleAppGet(c *gin.Context)
{ ctx := c.Request.Context() appId := c.Param(api.AppID) app, err := s.datastore.GetAppByID(ctx, appId) if err != nil { handleErrorResponse(c, err) return } c.JSON(http.StatusOK, app) }
package restic import "syscall" func (node Node) restoreSymlinkTimestamps(path string, utimes [2]syscall.Timespec) error { return nil } func (node Node) device() int { return int(node.Device) } func (s statUnix) atim() syscall.Timespec { return s.Atimespec } func (s statUnix) mtim() syscall.Timespec { return s.Mt...
{ return nil, nil }
package post import "github.com/barnex/bruteray/imagef" type Params struct { Gaussian BloomParams Airy BloomParams Star BloomParams } type BloomParams struct { Radius float64 Amplitude float64 Threshold float64 } func (p *Params) ApplyTo(img imagef.Image, pixelSize float64) imagef.Image { if b := ...
{ widthPix := radius / pixelSize numPix := int(widthPix) K := starKernel(numPix) img2 := img.Copy() AddConvolution(img2, img, K, amplitude, threshold) return img2 }
package byteorder import ( "encoding/binary" "net" "testing" . "gopkg.in/check.v1" ) func Test(t *testing.T) { TestingT(t) } type ByteorderSuite struct{} var _ = Suite(&ByteorderSuite{}) func (b *ByteorderSuite) TestNativeIsInitialized(c *C) { c.Assert(Native, NotNil) } func (b *ByteorderSuite) TestHostTo...
{ switch Native { case binary.LittleEndian: c.Assert(NetIPv4ToHost32(net.ParseIP("10.11.129.91")), Equals, uint32(0x5b810b0a)) c.Assert(NetIPv4ToHost32(net.ParseIP("10.11.138.214")), Equals, uint32(0xd68a0b0a)) case binary.BigEndian: c.Assert(NetIPv4ToHost32(net.ParseIP("10.11.129.91")), Equals, uint32(0x0a0b8...
package vm import ( "github.com/expanse-org/go-expanse/common" "github.com/expanse-org/go-expanse/common/math" "github.com/holiman/uint256" ) func calcMemSize64WithUint(off *uint256.Int, length64 uint64) (uint64, bool) { if length64 == 0 { return 0, false } offset64, overflow := off.Uint64WithOverflow(...
{ if !l.IsUint64() { return 0, true } return calcMemSize64WithUint(off, l.Uint64()) }
package metrics_test import ( "github.com/stripe/veneur/v14/ssf" "github.com/stripe/veneur/v14/trace" "github.com/stripe/veneur/v14/trace/metrics" ) func ExampleReportAsync()
{ samples := []*ssf.SSFSample{} samples = append(samples, ssf.Count("a.counter", 2, nil)) samples = append(samples, ssf.Gauge("a.gauge", 420, nil)) done := make(chan error) metrics.ReportAsync(trace.DefaultClient, samples, done) <-done }
package cluster import ( "common" "testing" . "launchpad.net/gocheck" ) type UserSuite struct{} var _ = Suite(&UserSuite{}) var root common.User func Test(t *testing.T) { TestingT(t) } func (self *UserSuite) TestProperties(c *C) { u := ClusterAdmin{CommonUser{Name: "root"}} c.Assert(u.IsClusterAdmin(), E...
{ user := &ClusterAdmin{CommonUser{"root", "", false, "root"}} c.Assert(user.ChangePassword("password"), IsNil) root = user }
package common import ( "strconv" "time" ) type ConversionResult struct { DateAsString string DateAsInt int Date time.Time } func ConvertIntToDisplay(dateAsInt int) string { dayAsString := strconv.Itoa(dateAsInt) return dayAsString } func ConvertStringToDates(dateAsString string) (ConversionResul...
{ return ConvertStringToDates(d.Date.AddDate(0, 0, 1).Format("20060102")) }
package core import ( "github.com/oracle/oci-go-sdk/v46/common" "net/http" ) type CopyVolumeGroupBackupRequest struct { VolumeGroupBackupId *string `mandatory:"true" contributesTo:"path" name:"volumeGroupBackupId"` CopyVolumeGroupBackupDetails `contributesTo:"body"` OpcRetryToken *string `mandatory:"fals...
{ return common.PointerString(request) }
package handler import ( "net/http" "github.com/cosiner/zerver" ) type MethodHandler interface { Get(zerver.Request, zerver.Response) Post(zerver.Request, zerver.Response) Delete(zerver.Request, zerver.Response) Put(zerver.Request, zerver.Response) Patch(zerver.Request, zerver.Response) } type methodHandler ...
{ resp.StatusCode(http.StatusMethodNotAllowed) }
package main import ( "bytes" "github.com/bitly/go-nsq" ) type BackendQueue interface { Put([]byte) error ReadChan() chan []byte Close() error Delete() error Depth() int64 Empty() error } type DummyBackendQueue struct { readChan chan []byte } func NewDummyBackendQueue() BackendQueue { return &DummyBac...
{ return d.readChan }
package land import ( "context" "os" "code.cloudfoundry.org/lager" "code.cloudfoundry.org/lager/lagerctx" "github.com/concourse/concourse/atc" "github.com/concourse/concourse/worker" ) type LandWorkerCommand struct { TSA worker.TSAConfig `group:"TSA Configuration" namespace:"tsa" required:"true"` WorkerName...
{ logger := lager.NewLogger("land-worker") logger.RegisterSink(lager.NewPrettySink(os.Stdout, lager.DEBUG)) client := cmd.TSA.Client(atc.Worker{ Name: cmd.WorkerName, }) return client.Land(lagerctx.NewContext(context.Background(), logger)) }
package main import ( "github.com/gossamer-irc/lib" "strings" ) type PendingClient struct { Ircd *Ircd Conn *IrcConnection Subnet *lib.Subnet Nick string Ident string Gecos string Host string } func NewPendingClient(ircd *Ircd, conn *IrcConnection, subnet *lib.Subnet, host string) *PendingClient {...
{ if pc.Nick == "" || pc.Ident == "" || pc.Gecos == "" { return } lnick := strings.ToLower(pc.Nick) _, found := pc.Subnet.Client[lnick] if found { pc.Conn.Send(&IrcNickInUse{pc.Nick}) pc.Nick = "" return } pc.Ircd.AcceptPendingClient(pc) }
package like import ( "context" "fmt" "go-common/app/interface/main/activity/model/like" "go-common/library/cache/memcache" "go-common/library/log" ) const ( _prefixInfo = "m_" ) func (dao *Dao) SetInfoCache(c context.Context, v *like.Subject, sid int64) (err error) { if v == nil { v = &like.Subject{} ...
{ return fmt.Sprintf("%s%d", _prefixInfo, sid) }
package character type Histogram struct { counts [256]uint16 } func StringHistogram(text string) *Histogram { histogram := &Histogram{} for i := 0; i < len(text); i++ { histogram.Add(Char(text[i])) } return histogram } func (h *Histogram) Add(char Char) { h.counts[char]++ } func (h *Histogram) Count(char ...
{ return int(h.counts[char]) }
package dhcpv6 import ( "fmt" "github.com/u-root/uio/uio" ) type optRelayPort struct { DownstreamSourcePort uint16 } func (op *optRelayPort) Code() OptionCode { return OptionRelayPort } func (op *optRelayPort) ToBytes() []byte { buf := uio.NewBigEndianBuffer(nil) buf.Write16(op.DownstreamSourcePort) retu...
{ return &optRelayPort{DownstreamSourcePort: port} }
package lib func cacheHintTagList(repository string) string { return "pull:" + repository } func cacheHintTagDetails(repository string) string { return "pull:" + repository } func cacheHintRegistryList() string
{ return "catalog:" }
package vpki import ( "crypto/tls" "sync" "time" ) type certCache struct { m map[string]*tls.Certificate mut *sync.RWMutex crt Certifier ttl time.Duration } func newCertCache(crt Certifier) *certCache { return &certCache{ m: map[string]*tls.Certificate{}, mut: &sync.RWMutex{}, crt: crt, ttl: Defa...
{ lkr := cc.mut.RLocker() lkr.Lock() if c, ok := cc.m[name]; ok { n := time.Now() if n.After(c.Leaf.NotBefore) && n.Before(c.Leaf.NotAfter) { lkr.Unlock() return c, nil } } lkr.Unlock() return cc.add(name) }
package fake_cmdpreparer import ( "os/exec" "sync" "code.cloudfoundry.org/garden" "code.cloudfoundry.org/garden-linux/container_daemon" ) type FakeCmdPreparer struct { PrepareCmdStub func(garden.ProcessSpec) (*exec.Cmd, error) prepareCmdMutex sync.RWMutex prepareCmdArgsForCall []struct { arg1 g...
{ fake.prepareCmdMutex.RLock() defer fake.prepareCmdMutex.RUnlock() return fake.prepareCmdArgsForCall[i].arg1 }
package aviasales type Alliance struct { Name string `json:"name" bson:"name"` Airlines []string `json:"alias" bson:"alias"` } func (a *AviasalesApi) DataAirlinesAlliances() (airlinesAlliances []Alliance, err error)
{ err = a.getJson("data/airlines_alliances.json", map[string]string{}, &airlinesAlliances) return }
package v1 import ( "github.com/ertgl/croncache" ) func init()
{ err := croncache.TaskManagerRepository().Register(MODULE_NAME, Generator) if err != nil { croncache.HandleFatalError(err) } }
package cgotest import "C" import "testing" import "time" func test6997(t *testing.T)
{ r := C.StartThread() if r != 0 { t.Error("pthread_create failed") } c := make(chan C.int) go func() { time.Sleep(500 * time.Millisecond) c <- C.CancelThread() }() select { case r = <-c: if r == 0 { t.Error("pthread finished but wasn't cancelled??") } case <-time.After(30 * time.Second): t.Err...
package watch type FilterFunc func(in Event) (out Event, keep bool) type filteredWatch struct { incoming Interface result chan Event f FilterFunc } func (fw *filteredWatch) ResultChan() <-chan Event { return fw.result } func (fw *filteredWatch) Stop() { fw.incoming.Stop() } func (fw *...
{ fw := &filteredWatch{ incoming: w, result: make(chan Event), f: f, } go fw.loop() return fw }
package sql import ( "fmt" "github.com/cockroachdb/cockroach/sql/parser" ) func (p *planner) Values(n parser.Values) (planNode, error) { v := &valuesNode{ rows: make([]parser.DTuple, 0, len(n)), } for _, tuple := range n { data, err := parser.EvalExpr(tuple, nil) if err != nil { return nil, err } ...
{ if n.nextRow >= len(n.rows) { return false } n.nextRow++ return true }
package v1 import ( dataService "github.com/tidepool-org/platform/data/service" "github.com/tidepool-org/platform/request" "github.com/tidepool-org/platform/service" ) func Authenticate(handler dataService.HandlerFunc) dataService.HandlerFunc
{ return func(context dataService.Context) { if details := request.DetailsFromContext(context.Request().Context()); details == nil { context.RespondWithError(service.ErrorUnauthenticated()) return } handler(context) } }
package testing import "k8s.io/kubernetes/pkg/util/iptables" type fake struct{} func NewFake() *fake { return &fake{} } func (*fake) EnsureChain(table iptables.Table, chain iptables.Chain) (bool, error) { return true, nil } func (*fake) FlushChain(table iptables.Table, chain iptables.Chain) error { return nil ...
{ return make([]byte, 0), nil }
package process import ( "net" "strconv" ) const ( MIN_PORT = 50000 MAX_PORT = 60000 INVALID_PORT = -1 ) func GetAvailablePort() (int, bool) { for port := MIN_PORT; port <= MAX_PORT; port++ { if !isPortUsed(port) { return port, true } } return INVALID_PORT, false } func isPortUsed(port i...
{ conn, err := net.Dial("tcp", net.JoinHostPort("localhost", strconv.Itoa(port))) if err != nil { return false } defer conn.Close() return true }
package lrucache import ( "testing" "time" "github.com/stretchr/testify/assert" ) func TestListMap_PushBack(t *testing.T) { m := NewListMap() t1 := time.Now().Nanosecond() t2 := time.Now().Nanosecond() m.PushBack(1, t1) m.PushFront(2, t2) v, _ := m.Get(1) assert.Equal(t, t1, v) v1, _ := m.Back() v2...
{ m := NewListMap() t1 := time.Now().Nanosecond() t2 := time.Now().Nanosecond() m.PushBack(1, t1) m.PushFront(2, t2) m.MoveToFront(1) v1, _ := m.Back() v2, _ := m.Front() assert.Equal(t, t2, v1) assert.Equal(t, t1, v2) }
package storage import ( "fmt" "github.com/apigee-labs/transicator/common" "strings" ) const ( EntryComparatorName = "transicator-entries-v1" SequenceComparatorName = "transicator-sequence-v1" ) var entryComparator = new(entryCmp) var sequenceComparator = new(sequenceCmp) type entryCmp struct { } func...
{ aScope, aLsn, aIndex, err := keyToLsnAndOffset(a) if err != nil { panic(fmt.Sprintf("Error parsing database key: %s", err)) } bScope, bLsn, bIndex, err := keyToLsnAndOffset(b) if err != nil { panic(fmt.Sprintf("Error parsing database key: %s", err)) } scopeCmp := strings.Compare(aScope, bScope) if scopeC...
package merkledag import ( "context" cid "gx/ipfs/QmPSQnBKM9g7BaUcZCvswUJVscQ1ipjmwxN5PXCjkp9EQ7/go-cid" ipld "gx/ipfs/QmR7TcHkR9nxkUorfi8XMTAMLUK7GiP64TWWBzY3aacc1o/go-ipld-format" ) type ErrorService struct { Err error } var _ ipld.DAGService = (*ErrorService)(nil) func (cs *ErrorService) Add(ctx context.C...
{ ch := make(chan *ipld.NodeOption) close(ch) return ch }
package models import ( "database/sql" "github.com/BrandonRomano/serf" db "github.com/carrot/burrow/db/postgres" "time" ) type Topic struct { serf.Worker `json:"-"` Id int64 `json:"id"` Name string `json:"name"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"upd...
{ t.Worker = &serf.PqWorker{ Database: db.Get(), Config: serf.Configuration{ TableName: "topics", Fields: []serf.Field{ serf.Field{Pointer: &t.Id, Name: "id", UniqueIdentifier: true, IsSet: func(pointer interface{}) bool { pointerInt := *pointer.(*int64) return pointerInt != 0 }, ...
package main import ( "bytes" "io/ioutil" "os" "path/filepath" "testing" . "gopkg.in/check.v1" ) func Test(t *testing.T) { TestingT(t) } type CommonTests struct { out *bytes.Buffer d *Dispatcher } var _ = Suite(&CommonTests{}) func (t *CommonTests) SetUpTest(c *C) { t.out = new(bytes.Buffer) t.d = &D...
{ files, err := ioutil.ReadDir(dir) if err != nil { return err } for _, file := range files { path := filepath.Join(dir, file.Name()) err = os.Remove(path) if err != nil { return err } } return nil }
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { sc := bufio.NewScanner(os.Stdin) sc.Split(bufio.ScanWords) n := nextInt(sc) a := nextInt(sc) b := nextInt(sc) answer := 0 for i := 1; i <= n; i++ { sum := 0 for _, s := range fmt.Sprintf("%d", i) { x, _ := strconv.Atoi(st...
{ fmt.Fprintf(os.Stderr, format, a...) }
package models import ( "sync" "github.com/eaciit/orm" ) type FuelTransport struct { sync.RWMutex orm.ModelBase `bson:"-" json:"-"` Plant string `bson:"Plant" json:"Plant"` Year int `bson:"Year" json:"Year"` TransportCost float64 `bson:"TransportCost" json:"TransportCost"` } func (m *...
{ return "FuelTransport" }
package models import ( "crawshaw.io/sqlite" "xorm.io/builder" itchio "github.com/itchio/go-itchio" "github.com/itchio/hades" ) type ProfileGame struct { GameID int64 `json:"gameId" hades:"primary_key"` Game *itchio.Game `json:"game,omitempty"` ProfileID int64 `json:"profileId" hades:"primary_key...
{ var pgs []*ProfileGame MustSelect(conn, &pgs, builder.Eq{"game_id": gameID}, hades.Search{}) return pgs }
package kernel import ( "fmt" "os/exec" "strings" ) func GetKernelVersion() (*VersionInfo, error) { osName, err := getSPSoftwareDataType() if err != nil { return nil, err } release, err := getRelease(osName) if err != nil { return nil, err } return ParseRelease(release) } func getSPSoftwareDataTyp...
{ var release string data := strings.Split(osName, "\n") for _, line := range data { if !strings.Contains(line, "Kernel Version") { continue } content := strings.SplitN(line, ":", 2) if len(content) != 2 { return "", fmt.Errorf("Kernel Version is invalid") } prettyNames := strings.SplitN(strings.T...
package util import ( "fmt" "os" "os/user" "strconv" ) func mkdir(paths []string) error { for _, path := range paths { err := os.MkdirAll(path, os.ModePerm) if err != nil { fmt.Printf("Make directory failed: %s\n", err) return err } } return nil } func chown(paths []string, userName string, gro...
{ err := mkdir(paths) if err != nil { return err } err = chown(paths, userName, groupName) if err != nil { return err } return nil }
package models import ( strfmt "github.com/go-openapi/strfmt" "github.com/go-openapi/errors" "github.com/go-openapi/swag" "github.com/go-openapi/validate" ) type SendPhotoLinkBody struct { Caption string `json:"caption,omitempty"` ChatID interface{} `json:"chat_id"` DisableNotification bool `json:"dis...
{ var res SendPhotoLinkBody if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil }
package main import ( "fmt" "reflect" ) type User struct{ Id int Name string Age int } func (u User) Hello(){ fmt.Println("Hello World.") } func main(){ var u User u = User{1, "ok", 12} info(u) } func info(o interface{})
{ t := reflect.TypeOf(o) fmt.Println("Type:", t.Name()) v := reflect.ValueOf(o) fmt.Println("Fields:") for i:= 0; i < t.NumField(); i++{ f := t.Field(i) val := v.Field(i).Interface() fmt.Printf("%6s: %v = %v\n", f.Name, f.Type, val) } for i:= 0; i < t.NumMethod...
package utils import ( "runtime" "strings" ) func GetTraceback() string
{ tb := make([]byte, 4096) stb := string(tb[:runtime.Stack(tb, false)]) lines := strings.Split(stb, "\n") for i := range lines { if strings.Contains(lines[i], "ServeHTTP") { return strings.Join(lines[4:i], "\n") } } return stb }