input
stringlengths
24
2.11k
output
stringlengths
7
948
package stick import ( "encoding/json" "fmt" "reflect" "strings" "go.mongodb.org/mongo-driver/bson" ) type Coding string const ( JSON Coding = "json" BSON Coding = "bson" ) func (c Coding) Marshal(in interface{}) ([]byte, error) { switch c { case JSON: return json.Marshal(in) case BSON: return bson.Marshal(in) default: panic(fmt.Sprintf("coal: unknown coding %q", c)) } } func (c Coding) Transfer(in, out interface{}) error { bytes, err := c.Marshal(in) if err != nil { return err } err = c.Unmarshal(bytes, out) if err != nil { return err } return nil } func GetJSONKey(field *reflect.StructField) string { tag := field.Tag.Get("json") if tag == "-" { return "" } values := strings.Split(tag, ",") if len(values) > 0 && len(values[0]) > 0 { return values[0] } return field.Name } func GetBSONKey(field *reflect.StructField) string { tag := field.Tag.Get("bson") if tag == "-" { return "" } values := strings.Split(tag, ",") if len(values) > 0 && len(values[0]) > 0 { return values[0] } return strings.ToLower(field.Name) } func (c Coding) Unmarshal(in []byte, out interface{}) error
{ switch c { case JSON: return json.Unmarshal(in, out) case BSON: return bson.Unmarshal(in, out) default: panic(fmt.Sprintf("coal: unknown coding %q", c)) } }
package main import ( "github.com/stretchr/testify/assert" "github.com/xtracdev/xavi/env" "github.com/xtracdev/xavi/plugin" "os" "testing" ) func TestPluginRegistration(t *testing.T) { registerPlugins() assert.True(t, plugin.RegistryContains("Logging")) } func TestXapHook(t *testing.T) { os.Setenv(env.LoggingOpts, "") err := addXapHook() assert.Nil(t, err) os.Setenv(env.LoggingOpts, env.Tcplog) err = addXapHook() assert.NotNil(t, err) os.Setenv(env.TcplogAddress, "parse this ### yes?") err = addXapHook() assert.NotNil(t, err) os.Setenv(env.TcplogAddress, "0.0.0.0:80") err = addXapHook() assert.NotNil(t, err) } func TestGrabCommandLineArgs(t *testing.T)
{ grabCommandLineArgs() }
package cron import ( "fmt" "github.com/Cepave/agent/g" "github.com/Cepave/common/model" "log" "time" ) func reportAgentStatus(interval time.Duration) { for { hostname, err := g.Hostname() if err != nil { hostname = fmt.Sprintf("error:%s", err.Error()) } req := model.AgentReportRequest{ Hostname: hostname, IP: g.IP(), AgentVersion: g.VERSION, PluginVersion: g.GetCurrPluginVersion(), } var resp model.SimpleRpcResponse err = g.HbsClient.Call("Agent.ReportStatus", req, &resp) if err != nil || resp.Code != 0 { log.Println("call Agent.ReportStatus fail:", err, "Request:", req, "Response:", resp) } time.Sleep(interval) } } func ReportAgentStatus()
{ if g.Config().Heartbeat.Enabled && g.Config().Heartbeat.Addr != "" { go reportAgentStatus(time.Duration(g.Config().Heartbeat.Interval) * time.Second) } }
package elements_test import ( "encoding/xml" "testing" "baliance.com/gooxml/schema/purl.org/dc/elements" ) func TestSimpleLiteralMarshalUnmarshal(t *testing.T) { v := elements.NewSimpleLiteral() buf, _ := xml.Marshal(v) v2 := elements.NewSimpleLiteral() xml.Unmarshal(buf, v2) } func TestSimpleLiteralConstructor(t *testing.T)
{ v := elements.NewSimpleLiteral() if v == nil { t.Errorf("elements.NewSimpleLiteral must return a non-nil value") } if err := v.Validate(); err != nil { t.Errorf("newly constructed elements.SimpleLiteral should validate: %s", err) } }
package network import ( "github.com/docker/docker/api/server/httputils" "github.com/docker/docker/api/server/router" ) type networkRouter struct { routes []router.Route } type networkRoute struct { path string handler httputils.APIFunc } func (l networkRoute) Handler() httputils.APIFunc { return l.handler } func (n networkRouter) Routes() []router.Route
{ return n.routes }
package main import ( "github.com/pebbe/zmq4/examples/mdapi" "errors" "fmt" "os" "time" ) func main() { var verbose bool if len(os.Args) > 1 && os.Args[1] == "-v" { verbose = true } session, _ := mdapi.NewMdcli("tcp:localhost:5555", verbose) reply, err := ServiceCall(session, "titanic.request", "echo", "Hello world") if err != nil { fmt.Println(err) return } var uuid string if err == nil { uuid = reply[0] fmt.Println("I: request UUID", uuid) } time.Sleep(100 * time.Millisecond) for { reply, err := ServiceCall(session, "titanic.reply", uuid) if err == nil { fmt.Println("Reply:", reply[0]) ServiceCall(session, "titanic.close", uuid) break } else { fmt.Println("I: no reply yet, trying again...") time.Sleep(5 * time.Second) } } } func ServiceCall(session *mdapi.Mdcli, service string, request ...string) (reply []string, err error)
{ reply = []string{} msg, err := session.Send(service, request...) if err == nil { switch status := msg[0]; status { case "200": reply = msg[1:] return case "400": fmt.Println("E: client fatal error, aborting") os.Exit(1) case "500": fmt.Println("E: server fatal error, aborting") os.Exit(1) } } else { fmt.Println("E: " + err.Error()) os.Exit(0) } err = errors.New("Didn't succeed") return }
package kms import ( "os" "github.com/denverdino/aliyungo/common" ) const ( KMSDefaultEndpoint = "https://kms.cn-hangzhou.aliyuncs.com" KMSAPIVersion = "2016-01-20" KMSServiceCode = "kms" ) type Client struct { common.Client } func NewClient(accessKeyId, accessKeySecret string) *Client { endpoint := os.Getenv("KMS_ENDPOINT") if endpoint == "" { endpoint = KMSDefaultEndpoint } return NewClientWithEndpoint(endpoint, accessKeyId, accessKeySecret) } func NewClientWithRegion(accessKeyId string, accessKeySecret string, regionID common.Region) *Client { endpoint := os.Getenv("KMS_ENDPOINT") if endpoint == "" { endpoint = KMSDefaultEndpoint } client := &Client{} client.NewInit(endpoint, KMSAPIVersion, accessKeyId, accessKeySecret, KMSServiceCode, regionID) return client } func NewClientWithEndpoint(endpoint string, accessKeyId string, accessKeySecret string) *Client { client := &Client{} client.Init(endpoint, KMSAPIVersion, accessKeyId, accessKeySecret) return client } func NewKMSClientWithEndpointAndSecurityToken(endpoint string, accessKeyId string, accessKeySecret string, securityToken string, regionID common.Region) *Client { client := &Client{} client.WithEndpoint(endpoint). WithVersion(KMSAPIVersion). WithAccessKeyId(accessKeyId). WithAccessKeySecret(accessKeySecret). WithSecurityToken(securityToken). WithServiceCode(KMSServiceCode). WithRegionID(regionID). InitClient() return client } func NewECSClientWithSecurityToken(accessKeyId string, accessKeySecret string, securityToken string, regionID common.Region) *Client
{ endpoint := os.Getenv("KMS_ENDPOINT") if endpoint == "" { endpoint = KMSDefaultEndpoint } return NewKMSClientWithEndpointAndSecurityToken(endpoint, accessKeyId, accessKeySecret, securityToken, regionID) }
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 (d *DummyBackendQueue) Put([]byte) error { return nil } func (d *DummyBackendQueue) ReadChan() chan []byte { return d.readChan } func (d *DummyBackendQueue) Close() error { return nil } func (d *DummyBackendQueue) Delete() error { return nil } func (d *DummyBackendQueue) Depth() int64 { return int64(0) } func (d *DummyBackendQueue) Empty() error { return nil } func WriteMessageToBackend(buf *bytes.Buffer, msg *nsq.Message, bq BackendQueue) error { buf.Reset() err := msg.Write(buf) if err != nil { return err } err = bq.Put(buf.Bytes()) if err != nil { return err } return nil } func NewDummyBackendQueue() BackendQueue
{ return &DummyBackendQueue{readChan: make(chan []byte)} }
package storage import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" genericapirequest "k8s.io/apiserver/pkg/request" "k8s.io/kubernetes/pkg/apis/batch" "k8s.io/kubernetes/pkg/genericapiserver/api/rest" "k8s.io/kubernetes/pkg/registry/batch/job" "k8s.io/kubernetes/pkg/registry/generic" genericregistry "k8s.io/kubernetes/pkg/registry/generic/registry" ) type JobStorage struct { Job *REST Status *StatusREST } func NewStorage(optsGetter generic.RESTOptionsGetter) JobStorage { jobRest, jobStatusRest := NewREST(optsGetter) return JobStorage{ Job: jobRest, Status: jobStatusRest, } } type REST struct { *genericregistry.Store } type StatusREST struct { store *genericregistry.Store } func (r *StatusREST) New() runtime.Object { return &batch.Job{} } func (r *StatusREST) Get(ctx genericapirequest.Context, name string, options *metav1.GetOptions) (runtime.Object, error) { return r.store.Get(ctx, name, options) } func (r *StatusREST) Update(ctx genericapirequest.Context, name string, objInfo rest.UpdatedObjectInfo) (runtime.Object, bool, error) { return r.store.Update(ctx, name, objInfo) } func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST)
{ store := &genericregistry.Store{ NewFunc: func() runtime.Object { return &batch.Job{} }, NewListFunc: func() runtime.Object { return &batch.JobList{} }, ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*batch.Job).Name, nil }, PredicateFunc: job.MatchJob, QualifiedResource: batch.Resource("jobs"), CreateStrategy: job.Strategy, UpdateStrategy: job.Strategy, DeleteStrategy: job.Strategy, } options := &generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: job.GetAttrs} if err := store.CompleteWithOptions(options); err != nil { panic(err) } statusStore := *store statusStore.UpdateStrategy = job.StatusStrategy return &REST{store}, &StatusREST{store: &statusStore} }
package client import ( "math" "math/rand" "time" "github.com/paybyphone/kintail/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request" ) type DefaultRetryer struct { NumMaxRetries int } func (d DefaultRetryer) RetryRules(r *request.Request) time.Duration { delay := int(math.Pow(2, float64(r.RetryCount))) * (rand.Intn(30) + 30) return time.Duration(delay) * time.Millisecond } func (d DefaultRetryer) ShouldRetry(r *request.Request) bool { if r.HTTPResponse.StatusCode >= 500 { return true } return r.IsErrorRetryable() } func (d DefaultRetryer) MaxRetries() int
{ return d.NumMaxRetries }
package vault import ( "fmt" "strings" ) type AuthType interface { Describe() string GetType() string getAuthConfig() map[string]interface{} getAuthMountConfig() map[string]interface{} Configure(c *VCClient) error TuneMount(c *VCClient, path string) error WriteUsers(c *VCClient) error WriteGroups(c *VCClient) error } func (c *VCClient) AuthExist(name string) bool { auth, err := c.Sys().ListAuth() if err != nil { return false } for a := range auth { if strings.TrimSuffix(a, "/") == name { return true } } return false } func Path(a AuthType) string { return fmt.Sprintf("auth/%s", a.GetType()) } func (c *VCClient) AuthConfigure(a AuthType) error { if err := a.WriteUsers(c); err != nil { return err } if err := a.WriteGroups(c); err != nil { return err } if err := a.TuneMount(c, Path(a)); err != nil { return err } if err := a.Configure(c); err != nil { return err } return nil } func EnableAndConfigure(a AuthType, c *VCClient) error { if !c.AuthExist(a.GetType()) { if err := c.AuthEnable(a); err != nil { return fmt.Errorf("Error enabling auth mount: %v", err) } } if err := c.AuthConfigure(a); err != nil { return fmt.Errorf("Error configuring auth mount: %v", err) } return nil } func (c *VCClient) AuthEnable(a AuthType) error
{ if err := c.Sys().EnableAuth(a.GetType(), a.GetType(), a.Describe()); err != nil { return err } return nil }
package nodes import "bufio" type Representation struct { Content string `bson:"c"` } func (r *Representation) Render(w *bufio.Writer) error
{ w.WriteString(r.Content) return nil }
package cluster_health import ( "fmt" "os" "testing" mbtest "github.com/elastic/beats/metricbeat/mb/testing" ) func TestData(t *testing.T) { f := mbtest.NewEventFetcher(t, getConfig()) err := mbtest.WriteEvent(f, t) if err != nil { t.Fatal("write", err) } } const ( cephDefaultHost = "127.0.0.1" cephDefaultPort = "5000" ) func getTestCephHost() string { return fmt.Sprintf("%v:%v", getenv("CEPH_HOST", cephDefaultHost), getenv("CEPH_PORT", cephDefaultPort), ) } func getenv(name, defaultValue string) string { return strDefault(os.Getenv(name), defaultValue) } func strDefault(a, defaults string) string { if len(a) == 0 { return defaults } return a } func getConfig() map[string]interface{}
{ return map[string]interface{}{ "module": "ceph", "metricsets": []string{"cluster_health"}, "hosts": getTestCephHost(), } }
package operations import ( "github.com/denkhaus/bitshares/types" "github.com/denkhaus/bitshares/util" "github.com/juju/errors" ) func init() { types.OperationMap[types.OperationTypeTransferFromBlind] = func() types.Operation { op := &TransferFromBlindOperation{} return op } } type TransferFromBlindOperation struct { types.OperationFee Amount types.AssetAmount `json:"amount"` To types.AccountID `json:"to"` BlindFactor types.FixedBuffer `json:"blinding_factor"` BlindInputs types.BlindInputs `json:"inputs"` } func (p TransferFromBlindOperation) Marshal(enc *util.TypeEncoder) error { if err := enc.Encode(int8(p.Type())); err != nil { return errors.Annotate(err, "encode OperationType") } if err := enc.Encode(p.Fee); err != nil { return errors.Annotate(err, "encode Fee") } if err := enc.Encode(p.Amount); err != nil { return errors.Annotate(err, "encode Amount") } if err := enc.Encode(p.To); err != nil { return errors.Annotate(err, "encode To") } if err := enc.Encode(p.BlindFactor); err != nil { return errors.Annotate(err, "encode BlindFactor") } if err := enc.Encode(p.BlindInputs); err != nil { return errors.Annotate(err, "encode BlindInputs") } return nil } func (p TransferFromBlindOperation) Type() types.OperationType
{ return types.OperationTypeTransferFromBlind }
package github import ( "strconv" "time" ) type Timestamp struct { time.Time } func (t *Timestamp) UnmarshalJSON(data []byte) (err error) { str := string(data) i, err := strconv.ParseInt(str, 10, 64) if err == nil { t.Time = time.Unix(i, 0) } else { t.Time, err = time.Parse(`"`+time.RFC3339+`"`, str) } return } func (t Timestamp) Equal(u Timestamp) bool { return t.Time.Equal(u.Time) } func (t Timestamp) String() string
{ return t.Time.String() }
package v1 import ( v1 "github.com/openshift/api/config/v1" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" ) type IdentityProviderLister interface { List(selector labels.Selector) (ret []*v1.IdentityProvider, err error) Get(name string) (*v1.IdentityProvider, error) IdentityProviderListerExpansion } type identityProviderLister struct { indexer cache.Indexer } func (s *identityProviderLister) List(selector labels.Selector) (ret []*v1.IdentityProvider, err error) { err = cache.ListAll(s.indexer, selector, func(m interface{}) { ret = append(ret, m.(*v1.IdentityProvider)) }) return ret, err } func (s *identityProviderLister) Get(name string) (*v1.IdentityProvider, error) { obj, exists, err := s.indexer.GetByKey(name) if err != nil { return nil, err } if !exists { return nil, errors.NewNotFound(v1.Resource("identityprovider"), name) } return obj.(*v1.IdentityProvider), nil } func NewIdentityProviderLister(indexer cache.Indexer) IdentityProviderLister
{ return &identityProviderLister{indexer: indexer} }
package cgo import ( "testing" ) func TestRead(t *testing.T) { testRead(t) } func TestWrite(t *testing.T)
{ testWrite(t) }
package v1beta3 import ( "github.com/GoogleCloudPlatform/kubernetes/pkg/api" ) func init()
{ api.Scheme.AddKnownTypes("v1beta3", &User{}, &UserList{}, &Identity{}, &IdentityList{}, &UserIdentityMapping{}, ) }
package log type logLevel struct { Level int Prefix string ColorFunc func(...interface{}) string } type logLevels []*logLevel func (l *logLevels) getLevel(Level int) *logLevel { for _, item := range *l { if item.Level == Level { return item } } return nil } func (l *logLevels) getFunc(Level int) func(...interface{}) string
{ level := l.getLevel(Level) if level != nil { return level.ColorFunc } return nil }
package main import ( "strings" "github.com/n0rad/go-erlog/errs" ) type envMap struct { mapping map[string]string } func (e *envMap) Set(s string) error { if e.mapping == nil { e.mapping = make(map[string]string) } pair := strings.SplitN(s, "=", 2) if len(pair) != 2 { return errs.With("environment variable must be specified as name=value") } e.mapping[pair[0]] = pair[1] return nil } func (e *envMap) Strings() []string { var env []string for n, v := range e.mapping { env = append(env, n+"="+v) } return env } func (e *envMap) Type() string { return "envMap" } func (e *envMap) String() string
{ return strings.Join(e.Strings(), "\n") }
package types import ( "fmt" "testing" "gopkg.in/yaml.v1" "github.com/stretchr/testify/assert" ) func newLocalDevicesObj() *LocalDevices { return &LocalDevices{ Driver: "vfs", DeviceMap: map[string]string{ "vfs-000": "/dev/xvda", "vfs-001": "/dev/xvdb", "vfs-002": "/dev/xvdc", }, } } var expectedLD1String = "vfs=vfs-000::/dev/xvda,vfs-001::/dev/xvdb,vfs-002::/dev/xvdc" func TestLocalDevicesUnmarshalText(t *testing.T) { ld1 := &LocalDevices{} err := ld1.UnmarshalText([]byte("scaleio=")) assert.NoError(t, err) } func TestLocalDevicesMarshalJSON(t *testing.T) { ld1 := newLocalDevicesObj() buf, err := ld1.MarshalJSON() assert.NoError(t, err) t.Logf("localDevices=%s", string(buf)) ld2 := &LocalDevices{} assert.NoError(t, ld2.UnmarshalJSON(buf)) assert.EqualValues(t, ld1, ld2) } func TestLocalDevicesMarshalToYAML(t *testing.T) { out, err := yaml.Marshal(newLocalDevicesObj()) if err != nil { t.Fatal(err) } fmt.Println(string(out)) } func TestLocalDevicesMarshalText(t *testing.T)
{ ld1 := newLocalDevicesObj() assert.Equal(t, expectedLD1String, ld1.String()) t.Logf("localDevices=%s", ld1) ld2 := &LocalDevices{} assert.NoError(t, ld2.UnmarshalText([]byte(ld1.String()))) assert.EqualValues(t, ld1, ld2) }
package common import ( "fmt" "os" "runtime" "runtime/debug" "strings" ) func Report(extra ...interface{}) { fmt.Fprintln(os.Stderr, "You've encountered a sought after, hard to reproduce bug. Please report this to the developers <3 https:github.com/WhaleCoinOrg/WhaleCoin/issues") fmt.Fprintln(os.Stderr, extra...) _, file, line, _ := runtime.Caller(1) fmt.Fprintf(os.Stderr, "%v:%v\n", file, line) debug.PrintStack() fmt.Fprintln(os.Stderr, "#### BUG! PLEASE REPORT ####") } func PrintDepricationWarning(str string)
{ line := strings.Repeat("#", len(str)+4) emptyLine := strings.Repeat(" ", len(str)) fmt.Printf(` %s # %s # # %s # # %s # %s `, line, emptyLine, str, emptyLine, line) }
package job import ( "context" "github.com/google/gapid/core/data/search" "github.com/google/gapid/core/event" "github.com/google/gapid/core/net/grpcutil" "github.com/google/gapid/core/os/device" "google.golang.org/grpc" ) type remote struct { client ServiceClient } func NewRemote(ctx context.Context, conn *grpc.ClientConn) Manager { return &remote{client: NewServiceClient(conn)} } func (m *remote) SearchDevices(ctx context.Context, query *search.Query, handler DeviceHandler) error { stream, err := m.client.SearchDevices(ctx, query) if err != nil { return err } return event.Feed(ctx, event.AsHandler(ctx, handler), grpcutil.ToProducer(stream)) } func (m *remote) GetWorker(ctx context.Context, host *device.Instance, target *device.Instance, op Operation) (*Worker, error) { request := &GetWorkerRequest{Host: host, Target: target, Operation: op} response, err := m.client.GetWorker(ctx, request) if err != nil { return nil, err } return response.Worker, nil } func (m *remote) SearchWorkers(ctx context.Context, query *search.Query, handler WorkerHandler) error
{ stream, err := m.client.SearchWorkers(ctx, query) if err != nil { return err } return event.Feed(ctx, event.AsHandler(ctx, handler), grpcutil.ToProducer(stream)) }
package bunyan import "os" type Sink interface { Write(record Record) error } type funcSink struct { write func(record Record) error } func (sink *funcSink) Write(record Record) error { return sink.write(record) } func SinkFunc(write func(record Record) error) Sink { return &funcSink{write} } func InfoSink(target Sink, info Info) Sink { return SinkFunc(func(record Record) error { record.SetIfNot(info.Key(), info.Value()) return target.Write(record) }) } func StdoutSink() Sink { return NewJsonSink(os.Stdout) } func FileSink(path string) Sink { const flags = os.O_CREATE | os.O_APPEND | os.O_WRONLY file, e := os.OpenFile(path, flags, 0666) if e != nil { panic(e) } return NewJsonSink(file) } func NilSink() Sink
{ return SinkFunc(func(record Record) error { return nil }) }
package model import ( "fmt" native_time "time" ) type Timestamp int64 const ( MinimumTick = native_time.Second second = int64(native_time.Second / MinimumTick) ) func (t Timestamp) Equal(o Timestamp) bool { return t == o } func (t Timestamp) Before(o Timestamp) bool { return t < o } func (t Timestamp) After(o Timestamp) bool { return t > o } func (t Timestamp) Add(d native_time.Duration) Timestamp { return t + Timestamp(d/MinimumTick) } func (t Timestamp) Sub(o Timestamp) native_time.Duration { return native_time.Duration(t-o) * MinimumTick } func (t Timestamp) Time() native_time.Time { return native_time.Unix(int64(t)/second, (int64(t) % second)) } func (t Timestamp) Unix() int64 { return int64(t) / second } func (t Timestamp) String() string { return fmt.Sprint(int64(t)) } func Now() Timestamp { return TimestampFromTime(native_time.Now()) } func TimestampFromTime(t native_time.Time) Timestamp { return TimestampFromUnix(t.Unix()) } func TimestampFromUnix(t int64) Timestamp
{ return Timestamp(t * second) }
package databasemigration import ( "github.com/oracle/oci-go-sdk/v46/common" ) type WorkRequestErrorCollection struct { Items []WorkRequestError `mandatory:"true" json:"items"` } func (m WorkRequestErrorCollection) String() string
{ return common.PointerString(m) }
package s2 var ( _ Shape = (*PointVector)(nil) ) type PointVector []Point func (p *PointVector) NumEdges() int { return len(*p) } func (p *PointVector) Edge(i int) Edge { return Edge{(*p)[i], (*p)[i]} } func (p *PointVector) ReferencePoint() ReferencePoint { return OriginReferencePoint(false) } func (p *PointVector) NumChains() int { return len(*p) } func (p *PointVector) Chain(i int) Chain { return Chain{i, 1} } func (p *PointVector) ChainEdge(i, j int) Edge { return Edge{(*p)[i], (*p)[j]} } func (p *PointVector) ChainPosition(e int) ChainPosition { return ChainPosition{e, 0} } func (p *PointVector) Dimension() int { return 0 } func (p *PointVector) IsEmpty() bool { return defaultShapeIsEmpty(p) } func (p *PointVector) IsFull() bool { return defaultShapeIsFull(p) } func (p *PointVector) privateInterface() {} func (p *PointVector) typeTag() typeTag
{ return typeTagPointVector }
package wire 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() []byte { return w.b } func newFixedWriter(max int) io.Writer { b := make([]byte, max) fw := fixedWriter{b, 0} return &fw } type fixedReader struct { buf []byte pos int iobuf *bytes.Buffer } func (fr *fixedReader) Read(p []byte) (n int, err error) { n, err = fr.iobuf.Read(p) fr.pos += n return } func newFixedReader(max int, buf []byte) io.Reader
{ b := make([]byte, max) if buf != nil { copy(b, buf) } iobuf := bytes.NewBuffer(b) fr := fixedReader{b, 0, iobuf} return &fr }
package coap import ( "encoding/binary" "errors" "io" ) type TcpMessage struct { Message } func (m *TcpMessage) UnmarshalBinary(data []byte) error { if len(data) < 4 { return errors.New("short packet") } return m.Message.UnmarshalBinary(data) } func Decode(r io.Reader) (*TcpMessage, error) { var ln uint16 err := binary.Read(r, binary.BigEndian, &ln) if err != nil { return nil, err } packet := make([]byte, ln) _, err = io.ReadFull(r, packet) if err != nil { return nil, err } m := TcpMessage{} err = m.UnmarshalBinary(packet) return &m, err } func (m *TcpMessage) MarshalBinary() ([]byte, error)
{ bin, err := m.Message.MarshalBinary() if err != nil { return nil, err } l := []byte{0, 0} binary.BigEndian.PutUint16(l, uint16(len(bin))) return append(l, bin...), nil }
package constraint import ( "fmt" "github.com/hashicorp/go-multierror" ) type ExactlyOne struct { Constraints []Check } var _ Range = &ExactlyOne{} func (e *ExactlyOne) ValidateItems(arr []interface{}, p Params) error
{ var matches int var err error mainloop: for _, a := range arr { for _, c := range e.Constraints { er := c.ValidateItem(a, p) if er != nil { err = multierror.Append(err, er) continue mainloop } } matches++ } switch matches { case 0: err = multierror.Append(err, fmt.Errorf("no item matched constraints: %v", arr)) return multierror.Flatten(err) case 1: return nil default: return fmt.Errorf("multiple items(%d) matched constraints: %v", matches, arr) } }
package colorable import ( "io" "os" ) func NewColorableStdout() io.Writer { return os.Stdout } func NewColorableStderr() io.Writer { return os.Stderr } func NewColorable(file *os.File) io.Writer
{ if file == nil { panic("nil passed instead of *os.File to NewColorable()") } return file }
package s3storage import ( "testing" "github.com/AdRoll/goamz/aws" "github.com/AdRoll/goamz/s3" "github.com/AdRoll/goamz/s3/s3test" "github.com/facebookgo/ensure" ) type MockS3 struct { auth aws.Auth region aws.Region srv *s3test.Server config *s3test.Config } func (s *MockS3) Start(t *testing.T) { srv, err := s3test.NewServer(s.config) ensure.Nil(t, err) ensure.NotNil(t, srv) s.srv = srv s.region = aws.Region{ Name: "faux-region-1", S3Endpoint: srv.URL(), S3LocationConstraint: true, } } func (s *MockS3) Stop() { s.srv.Quit() } func NewMockS3(t *testing.T) *MockS3 { m := MockS3{} m.Start(t) return &m } func NewStorageWithMockS3(s *MockS3) (*S3Storage, error)
{ return NewS3Storage(s.region, s.auth, "testbucket", "test", s3.Private) }
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 { return &keysQuerySet{ querySet: &querySet{ rorm: r, key: key, }, } } func (r *rorm) QueryString(key string) StringQuerySeter { return &stringQuerySet{ querySet: &querySet{ rorm: r, key: key, }, } } func (r *rorm) QueryZSet(key string) ZSetQuerySeter { return &zsetQuerySet{ querySet: &querySet{ rorm: r, key: key, }, } } func (r *rorm) QuerySet(key string) SetQuerySeter { return &setQuerySet{ querySet: &querySet{ rorm: r, key: key, }, } } func (r rorm) Using(alias string) ROrmer { client, ok := redisRegistry[alias] if !ok { panic("using reids '" + alias + "' not exist.") } r.redisQuerier = &RedisQuerier{ Client: client, } return &r } func (r *rorm) Querier() Querier
{ return r.redisQuerier }
package main import ("log"; "net") func main() { ln, err := net.Listen("tcp", ":6000") if err != nil { log.Fatal(err) } for { conn, err := ln.Accept() if err != nil { log.Println(err) continue } go handleConnection(conn) } } func handleConnection(c net.Conn)
{ buf := make([]byte, 4096) for { n, err := c.Read(buf) if err != nil || n == 0 { c.Close() break } n, err = c.Write(buf[0:n]) if err != nil { c.Close() break } } log.Printf("Connection from %v closed.", c.RemoteAddr()) }
package cacheval import ( "math/rand" "sync" "testing" "time" "github.com/stretchr/testify/assert" ) func TestInt32Stress(t *testing.T) { const valid = 10 * time.Millisecond const delay = 1 * time.Millisecond const concurrency = 50 const N = 500 cv := Int32{} cv.Init(valid) wg := sync.WaitGroup{} wg.Add(concurrency) passive := func() { max := int32(0) for j := 1; j <= N; j++ { v, ok := cv.GetFresh() if v > max { max = v } else if ok && v < max { t.Error("unexpected decrease") } time.Sleep(delay) } wg.Done() } for i := 1; i <= concurrency; i++ { go passive() } for j := 1; j <= N; j++ { prev := cv.Get() cv.GetOrUpdate(func() { cv.Set(prev + 1) }) time.Sleep(delay) } wg.Wait() } func TestInt32Valid(t *testing.T)
{ t.Parallel() rand := rand.New(rand.NewSource(time.Now().UnixNano())) const valid = 100 * time.Millisecond cv := Int32{} cv.Init(valid) assert.Equal(t, int32(0), cv.Get()) v, ok := cv.GetFresh() assert.Equal(t, int32(0), v) assert.Equal(t, false, ok) expect := int32(rand.Uint32()) cv.Set(expect) v, ok = cv.GetFresh() assert.Equal(t, expect, v) assert.Equal(t, true, ok) time.Sleep(valid) v = cv.GetOrUpdate(func() { cv.Set(expect + 1) }) assert.Equal(t, expect+1, v) assert.Equal(t, expect+1, cv.Get()) }
package toJson import ( "encoding/json" "fmt" "net/http" ) func WriteToJson(w http.ResponseWriter, obj interface{}) error { return WriteToJsonWithCode(w, obj, http.StatusOK) } func WriteToJsonWithCode(w http.ResponseWriter, obj interface{}, code int) error { o, err := ToJson(obj) if err != nil { writeError(err) return err } wrapped := map[string]interface{}{"result": o} return WriteJson(w, &wrapped, code) } func WriteToJsonNotWrappedWithCode(w http.ResponseWriter, obj interface{}, code int) error { o, err := ToJson(obj) if err != nil { writeError(err) return err } return WriteJson(w, &o, code) } func WriteJson(w http.ResponseWriter, obj interface{}, code int) error { marshalled, err := json.MarshalIndent(obj, "", " ") if err != nil { writeError(err) return err } data := []byte(fmt.Sprintf("%s\n", marshalled)) w.Header().Set("Content-Type", "application/json; charset=utf-8") w.Header().Set("Content-Length", fmt.Sprint(len(data))) w.WriteHeader(code) w.Write(data) return nil } func WriteToJsonNotWrapped(w http.ResponseWriter, obj interface{}) error
{ return WriteToJsonNotWrappedWithCode(w, obj, http.StatusOK) }
package client import ( atlantis "atlantis/common" . "atlantis/manager/constant" ) type ManagerRPCClient struct { atlantis.RPCClient User string Secrets map[string]string } type AuthedArg interface { SetCredentials(string, string) } func (r *ManagerRPCClient) CallAuthed(name string, arg AuthedArg, reply interface{}) error { return r.CallAuthedMulti(name, arg, 0, reply) } func (r *ManagerRPCClient) CallAuthedMulti(name string, arg AuthedArg, region int, reply interface{}) error { arg.SetCredentials(r.User, r.Secrets[r.Opts[region].RPCHostAndPort()]) return r.RPCClient.CallMulti(name, arg, region, reply) } func NewManagerRPCClient(hostAndPort string) *atlantis.RPCClient { return atlantis.NewRPCClient(hostAndPort, "ManagerRPC", ManagerRPCVersion, true) } func NewManagerRPCClientWithConfig(cfg []atlantis.RPCServerOpts) *atlantis.RPCClient
{ return atlantis.NewMultiRPCClientWithConfig(cfg, "ManagerRPC", ManagerRPCVersion, true) }
package retry import ( "context" "k8s.io/apimachinery/pkg/util/wait" ) type ConditionWithContextFunc func(ctx context.Context) (done bool, err error) func ExponentialBackoffWithContext(ctx context.Context, backoff wait.Backoff, condition ConditionWithContextFunc) error
{ return wait.ExponentialBackoff(backoff, func() (bool, error) { select { case <-ctx.Done(): return false, wait.ErrWaitTimeout default: return condition(ctx) } }) }
package core import ( "os"; "container/list"; "net"; "log"; "irc"; "runloop"; ) type Network struct { name string; server *server; clients *list.List; listen *listenConn; } func newNetwork(name string, serverConn net.Conn, listen net.Listener) *Network { var network *Network; accept := func(conn net.Conn) { runloop.CallLater(func() { network.addClient(conn) }) }; error := func(err os.Error) { }; l := newListenConn(listen, accept, error); network = &Network{name: name, clients: list.New(), listen: l}; network.server = newServer(serverConn, network); return network; } func (network *Network) addClient(conn net.Conn) { client := newClient(conn, network); network.clients.PushBack(client); log.Stderrf("client connected from %s\n", conn.RemoteAddr()); } func (network *Network) SendToServer(msg *irc.Message) { if network.server != nil { network.server.Send(msg) } } func (network *Network) SendNoticeToClient(conn Conn, line string) { nick := "bouncin"; conn.Send(&irc.Message{Command: "NOTICE", Params: []string{nick, line}}); } var networks = make(map[string] *Network); func AddNetwork(name string, server net.Conn, listen net.Listener) *Network { network := newNetwork(name, server, listen); networks[name] = network; return network; } func (network *Network) SendToClients(msg *irc.Message)
{ for c := range network.clients.Iter() { c.(*client).Send(msg) } }
package misc import "errors" func Mkfifo(path string, mode uint32) (err error) { return errors.New("not supported") } func Mksocket(path string) (err error)
{ return errors.New("not supported") }
package main import ( "net/http" "github.com/go-chi/chi" ) type todosResource struct{} func (rs todosResource) Routes() chi.Router { r := chi.NewRouter() r.Get("/", rs.List) r.Post("/", rs.Create) r.Put("/", rs.Delete) r.Route("/{id}", func(r chi.Router) { r.Get("/", rs.Get) r.Put("/", rs.Update) r.Delete("/", rs.Delete) r.Get("/sync", rs.Sync) }) return r } func (rs todosResource) List(w http.ResponseWriter, r *http.Request) { w.Write([]byte("todos list of stuff..")) } func (rs todosResource) Create(w http.ResponseWriter, r *http.Request) { w.Write([]byte("todos create")) } func (rs todosResource) Get(w http.ResponseWriter, r *http.Request) { w.Write([]byte("todo get")) } func (rs todosResource) Update(w http.ResponseWriter, r *http.Request) { w.Write([]byte("todo update")) } func (rs todosResource) Delete(w http.ResponseWriter, r *http.Request) { w.Write([]byte("todo delete")) } func (rs todosResource) Sync(w http.ResponseWriter, r *http.Request)
{ w.Write([]byte("todo sync")) }
package actor type restartingStrategy struct{} func (strategy *restartingStrategy) HandleFailure(actorSystem *ActorSystem, supervisor Supervisor, child *PID, rs *RestartStatistics, reason interface{}, message interface{}) { logFailure(actorSystem, child, reason, RestartDirective) supervisor.RestartChildren(child) } func NewRestartingStrategy() SupervisorStrategy
{ return &restartingStrategy{} }
package main import ( "fmt" _ "github.com/go-training/training/example16-init-func/bar" _ "github.com/go-training/training/example16-init-func/foo" ) var global = convert() func convert() int { return 100 } func main() { fmt.Println("global is", global) } func init()
{ global = 0 }
package main import "github.com/containerd/containerd/cmd/ctr/commands/shim" func init()
{ extraCmds = append(extraCmds, shim.Command) }
package filehash import ( "crypto/sha1" "fmt" "os" "github.com/cloudfoundry/gofileutils/fileutils" ) type Hash []byte func Zero() Hash { return Hash(make([]byte, sha1.Size)) } func New(filePath string) Hash { fileInfo, err := os.Lstat(filePath) if err != nil { panic(err) } if fileInfo.IsDir() { panic("cannot compute hash of directory") } else { hash := sha1.New() err = fileutils.CopyPathToWriter(filePath, hash) if err != nil { panic(err) } return Hash(hash.Sum(nil)) } } func (k Hash) String() string { return fmt.Sprintf("%x", string(k)) } func StringToHash(s string) Hash { var sh string if _, err := fmt.Sscanf(s, "%x", &sh); err != nil { panic(err) } return Hash(sh) } func (h1 Hash) Combine(h2 Hash) { if len(h1) != len(h2) { panic("Invalid hash length") } for i, b := range h1 { h1[i] = b ^ h2[i] } } func (h1 Hash) Remove(h2 Hash)
{ h1.Combine(h2) }
package main import "fmt" func main() { validate("aaaaa", "aaaaa", true) validate("aaaab", "aaaab", true) validate("aaaabc", "aaaab", false) validate("aaaa", "a*", true) validate("aaaabbb", "a*bbb", true) } func validate(s string, p string, want bool) { fmt.Printf("s: %s, p: %s, want: %t, got: %t\n", s, p, want, IsMatch(s, p)) } func IsMatch(s string, p string) bool
{ if len(p) == 0 { return len(s) == 0 } first := len(s) != 0 && (s[0] == p[0] || p[0] == '.') if len(p) > 1 && p[1] == '*' { return (first && IsMatch(s[1:], p)) || (IsMatch(s, p[2:])) } return first && IsMatch(s[1:], p[1:]) }
package conn import ( "fmt" "net" "sync" "sync/atomic" ) type ConnectRequest struct { id uint64 Address net.Addr Permanent bool Conn net.Conn state ConnectState lock sync.RWMutex retryCount uint32 } func (connectRequest *ConnectRequest) updateState(state ConnectState) { connectRequest.lock.Lock() defer connectRequest.lock.Unlock() connectRequest.state = state } func (connectRequest *ConnectRequest) State() ConnectState { connectRequest.lock.RLock() defer connectRequest.lock.RUnlock() return connectRequest.state } func (connectRequest *ConnectRequest) String() string { if connectRequest.Address.String() == "" { return fmt.Sprintf("reqid %d", atomic.LoadUint64(&connectRequest.id)) } return fmt.Sprintf("%s (reqid %d)", connectRequest.Address, atomic.LoadUint64(&connectRequest.id)) } func (connectRequest *ConnectRequest) ID() uint64
{ return atomic.LoadUint64(&connectRequest.id) }
package image import ( "github.com/dnephin/dobi/tasks/context" ) func RunRemove(ctx *context.ExecuteContext, t *Task, _ bool) (bool, error)
{ removeTag := func(tag string) error { if err := ctx.Client.RemoveImage(tag); err != nil { t.logger().Warnf("failed to remove %q: %s", tag, err) } return nil } if err := t.ForEachTag(ctx, removeTag); err != nil { return false, err } if err := updateImageRecord(recordPath(ctx, t.config), imageModifiedRecord{}); err != nil { t.logger().Warnf("Failed to clear image record: %s", err) } t.logger().Info("Removed") return true, nil }
package ivona_test import ( "log" ivona "github.com/jpadilla/ivona-go" ) func ExampleIvona_CreateSpeech() { client := ivona.New("IVONA_ACCESS_KEY", "IVONA_SECRET_KEY") options := ivona.NewSpeechOptions("Hello World") r, err := client.CreateSpeech(options) if err != nil { log.Fatal(err) } log.Printf("%v\n", len(r.Audio)) log.Printf("%v\n", r.ContentType) log.Printf("%v\n", r.RequestID) } func ExampleIvona_ListVoices()
{ client := ivona.New("IVONA_ACCESS_KEY", "IVONA_SECRET_KEY") r, err := client.ListVoices(ivona.Voice{}) if err != nil { log.Fatal(err) } log.Printf("%v\n", len(r.Voices)) }
package wire 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 newFixedWriter(max int) io.Writer { b := make([]byte, max) fw := fixedWriter{b, 0} return &fw } type fixedReader struct { buf []byte pos int iobuf *bytes.Buffer } func (fr *fixedReader) Read(p []byte) (n int, err error) { n, err = fr.iobuf.Read(p) fr.pos += n return } func newFixedReader(max int, buf []byte) io.Reader { b := make([]byte, max) if buf != nil { copy(b[:], buf) } iobuf := bytes.NewBuffer(b) fr := fixedReader{b, 0, iobuf} return &fr } func (w *fixedWriter) Bytes() []byte
{ return w.b }
package cloudguard import ( "github.com/oracle/oci-go-sdk/v46/common" "net/http" ) type UpdateManagedListRequest struct { ManagedListId *string `mandatory:"true" contributesTo:"path" name:"managedListId"` UpdateManagedListDetails `contributesTo:"body"` IfMatch *string `mandatory:"false" contributesTo:"header" name:"if-match"` OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"` OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"` RequestMetadata common.RequestMetadata } func (request UpdateManagedListRequest) String() string { return common.PointerString(request) } func (request UpdateManagedListRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) { return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders) } func (request UpdateManagedListRequest) RetryPolicy() *common.RetryPolicy { return request.RequestMetadata.RetryPolicy } type UpdateManagedListResponse struct { RawResponse *http.Response ManagedList `presentIn:"body"` Etag *string `presentIn:"header" name:"etag"` OpcRequestId *string `presentIn:"header" name:"opc-request-id"` } func (response UpdateManagedListResponse) String() string { return common.PointerString(response) } func (response UpdateManagedListResponse) HTTPResponse() *http.Response { return response.RawResponse } func (request UpdateManagedListRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool)
{ return nil, false }
package main import ( "fmt" _ "ServiceTree/docs" _ "ServiceTree/routers" "github.com/astaxie/beego" "github.com/astaxie/beego/orm" _ "github.com/go-sql-driver/mysql" ) func main() { if beego.RunMode == "dev" { beego.DirectoryIndex = true beego.StaticDir["/swagger"] = "swagger" } beego.Run() } func init()
{ db_type := beego.AppConfig.String("database::db_type") db_user := beego.AppConfig.String("database::username") db_password := beego.AppConfig.String("database::password") db_host := beego.AppConfig.String("database::host") db_port := beego.AppConfig.String("database::port") db_name := beego.AppConfig.String("database::dbname") connect_str := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s",db_user, db_password, db_host, db_port, db_name) beego.SetLogger("file", `{"filename":"./logs/tree.log"}`) orm.RegisterDataBase("default", db_type, connect_str) }
package os const ( PathSeparator = '/' PathListSeparator = ':' ) func IsPathSeparator(c uint8) bool
{ return PathSeparator == c }
package floatingips import "github.com/gophercloud/gophercloud" const resourcePath = "floatingips" func rootURL(c *gophercloud.ServiceClient) string { return c.ServiceURL(resourcePath) } func resourceURL(c *gophercloud.ServiceClient, id string) string
{ return c.ServiceURL(resourcePath, id) }
package pes import "io" import "bytes" import "github.com/32bitkid/bitreader" type payloadReader struct { br bitreader.BitReader currentPacket *Packet remainder bytes.Buffer } func (r *payloadReader) Read(p []byte) (n int, err error) { for len(p) > 0 { cn, err := r.remainder.Read(p) n += cn p = p[cn:] if err == io.EOF { break } else if err != nil { return n, err } } var remainder []byte for len(p) > 0 { err := r.currentPacket.Next(r.br) if err != nil { return n, err } cn := copy(p, r.currentPacket.Payload) n += cn p = p[cn:] remainder = r.currentPacket.Payload[cn:] } _, err = r.remainder.Write(remainder) return } func NewPayloadReader(source io.Reader) io.Reader
{ return &payloadReader{ br: bitreader.NewReader(source), currentPacket: new(Packet), } }
package Plugin import "github.com/MPjct/GoMP/MySQLProtocol" type Plugin_interface interface { init(context MySQLProtocol.Context) read_handshake(context MySQLProtocol.Context) send_handshake(context MySQLProtocol.Context) read_auth(context MySQLProtocol.Context) send_auth(context MySQLProtocol.Context) read_auth_result(context MySQLProtocol.Context) send_auth_result(context MySQLProtocol.Context) read_query(context MySQLProtocol.Context) send_query(context MySQLProtocol.Context) read_query_result(context MySQLProtocol.Context) send_query_result(context MySQLProtocol.Context) cleanup(context MySQLProtocol.Context) } type Plugin struct { } func (plugin *Plugin) init(context MySQLProtocol.Context) { return } func (plugin *Plugin) send_handshake(context MySQLProtocol.Context) { return } func (plugin *Plugin) read_auth(context MySQLProtocol.Context) { return } func (plugin *Plugin) send_auth(context MySQLProtocol.Context) { return } func (plugin *Plugin) read_auth_result(context MySQLProtocol.Context) { return } func (plugin *Plugin) send_auth_result(context MySQLProtocol.Context) { return } func (plugin *Plugin) read_query(context MySQLProtocol.Context) { return } func (plugin *Plugin) send_query(context MySQLProtocol.Context) { return } func (plugin *Plugin) read_query_result(context MySQLProtocol.Context) { return } func (plugin *Plugin) send_query_result(context MySQLProtocol.Context) { return } func (plugin *Plugin) cleanup(context MySQLProtocol.Context) { return } func (plugin *Plugin) read_handshake(context MySQLProtocol.Context)
{ return }
package builders import ( "time" "github.com/docker/docker/api/types" ) func Container(name string, builders ...func(container *types.Container)) *types.Container { container := &types.Container{ ID: "container_id", Names: []string{"/" + name}, Command: "top", Image: "busybox:latest", Status: "Up 1 second", Created: time.Now().Unix(), } for _, builder := range builders { builder(container) } return container } func WithLabel(key, value string) func(*types.Container) { return func(c *types.Container) { if c.Labels == nil { c.Labels = map[string]string{} } c.Labels[key] = value } } func WithName(name string) func(*types.Container) { return func(c *types.Container) { c.Names = append(c.Names, "/"+name) } } func WithPort(privateport, publicport uint16, builders ...func(*types.Port)) func(*types.Container) { return func(c *types.Container) { if c.Ports == nil { c.Ports = []types.Port{} } port := &types.Port{ PrivatePort: privateport, PublicPort: publicport, } for _, builder := range builders { builder(port) } c.Ports = append(c.Ports, *port) } } func IP(ip string) func(*types.Port) { return func(p *types.Port) { p.IP = ip } } func TCP(p *types.Port) { p.Type = "tcp" } func UDP(p *types.Port)
{ p.Type = "udp" }
package matchers import ( "fmt" "github.com/bfontaine/go-tchoutchou/Godeps/_workspace/src/github.com/onsi/gomega/format" ) type SucceedMatcher struct { } func (matcher *SucceedMatcher) FailureMessage(actual interface{}) (message string) { return fmt.Sprintf("Expected success, but got an error:\n%s", format.Object(actual, 1)) } func (matcher *SucceedMatcher) NegatedFailureMessage(actual interface{}) (message string) { return "Expected failure, but got no error." } func (matcher *SucceedMatcher) Match(actual interface{}) (success bool, err error)
{ if actual == nil { return true, nil } if isError(actual) { return false, nil } return false, fmt.Errorf("Expected an error-type. Got:\n%s", format.Object(actual, 1)) }
package uguis import ( "fmt" "os/exec" ) const serviceNameSimplePlayer = "simplePlayer" type simplePlayer struct { command string reqC chan PlayerRequest resC chan PlayerResponse closedReqC chan struct{} app *Application lgr Logger } func (p *simplePlayer) Play(req PlayerRequest) { p.reqC <- req } func (p *simplePlayer) Close() error { close(p.reqC) <-p.closedReqC return nil } func (p *simplePlayer) ResC() <-chan PlayerResponse { return p.resC } func (p *simplePlayer) logError(err error) { p.lgr.Print(NewLog( LogLevelERROR, p.app.Hostname, serviceNameSimplePlayer, err.Error(), )) } func NewSimplePlayer( command string, app *Application, lgr Logger, opts *SimplePlayerOptions, ) Player { if opts == nil { opts = &SimplePlayerOptions{} } opts.setDefaults() p := &simplePlayer{ command: command, reqC: make(chan PlayerRequest, opts.ReqCBfSize), resC: make(chan PlayerResponse, opts.ResCBfSize), closedReqC: make(chan struct{}), app: app, lgr: lgr, } go p.play() return p } func (p *simplePlayer) play()
{ for req := range p.reqC { p.lgr.Print(NewLog( LogLevelINFO, p.app.Hostname, serviceNameSimplePlayer, fmt.Sprintf("%s by %s(@%s)", req.tweet.Text, req.tweet.User.Name, req.tweet.User.ScreenName), )) path := req.path if err := exec.Command(p.command, path).Run(); err != nil { p.logError(err) continue } p.resC <- NewPlayerResponse(req.tweet, path) } p.closedReqC <- struct{}{} }
package client import ( "encoding/json" "fmt" "io" "io/ioutil" "net/http" "github.com/docker/distribution/registry/api/errcode" "github.com/docker/distribution/registry/api/v2" ) type UnexpectedHTTPStatusError struct { Status string } func (e *UnexpectedHTTPStatusError) Error() string { return fmt.Sprintf("Received unexpected HTTP status: %s", e.Status) } type UnexpectedHTTPResponseError struct { ParseErr error Response []byte } func parseHTTPErrorResponse(r io.Reader) error { var errors errcode.Errors body, err := ioutil.ReadAll(r) if err != nil { return err } if err := json.Unmarshal(body, &errors); err != nil { return &UnexpectedHTTPResponseError{ ParseErr: err, Response: body, } } return errors } func handleErrorResponse(resp *http.Response) error { if resp.StatusCode == 401 { err := parseHTTPErrorResponse(resp.Body) if uErr, ok := err.(*UnexpectedHTTPResponseError); ok { return v2.ErrorCodeUnauthorized.WithDetail(uErr.Response) } return err } if resp.StatusCode >= 400 && resp.StatusCode < 500 { return parseHTTPErrorResponse(resp.Body) } return &UnexpectedHTTPStatusError{Status: resp.Status} } func (e *UnexpectedHTTPResponseError) Error() string
{ return fmt.Sprintf("Error parsing HTTP response: %s: %q", e.ParseErr.Error(), string(e.Response)) }
package main import ( "fmt" "net/http" "github.com/gorilla/mux" "github.com/unrolled/render" ) var Render *render.Render func init() { Render = render.New(render.Options{ IndentJSON: true, }) } func index(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Welcome to the home page!") } func apiHandler(w http.ResponseWriter, r *http.Request) { Render.JSON(w, http.StatusOK, "Welcome to the api hander page!") } func apiKeyDetailsHandler(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] fmt.Fprintf(w, "Welcome to the api Key Details hander page! %s", id) } func webKeyHandler(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] fmt.Fprintf(w, "Welcome to the web Key hander page! %s", id) } func notFound(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/", http.StatusTemporaryRedirect) } func apiKeyHandler(w http.ResponseWriter, r *http.Request)
{ id := mux.Vars(r)["id"] fmt.Fprintf(w, "Welcome to the api Key hander page! %s", id) }
package fake import ( "encoding/json" "fmt" "net/http" "strings" . "github.com/onsi/gomega" "github.com/onsi/gomega/ghttp" ) type CFAPI struct { server *ghttp.Server } type CFAPIConfig struct { Routes map[string]Response } type Response struct { Code int Body interface{} } func NewCFAPI() *CFAPI { server := ghttp.NewServer() return &CFAPI{ server: server, } } func (a *CFAPI) SetConfiguration(config CFAPIConfig) { a.server.Reset() for request, response := range config.Routes { method, path := parseRequest(request) responseBytes, err := json.Marshal(response.Body) Expect(err).NotTo(HaveOccurred()) a.server.RouteToHandler(method, path, ghttp.RespondWith(response.Code, responseBytes)) } } func (a *CFAPI) URL() string { return a.server.URL() } func (a *CFAPI) ReceivedRequests() map[string][]*http.Request { result := map[string][]*http.Request{} for _, req := range a.server.ReceivedRequests() { key := fmt.Sprintf("%s %s", req.Method, req.URL.Path) result[key] = append(result[key], req) } return result } func parseRequest(request string) (string, string) { fields := strings.Split(request, " ") Expect(fields).To(HaveLen(2)) return fields[0], fields[1] } func (a *CFAPI) Close()
{ a.server.Close() }
package document type IndexingOptions int const ( IndexField IndexingOptions = 1 << iota StoreField IncludeTermVectors ) func (o IndexingOptions) IsIndexed() bool { return o&IndexField != 0 } func (o IndexingOptions) IncludeTermVectors() bool { return o&IncludeTermVectors != 0 } func (o IndexingOptions) String() string { rv := "" if o.IsIndexed() { rv += "INDEXED" } if o.IsStored() { if rv != "" { rv += ", " } rv += "STORE" } if o.IncludeTermVectors() { if rv != "" { rv += ", " } rv += "TV" } return rv } func (o IndexingOptions) IsStored() bool
{ return o&StoreField != 0 }
package log import ( "testing" ) type testLogger struct { keyvals []interface{} } type testSink struct { keyvals []interface{} } func (ts *testSink) Receive(keyvals ...interface{}) error { ts.keyvals = keyvals return nil } func TestLogger_Log(t *testing.T) { tl := &testLogger{} l := NewLogger(tl, nil) l.Log("message", "value") if len(tl.keyvals) != 2 { t.Errorf("Expected log message with 2 values, got %v", len(tl.keyvals)) } m1 := tl.keyvals[0] m2 := tl.keyvals[1] if m1.(string) != "message" || m2.(string) != "value" { t.Errorf("Expected [message, value] but got %s", tl.keyvals) } } func TestLogger_Event(t *testing.T) { ts := &testSink{} tl := &testLogger{} l := NewLogger(tl, []EventSink{ts}) l.Event("important_event", "act_on_me") if len(ts.keyvals) != 2 { t.Errorf("Expected to recieve event with 2 values, got %v", len(ts.keyvals)) } m1 := ts.keyvals[0] m2 := ts.keyvals[1] if m1.(string) != "important_event" || m2.(string) != "act_on_me" { t.Errorf("Expected [important_event, act_on_me] but got %s", ts.keyvals) } } func (tl *testLogger) Log(keyvals ...interface{}) error
{ tl.keyvals = keyvals return nil }
package tasks import ( "net/http" "github.com/go-openapi/errors" "github.com/go-openapi/runtime/middleware" "github.com/go-openapi/swag" strfmt "github.com/go-openapi/strfmt" ) type DeleteTaskParams struct { HTTPRequest *http.Request ID int64 } func (o *DeleteTaskParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { var res []error o.HTTPRequest = r rID, rhkID, _ := route.Params.GetOK("id") if err := o.bindID(rID, rhkID, route.Formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (o *DeleteTaskParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { var raw string if len(rawData) > 0 { raw = rawData[len(rawData)-1] } value, err := swag.ConvertInt64(raw) if err != nil { return errors.InvalidType("id", "path", "int64", raw) } o.ID = value return nil } func NewDeleteTaskParams() DeleteTaskParams
{ var () return DeleteTaskParams{} }
package pdf417 import ( "image" "image/color" "github.com/boombuler/barcode" "github.com/boombuler/barcode/utils" ) type pdfBarcode struct { data string width int code *utils.BitList } func (c *pdfBarcode) Metadata() barcode.Metadata { return barcode.Metadata{barcode.TypePDF, 2} } func (c *pdfBarcode) Content() string { return c.data } func (c *pdfBarcode) ColorModel() color.Model { return color.Gray16Model } func (c *pdfBarcode) Bounds() image.Rectangle { height := c.code.Len() / c.width return image.Rect(0, 0, c.width, height*moduleHeight) } func (c *pdfBarcode) At(x, y int) color.Color
{ if c.code.GetBit((y/moduleHeight)*c.width + x) { return color.Black } return color.White }
package model import "testing" func TestLocaleSyncKeys(t *testing.T)
{ l := Locale{} l.SyncKeys([]string{"testkey1", "testkey2"}) if _, ok := l.Pairs["testkey1"]; !ok { t.Fatal("expected 'testkey1' to be present") } if _, ok := l.Pairs["testkey2"]; !ok { t.Fatal("expected 'testkey2' to be present") } l.SyncKeys([]string{"testkey1"}) if _, ok := l.Pairs["testkey2"]; ok { t.Fatal("expected 'testkey2' to not be present") } }
package object type Error string func (e Error) First() Value { return e } func (e Error) Rest() Value { return e } func (e Error) String() string { return string("<error: " + e + ">") } func (e Error) Type() Type
{ return ERROR }
package readline import "io" type Instance struct { t *Terminal o *Operation } type Config struct { Prompt string HistoryFile string } func NewEx(cfg *Config) (*Instance, error) { t, err := NewTerminal(cfg) if err != nil { return nil, err } rl := t.Readline() return &Instance{ t: t, o: rl, }, nil } func New(prompt string) (*Instance, error) { return NewEx(&Config{Prompt: prompt}) } func (i *Instance) Stdout() io.Writer { return i.o.Stdout() } func (i *Instance) Readline() (string, error) { return i.o.String() } func (i *Instance) ReadSlice() ([]byte, error) { return i.o.Slice() } func (i *Instance) Close() error { if err := i.t.Close(); err != nil { return err } i.o.Close() return nil } func (i *Instance) Stderr() io.Writer
{ return i.o.Stderr() }
package metrics import ( "github.com/cloudfoundry/dropsonde/metric_sender" ) var metricSender metric_sender.MetricSender var metricBatcher MetricBatcher type MetricBatcher interface { BatchIncrementCounter(name string) BatchAddCounter(name string, delta uint64) Close() } func Initialize(ms metric_sender.MetricSender, mb MetricBatcher) { if metricBatcher != nil { metricBatcher.Close() } metricSender = ms metricBatcher = mb } func Close() { metricBatcher.Close() } func SendValue(name string, value float64, unit string) error { if metricSender == nil { return nil } return metricSender.SendValue(name, value, unit) } func IncrementCounter(name string) error { if metricSender == nil { return nil } return metricSender.IncrementCounter(name) } func BatchIncrementCounter(name string) { if metricBatcher == nil { return } metricBatcher.BatchIncrementCounter(name) } func AddToCounter(name string, delta uint64) error { if metricSender == nil { return nil } return metricSender.AddToCounter(name, delta) } func SendContainerMetric(applicationId string, instanceIndex int32, cpuPercentage float64, memoryBytes uint64, diskBytes uint64) error { if metricSender == nil { return nil } return metricSender.SendContainerMetric(applicationId, instanceIndex, cpuPercentage, memoryBytes, diskBytes) } func BatchAddCounter(name string, delta uint64)
{ if metricBatcher == nil { return } metricBatcher.BatchAddCounter(name, delta) }
package vox type Block uint8 const ( BlockNil = 0x00 blockActiveMask = 0x80 blockTypeMask = 0x7F ) func (b Block) Active() bool { return (blockActiveMask & b) == blockActiveMask } func (b Block) Activate(active bool) Block { if active { return b | blockActiveMask } return b & blockTypeMask } func (b Block) TypeID() uint8 { return uint8(b & blockTypeMask) } func (b Block) ChangeType(t *BlockType) Block { return Block((uint8(b) & blockActiveMask) | t.ID) } type BlockType struct { ID uint8 Top *TextureRegion Bottom *TextureRegion Side *TextureRegion } type BlockBank struct { Types []*BlockType typeMap map[uint8]*BlockType } func (b *BlockBank) AddType(blockType *BlockType) { b.typeMap[blockType.ID] = blockType b.Types = append(b.Types, blockType) } func (b *BlockBank) TypeOf(block Block) *BlockType { return b.typeMap[block.TypeID()] } func NewBlockBank() *BlockBank
{ return &BlockBank{ typeMap: make(map[uint8]*BlockType), } }
package bauth_test import ( "github.com/insionng/macross" "github.com/insionng/macross/bauth" "testing" ) func TestBasicAuth(t *testing.T)
{ m := macross.New() m.Use(bauth.BasicAuth(func(username, password string) bool { if username == "inson" && password == "secret" { return true } return false })) go m.Run(":9999") }
package ast import ( "fmt" "github.com/rhysd/gocaml/token" "github.com/rhysd/locerr" ) type printPath struct { total int } func (v *printPath) VisitTopdown(e Expr) Visitor { fmt.Printf("\n -> %s (topdown)", e.Name()) return v } func Example() { src := locerr.NewDummySource("") rootOfAST := &Let{ LetToken: &token.Token{File: src}, Symbol: NewSymbol("test"), Bound: &Int{ Token: &token.Token{File: src}, Value: 42, }, Body: &Add{ Left: &VarRef{ Token: &token.Token{File: src}, Symbol: NewSymbol("test"), }, Right: &Float{ Token: &token.Token{File: src}, Value: 3.14, }, }, } ast := &AST{Root: rootOfAST} v := &printPath{0} fmt.Println("ROOT") Visit(v, ast.Root) Println(ast) } func (v *printPath) VisitBottomup(e Expr)
{ fmt.Printf("\n -> %s (bottomup)", e.Name()) }
package jail import ( "bufio" "fmt" "os" ) type logReader struct { filename string file *os.File reader *bufio.Reader lines chan string errors chan error } func newLogReader(filename string) *logReader { f, err := os.Open(filename) if err != nil { fmt.Println(err) return nil } r := bufio.NewReader(f) return &logReader{ filename: filename, file: f, reader: r, lines: make(chan string), errors: make(chan error), } } func (l *logReader) reset() { f, err := os.Open(l.filename) if err != nil { fmt.Println(err) } r := bufio.NewReader(f) l.reader.Reset(r) } func (l *logReader) readLine()
{ line, err := l.reader.ReadString('\n') if err != nil { go func() { l.errors <- err }() } if line != "" { go func() { l.lines <- line }() } }
package issues import ( "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M)
{ unittest.MainTest(m, filepath.Join("..", ".."), "") }
package btcd import ( "os" "os/user" "path/filepath" "runtime" "strings" "unicode" ) func appDataDir(goos, appName string, roaming bool) string { if appName == "" || appName == "." { return "." } if strings.HasPrefix(appName, ".") { appName = appName[1:] } appNameUpper := string(unicode.ToUpper(rune(appName[0]))) + appName[1:] appNameLower := string(unicode.ToLower(rune(appName[0]))) + appName[1:] var homeDir string usr, err := user.Current() if err == nil { homeDir = usr.HomeDir } if err != nil || homeDir == "" { homeDir = os.Getenv("HOME") } switch goos { case "windows": appData := os.Getenv("LOCALAPPDATA") if roaming || appData == "" { appData = os.Getenv("APPDATA") } if appData != "" { return filepath.Join(appData, appNameUpper) } case "darwin": if homeDir != "" { return filepath.Join(homeDir, "Library", "Application Support", appNameUpper) } case "plan9": if homeDir != "" { return filepath.Join(homeDir, appNameLower) } default: if homeDir != "" { return filepath.Join(homeDir, "."+appNameLower) } } return "." } func AppDataDir(appName string, roaming bool) string
{ return appDataDir(runtime.GOOS, appName, roaming) }
package helper import ( "bufio" "net" ) type BufConn struct { net.Conn BR *bufio.Reader } func (c *BufConn) Peek(n int) ([]byte, error) { return c.BR.Peek(n) } func (c *BufConn) Read(b []byte) (n int, err error) { return c.BR.Read(b) } func (c *BufConn) Write(b []byte) (n int, err error) { return c.Conn.Write(b) } func NewBufConn(c net.Conn, r *bufio.Reader) *BufConn { conn := &BufConn{Conn: c} conn.BR = r if nil == r { conn.BR = bufio.NewReader(c) } return conn } func (c *BufConn) Reset(conn net.Conn)
{ c.Conn = conn }
package main func f(int) {} func h(int, int) {} func main() { f(g()) f(true) h(true, true) } func g() bool
{ return true }
package glib import "C" import "unsafe" type IActionMap interface { Native() uintptr LookupAction(actionName string) *Action AddAction(action IAction) RemoveAction(actionName string) } type ActionMap struct { *Object } func (v *ActionMap) Native() uintptr { return uintptr(unsafe.Pointer(v.native())) } func marshalActionMap(p uintptr) (interface{}, error) { c := C.g_value_get_object((*C.GValue)(unsafe.Pointer(p))) return wrapActionMap(wrapObject(unsafe.Pointer(c))), nil } func wrapActionMap(obj *Object) *ActionMap { return &ActionMap{obj} } func (v *ActionMap) LookupAction(actionName string) *Action { c := C.g_action_map_lookup_action(v.native(), (*C.gchar)(C.CString(actionName))) if c == nil { return nil } return wrapAction(wrapObject(unsafe.Pointer(c))) } func (v *ActionMap) AddAction(action IAction) { C.g_action_map_add_action(v.native(), action.toGAction()) } func (v *ActionMap) RemoveAction(actionName string) { C.g_action_map_remove_action(v.native(), (*C.gchar)(C.CString(actionName))) } func (v *ActionMap) native() *C.GActionMap
{ if v == nil || v.GObject == nil { return nil } return C.toGActionMap(unsafe.Pointer(v.GObject)) }
package lib import "sync" type ConcurrentPrinterMap struct { byCUPSName map[string]Printer byGCPID map[string]Printer mutex sync.RWMutex } func NewConcurrentPrinterMap(printers []Printer) *ConcurrentPrinterMap { cpm := ConcurrentPrinterMap{} cpm.Refresh(printers) return &cpm } func (cpm *ConcurrentPrinterMap) GetByCUPSName(name string) (Printer, bool) { cpm.mutex.RLock() defer cpm.mutex.RUnlock() if p, exists := cpm.byCUPSName[name]; exists { return p, true } return Printer{}, false } func (cpm *ConcurrentPrinterMap) GetByGCPID(gcpID string) (Printer, bool) { cpm.mutex.RLock() defer cpm.mutex.RUnlock() if p, exists := cpm.byGCPID[gcpID]; exists { return p, true } return Printer{}, false } func (cpm *ConcurrentPrinterMap) GetAll() []Printer { cpm.mutex.RLock() defer cpm.mutex.RUnlock() printers := make([]Printer, len(cpm.byCUPSName)) i := 0 for _, printer := range cpm.byCUPSName { printers[i] = printer i++ } return printers } func (cpm *ConcurrentPrinterMap) Refresh(newPrinters []Printer)
{ c := make(map[string]Printer, len(newPrinters)) for _, printer := range newPrinters { c[printer.Name] = printer } g := make(map[string]Printer, len(newPrinters)) for _, printer := range newPrinters { if len(printer.GCPID) > 0 { g[printer.GCPID] = printer } } cpm.mutex.Lock() defer cpm.mutex.Unlock() cpm.byCUPSName = c cpm.byGCPID = g }
package astar import ( "os" "image" ) import _ "image/png" func parseImage(img image.Image) MapData { max := uint32(65536-1) bounds := img.Bounds() map_data := NewMapData(bounds.Max.X, bounds.Max.Y) for y := bounds.Min.Y; y < bounds.Max.Y; y++ { for x := bounds.Min.X; x < bounds.Max.X; x++ { r, g, b, a := img.At(x, y).RGBA() if(r == max && g == max && b == max && a == max) { map_data[x][bounds.Max.Y-1-y] = LAND } else { map_data[x][bounds.Max.Y-1-y] = WALL } } } return map_data } func GetMapFromImage(filename string) MapData { img := openImage(filename) if(img == nil) { return nil } return parseImage(img) } func openImage(filename string) (image.Image)
{ f, err := os.Open(filename) if err != nil { return nil } defer f.Close() img, _, _ := image.Decode(f) return img }
package centos import ( "github.com/megamsys/libmegdc/templates" "github.com/megamsys/urknall" ) var centoshostinfo *CentosHostInfo func init() { centoshostinfo = &CentosHostInfo{} templates.Register("CentosHostInfo", centoshostinfo) } type CentosHostInfo struct{} func (tpl *CentosHostInfo) Options(t *templates.Template) { } func (tpl *CentosHostInfo) Run(target urknall.Target,inputs map[string]string) error { return urknall.Run(target, &CentosHostInfo{},inputs) } type CentosHostInfoTemplate struct{} func (m *CentosHostInfoTemplate) Render(pkg urknall.Package) { pkg.AddCommands("disk", Shell("df -h"), ) pkg.AddCommands("memory", Shell("free -m"), ) pkg.AddCommands("blockdevices", Shell("lsblk"), ) pkg.AddCommands("cpu", Shell("lscpu"), ) pkg.AddCommands("hostname", Shell("hostname"), ) pkg.AddCommands("dnsserver", Shell("cat /etc/resolv.conf"), ) pkg.AddCommands("ipaddress", Shell("yum install -y net-tools"), Shell("ifconfig"), ) pkg.AddCommands("bridge", Shell("if /sbin/brctl ; then brctl show; else echo 'no bridge is available'; fi"), ) } func (tpl *CentosHostInfo) Render(p urknall.Package)
{ p.AddTemplate("hostinfo", &CentosHostInfoTemplate{}) }
package TeleGogo import ( "encoding/json" "net/http" ) func responseToTgError(response *http.Response) TelegramError { defer response.Body.Close() tgErr := telegramError{} json.NewDecoder(response.Body).Decode(&tgErr) return tgErr } func errToTelegramErr(err error) TelegramError { return telegramError{OK: false, ErrorCode: 0, Description: err.Error()} } type telegramError struct { OK bool `json:"ok"` ErrorCode int `json:"error_code"` Description string `json:"description"` } func (t telegramError) IsOK() bool { return t.OK } func (t telegramError) ErrCode() int { return t.ErrorCode } func (t telegramError) Error() string { return t.Description } type TelegramError interface { IsOK() bool ErrCode() int Error() string } func responseToError(response *http.Response) error
{ return responseToTgError(response) }
package lock import ( "os" ) type LockedFile interface { File() *os.File Exclusive() bool Close() error } type DefaultLockedFile struct { f *os.File exclusive bool } func OpenExclusive(path string, flag int, perm os.FileMode) (LockedFile, error) { return open(path, flag, perm, true) } func OpenShared(path string, flag int, perm os.FileMode) (LockedFile, error) { return open(path, flag, perm, false) } func (e *DefaultLockedFile) File() *os.File { return e.f } func (e *DefaultLockedFile) Close() error { err := e.unlock() err2 := e.f.Close() if err2 != nil && err == nil { err = err2 } return err } func (e *DefaultLockedFile) Exclusive() bool
{ return e.exclusive }
package treemap import "github.com/emirpasic/gods/containers" func (m *Map) ToJSON() ([]byte, error) { return m.tree.ToJSON() } func (m *Map) FromJSON(data []byte) error { return m.tree.FromJSON(data) } func assertSerializationImplementation()
{ var _ containers.JSONSerializer = (*Map)(nil) var _ containers.JSONDeserializer = (*Map)(nil) }
package main import "./buildings" var board [2][2][][]buildings.Building func bget(x, y int) buildings.Building { xIndex, yIndex := 0, 0 if x < 0 { xIndex = 1 x = -x } if y < 0 { yIndex = 1 y = -y } return board[xIndex][yIndex][x][y] } func bset(x, y int, b buildings.Building) { xIndex, yIndex := 0, 0 if x < 0 { xIndex = 1 x = -x } if y < 0 { yIndex = 1 y = -y } board[xIndex][yIndex][x][y] = b } func badd(x, y int, b buildings.Building) { xIndex, yIndex := 0, 0 if x < 0 { xIndex = 1 x = -x } if y < 0 { yIndex = 1 y = -y } if cap(board[xIndex][yIndex]) < x { slice2 := make([][]buildings.Building, len(board[xIndex][yIndex]), x+4) copy(slice2, board[xIndex][yIndex]) board[xIndex][yIndex] = slice2 } if cap(board[xIndex][yIndex][x]) < y { slice2 := make([]buildings.Building, len(board[xIndex][yIndex][x]), x+4) copy(slice2, board[xIndex][yIndex][x]) board[xIndex][yIndex][x] = slice2 } board[xIndex][yIndex][x][y] = b } func bForEach(f func(buildings.Building, int, int))
{ for xIndex := 0; xIndex <= 1; xIndex++ { for yIndex := 0; yIndex <= 1; yIndex++ { for x := xIndex; x < len(board[xIndex][yIndex]); x++ { for y := yIndex; y < len(board[xIndex][yIndex][x]); y++ { f(board[xIndex][yIndex][x][y], x, y) } } } } }
package auth import ( "encoding/base64" "github.com/outbrain/orchestrator/Godeps/_workspace/src/github.com/go-martini/martini" "net/http" "strings" ) type User string var BasicRealm = "Authorization Required" func Basic(username string, password string) martini.Handler { var siteAuth = base64.StdEncoding.EncodeToString([]byte(username + ":" + password)) return func(res http.ResponseWriter, req *http.Request, c martini.Context) { auth := req.Header.Get("Authorization") if !SecureCompare(auth, "Basic "+siteAuth) { unauthorized(res) return } c.Map(User(username)) } } func BasicFunc(authfn func(string, string) bool) martini.Handler { return func(res http.ResponseWriter, req *http.Request, c martini.Context) { auth := req.Header.Get("Authorization") if len(auth) < 6 || auth[:6] != "Basic " { unauthorized(res) return } b, err := base64.StdEncoding.DecodeString(auth[6:]) if err != nil { unauthorized(res) return } tokens := strings.SplitN(string(b), ":", 2) if len(tokens) != 2 || !authfn(tokens[0], tokens[1]) { unauthorized(res) return } c.Map(User(tokens[0])) } } func unauthorized(res http.ResponseWriter)
{ res.Header().Set("WWW-Authenticate", "Basic realm=\""+BasicRealm+"\"") http.Error(res, "Not Authorized", http.StatusUnauthorized) }
package dom import ( "bytes" "fmt" ) type Node interface { String() string Parent() Node SetParent(node Node) Children() []Node AddChild(child Node) Clone() Node } type Element struct { text string parent Node children []Node } func NewElement(text string) *Element { return &Element{ text: text, parent: nil, children: make([]Node, 0), } } func (e *Element) Parent() Node { return e.parent } func (e *Element) SetParent(node Node) { e.parent = node } func (e *Element) Children() []Node { return e.children } func (e *Element) AddChild(child Node) { copy := child.Clone() copy.SetParent(e) e.children = append(e.children, copy) } func (e *Element) String() string { buffer := bytes.NewBufferString(e.text) for _, c := range e.Children() { text := c.String() fmt.Fprintf(buffer, "\n %s", text) } return buffer.String() } func (e *Element) Clone() Node
{ copy := &Element{ text: e.text, parent: nil, children: make([]Node, 0), } for _, child := range e.children { copy.AddChild(child) } return copy }
package getter import ( "errors" "fmt" "github.com/goharbor/harbor/src/lib/orm" "github.com/goharbor/harbor/src/pkg/joblog" "github.com/goharbor/harbor/src/jobservice/errs" ) type DBGetter struct { } func NewDBGetter() *DBGetter { return &DBGetter{} } func (dbg *DBGetter) Retrieve(logID string) ([]byte, error)
{ if len(logID) == 0 { return nil, errors.New("empty log identify") } jobLog, err := joblog.Mgr.Get(orm.Context(), logID) if err != nil { return nil, errs.NoObjectFoundError(fmt.Sprintf("log entity: %s", logID)) } return []byte(jobLog.Content), nil }
package main import ( "testing" ) func TestAvgScore(t *testing.T)
{ scores := []int{30, 60, 80, 100} exp := 67 act := avgScore(scores) if exp != act { t.Error("Expected", exp, "got", act) } }
package drive import ( "camlistore.org/pkg/blob" ) func (sto *driveStorage) StatBlobs(dest chan<- blob.SizedRef, blobs []blob.Ref) error
{ for _, br := range blobs { size, err := sto.service.Stat(br.String()) if err == nil { dest <- blob.SizedRef{Ref: br, Size: size} } else { return err } } return nil }
package obj import "fmt" const _SymKind_name = "SxxxSTEXTSELFRXSECTSTYPESSTRINGSGOSTRINGSGOFUNCSGCBITSSRODATASFUNCTABSELFROSECTSMACHOPLTSTYPERELROSSTRINGRELROSGOSTRINGRELROSGOFUNCRELROSGCBITSRELROSRODATARELROSFUNCTABRELROSTYPELINKSITABLINKSSYMTABSPCLNTABSELFSECTSMACHOSMACHOGOTSWINDOWSSELFGOTSNOPTRDATASINITARRSDATASBSSSNOPTRBSSSTLSBSSSXREFSMACHOSYMSTRSMACHOSYMTABSMACHOINDIRECTPLTSMACHOINDIRECTGOTSFILESFILEPATHSCONSTSDYNIMPORTSHOSTOBJSDWARFSECTSDWARFINFO" var _SymKind_index = [...]uint16{0, 4, 9, 19, 24, 31, 40, 47, 54, 61, 69, 79, 88, 98, 110, 124, 136, 148, 160, 173, 182, 191, 198, 206, 214, 220, 229, 237, 244, 254, 262, 267, 271, 280, 287, 292, 304, 316, 333, 350, 355, 364, 370, 380, 388, 398, 408} func (i SymKind) String() string
{ if i < 0 || i >= SymKind(len(_SymKind_index)-1) { return fmt.Sprintf("SymKind(%d)", i) } return _SymKind_name[_SymKind_index[i]:_SymKind_index[i+1]] }
package validating import ( "io" "k8s.io/apiserver/pkg/admission" "k8s.io/apiserver/pkg/admission/configuration" "k8s.io/apiserver/pkg/admission/plugin/webhook/generic" ) const ( PluginName = "ValidatingAdmissionWebhook" ) type Plugin struct { *generic.Webhook } var _ admission.ValidationInterface = &Plugin{} func NewValidatingAdmissionWebhook(configFile io.Reader) (*Plugin, error) { handler := admission.NewHandler(admission.Connect, admission.Create, admission.Delete, admission.Update) webhook, err := generic.NewWebhook(handler, configFile, configuration.NewValidatingWebhookConfigurationManager, newValidatingDispatcher) if err != nil { return nil, err } return &Plugin{webhook}, nil } func (a *Plugin) Validate(attr admission.Attributes) error { return a.Webhook.Dispatch(attr) } func Register(plugins *admission.Plugins)
{ plugins.Register(PluginName, func(configFile io.Reader) (admission.Interface, error) { plugin, err := NewValidatingAdmissionWebhook(configFile) if err != nil { return nil, err } return plugin, nil }) }
package servo_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "testing" "github.com/fgrosse/servo" "fmt" ) func TestServo(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Servo Test Suite") } type TestBundle struct {} func (b *TestBundle) Boot(kernel *servo.Kernel) { kernel.RegisterType("test_bundle.my_type", NewService) } type SomeService struct {} func NewService() *SomeService { return &SomeService{} } func NewServiceWithParam(param interface{}) *SomeService { panic(param) return &SomeService{} } type ServerMock struct { RunHasBeenCalled bool ReturnError bool Parameter1, Parameter2 string } func NewServerMockWithParams(param1, param2 string) *ServerMock { Expect(param1).To(Equal("foo"), `NewServerMockWithParams should always be called with the values "foo" and "bar"`) Expect(param2).To(Equal("bar"), `NewServerMockWithParams should always be called with the values "foo" and "bar"`) return &ServerMock{ Parameter1: param1, Parameter2: param2, } } func (s *ServerMock) Run() error { s.RunHasBeenCalled = true if s.ReturnError { return fmt.Errorf("ServerMock was told to return an error!") } return nil } func NewRecursiveService(*SomeService) *SomeService
{ return &SomeService{} }
package chart import ( "bytes" "github.com/golang/protobuf/jsonpb" ) func (msg *Config) MarshalJSON() ([]byte, error) { var buf bytes.Buffer err := (&jsonpb.Marshaler{ EnumsAsInts: false, EmitDefaults: false, OrigName: false, }).Marshal(&buf, msg) return buf.Bytes(), err } func (msg *Value) MarshalJSON() ([]byte, error) { var buf bytes.Buffer err := (&jsonpb.Marshaler{ EnumsAsInts: false, EmitDefaults: false, OrigName: false, }).Marshal(&buf, msg) return buf.Bytes(), err } func (msg *Value) UnmarshalJSON(b []byte) error { return (&jsonpb.Unmarshaler{ AllowUnknownFields: false, }).Unmarshal(bytes.NewReader(b), msg) } func (msg *Config) UnmarshalJSON(b []byte) error
{ return (&jsonpb.Unmarshaler{ AllowUnknownFields: false, }).Unmarshal(bytes.NewReader(b), msg) }
package utils import ( "fmt" "strings" "github.com/SaferLuo/EtherIOT/node" "github.com/SaferLuo/EtherIOT/rpc" "gopkg.in/urfave/cli.v1" ) func NewRemoteRPCClient(ctx *cli.Context) (rpc.Client, error) { if ctx.Args().Present() { endpoint := ctx.Args().First() return NewRemoteRPCClientFromString(endpoint) } return rpc.NewIPCClient(node.DefaultIPCEndpoint()) } func NewRemoteRPCClientFromString(endpoint string) (rpc.Client, error)
{ if strings.HasPrefix(endpoint, "ipc:") { return rpc.NewIPCClient(endpoint[4:]) } if strings.HasPrefix(endpoint, "rpc:") { return rpc.NewHTTPClient(endpoint[4:]) } if strings.HasPrefix(endpoint, "http:") { return rpc.NewHTTPClient(endpoint) } if strings.HasPrefix(endpoint, "ws:") { return rpc.NewWSClient(endpoint) } return nil, fmt.Errorf("invalid endpoint") }
package main import "fmt" func main() { rmbNum := make(map[int]int) only89 := []int{} rmbNum[89] = 89 rmbNum[1] = 1 for i := 1; i < 10000000; i++ { yes := false rmbSeq := []int{} for num := i; ; num = findNext(num) { rmbSeq = append(rmbSeq, num) if val, ok := rmbNum[num]; ok { if val == 89 { for _, r := range rmbSeq { rmbNum[r] = 89 } yes = true break } else if val == 1 { for _, r := range rmbSeq { rmbNum[r] = 1 } break } } } if yes { only89 = append(only89, i) } } fmt.Println(len(only89)) } func findNext(num int) int
{ var newNum int for num > 0 { digit := num % 10 newNum += digit * digit num /= 10 } return newNum }
package main import ( "fmt" "time" "github.com/lxc/lxd/client" ) func cmdShutdown(args *Args) error
{ c, err := lxd.ConnectLXDUnix("", nil) if err != nil { return err } _, _, err = c.RawQuery("PUT", "/internal/shutdown", nil, "") if err != nil { return err } chMonitor := make(chan bool, 1) go func() { monitor, err := c.GetEvents() if err != nil { close(chMonitor) return } monitor.Wait() close(chMonitor) }() if args.Timeout > 0 { select { case <-chMonitor: break case <-time.After(time.Second * time.Duration(args.Timeout)): return fmt.Errorf("LXD still running after %ds timeout.", args.Timeout) } } else { <-chMonitor } return nil }
package lemon import ( "errors" "testing" ) func TestOption(t *testing.T) { tests := map[string]TestHandler{ "WithError": OptionWithError, } for name, handler := range tests { t.Run(name, Setup(handler)) } } type errOption struct { err error } func OptionWithError(runtime *TestRuntime) { expected := errors.New("cannot update engine with foobar") option := errOption{ err: expected, } engine, err := New(runtime.Context(), option) if err == nil { runtime.Error("An error was expected") } if err != expected { runtime.Error("Unexpected error: %s", err) } if engine != nil { runtime.Error("Engine should be undefined") } runtime.Log("We received expected error: %s.", err) } func (o errOption) apply(e *Engine) error
{ return o.err }
package mailru import ( "encoding/json" "errors" "strings" "time" "github.com/markbates/goth" ) type Session struct { AuthURL string AccessToken string RefreshToken string ExpiresAt time.Time } func (s *Session) GetAuthURL() (string, error) { if s.AuthURL == "" { return "", errors.New(goth.NoAuthUrlErrorMessage) } return s.AuthURL, nil } func (s *Session) Marshal() string { b, _ := json.Marshal(s) return string(b) } func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) { p := provider.(*Provider) token, err := p.oauthConfig.Exchange(goth.ContextForClient(p.Client()), params.Get("code")) if err != nil { return "", err } if !token.Valid() { return "", errors.New("invalid token received from provider") } s.AccessToken = token.AccessToken s.RefreshToken = token.RefreshToken s.ExpiresAt = token.Expiry return s.AccessToken, err } func (p *Provider) UnmarshalSession(data string) (goth.Session, error)
{ sess := new(Session) err := json.NewDecoder(strings.NewReader(data)).Decode(&sess) return sess, err }