input
stringlengths
24
2.11k
output
stringlengths
7
948
package ansiwriter import ( "fmt" "io" ) type Modifier func() string func Bold() string { return escapeANSI(1) } func Black() string { return escapeANSI(30) } func Red() string { return escapeANSI(31) } func Green() string { return escapeANSI(32) } func Yellow() string { return escapeANSI(33) } func Blue() string { return escapeANSI(34) } func Magenta() string { return escapeANSI(35) } func Cyan() string { return escapeANSI(36) } func White() string { return escapeANSI(37) } type awr struct { io.Writer modifiers []Modifier } func New(w io.Writer, mods ...Modifier) io.Writer { return awr{w, mods} } func (a awr) Write(b []byte) (n int, err error) { for _, mod := range a.modifiers { a.Writer.Write([]byte(mod())) } n, err = a.Writer.Write(b) _, _ = a.Writer.Write([]byte("\033[0m")) return } func escapeANSI(code int) string
{ return fmt.Sprintf("\033[%dm", code) }
package btcec import ( secp "github.com/decred/dcrd/dcrec/secp256k1/v4" ) type JacobianPoint = secp.JacobianPoint func MakeJacobianPoint(x, y, z *FieldVal) JacobianPoint { return secp.MakeJacobianPoint(x, y, z) } func AddNonConst(p1, p2, result *JacobianPoint) { secp.AddNonConst(p1, p2, result) } func DoubleNonConst(p, result *JacobianPoint) { secp.DoubleNonConst(p, result) } func ScalarBaseMultNonConst(k *ModNScalar, result *JacobianPoint) { secp.ScalarBaseMultNonConst(k, result) } func ScalarMultNonConst(k *ModNScalar, point, result *JacobianPoint) { secp.ScalarMultNonConst(k, point, result) } func DecompressY(x *FieldVal, odd bool, resultY *FieldVal) bool
{ return secp.DecompressY(x, odd, resultY) }
package billing import original "github.com/Azure/azure-sdk-for-go/services/billing/mgmt/2017-04-24-preview/billing" const ( DefaultBaseURI = original.DefaultBaseURI ) type ManagementClient = original.ManagementClient type InvoicesClient = original.InvoicesClient type DownloadURL = original.DownloadURL type ErrorDetails = original.ErrorDetails type ErrorResponse = original.ErrorResponse type Invoice = original.Invoice type InvoiceProperties = original.InvoiceProperties type InvoicesListResult = original.InvoicesListResult type Operation = original.Operation type OperationDisplay = original.OperationDisplay type OperationListResult = original.OperationListResult type Period = original.Period type PeriodProperties = original.PeriodProperties type PeriodsListResult = original.PeriodsListResult type Resource = original.Resource type OperationsClient = original.OperationsClient type PeriodsClient = original.PeriodsClient func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { return original.NewOperationsClientWithBaseURI(baseURI, subscriptionID) } func NewPeriodsClient(subscriptionID string) PeriodsClient { return original.NewPeriodsClient(subscriptionID) } func NewPeriodsClientWithBaseURI(baseURI string, subscriptionID string) PeriodsClient { return original.NewPeriodsClientWithBaseURI(baseURI, subscriptionID) } func UserAgent() string { return original.UserAgent() + " profiles/preview" } func Version() string { return original.Version() } func New(subscriptionID string) ManagementClient { return original.New(subscriptionID) } func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient { return original.NewWithBaseURI(baseURI, subscriptionID) } func NewInvoicesClient(subscriptionID string) InvoicesClient { return original.NewInvoicesClient(subscriptionID) } func NewInvoicesClientWithBaseURI(baseURI string, subscriptionID string) InvoicesClient { return original.NewInvoicesClientWithBaseURI(baseURI, subscriptionID) } func NewOperationsClient(subscriptionID string) OperationsClient
{ return original.NewOperationsClient(subscriptionID) }
package dosingdecision import ( "time" "github.com/tidepool-org/platform/structure" ) const ( CarbohydratesOnBoardAmountMaximum = 1000 CarbohydratesOnBoardAmountMinimum = 0 ) type CarbohydratesOnBoard struct { Time *time.Time `json:"time,omitempty" bson:"time,omitempty"` Amount *float64 `json:"amount,omitempty" bson:"amount,omitempty"` } func ParseCarbohydratesOnBoard(parser structure.ObjectParser) *CarbohydratesOnBoard { if !parser.Exists() { return nil } datum := NewCarbohydratesOnBoard() parser.Parse(datum) return datum } func NewCarbohydratesOnBoard() *CarbohydratesOnBoard { return &CarbohydratesOnBoard{} } func (c *CarbohydratesOnBoard) Validate(validator structure.Validator) { validator.Float64("amount", c.Amount).Exists().InRange(CarbohydratesOnBoardAmountMinimum, CarbohydratesOnBoardAmountMaximum) } func (c *CarbohydratesOnBoard) Parse(parser structure.ObjectParser)
{ c.Time = parser.Time("time", time.RFC3339Nano) c.Amount = parser.Float64("amount") }
package cache import "github.com/lomik/go-carbon/points" type Query struct { Metric string ReplyChan chan *Reply } func NewQuery(metric string) *Query { return &Query{ Metric: metric, ReplyChan: make(chan *Reply, 1), } } type Reply struct { Points *points.Points } func NewReply() *Reply
{ return &Reply{} }
package routing import "net/http" func Method(method string, handler http.Handler) Matcher { return func(remainingPath string, resp http.ResponseWriter, req *http.Request) bool { if req.Method == method { handler.ServeHTTP(resp, req) return true } return false } } func GET(handler http.Handler) Matcher { return Method("GET", handler) } func GETFunc(handler func(http.ResponseWriter, *http.Request)) Matcher { return GET(http.HandlerFunc(handler)) } func POSTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher { return POST(http.HandlerFunc(handler)) } func PUT(handler http.Handler) Matcher { return Method("PUT", handler) } func PUTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher { return PUT(http.HandlerFunc(handler)) } func PATCH(handler http.Handler) Matcher { return Method("PATCH", handler) } func PATCHFunc(handler func(http.ResponseWriter, *http.Request)) Matcher { return PATCH(http.HandlerFunc(handler)) } func DELETE(handler http.Handler) Matcher { return Method("DELETE", handler) } func DELETEFunc(handler func(http.ResponseWriter, *http.Request)) Matcher { return DELETE(http.HandlerFunc(handler)) } func MethodNotAllowed(remainingPath string, resp http.ResponseWriter, req *http.Request) bool { resp.WriteHeader(405) return true } func POST(handler http.Handler) Matcher
{ return Method("POST", handler) }
package agent import ( "flag" ) func (this *Agent) BindFlags()
{ flag.BoolVar(&this.selfRegister, "self_register", true, "Registers self with the registry.") flag.IntVar(&this.ListenPort, "port", 25657, "Listening port for agent") flag.StringVar(&this.StatusPubsubTopic, "status_topic", "", "Status pubsub topic") flag.BoolVar(&this.EnableUI, "enable_ui", false, "Enables UI") flag.IntVar(&this.DockerUIPort, "dockerui_port", 25658, "Listening port for dockerui") flag.StringVar(&this.UiDocRoot, "ui_docroot", "", "UI DocRoot") }
package muta import ( "fmt" "io" "github.com/leeola/muta/mutil" ) type MockStreamer struct { Files []string Contents []string Errors []error } func (s *MockStreamer) Next(inFi FileInfo, inRc io.ReadCloser) ( fi FileInfo, rc io.ReadCloser, err error)
{ fi = inFi rc = inRc if fi != nil { return } if len(s.Files) == 0 { return } file := s.Files[0] s.Files = s.Files[1:] fi = NewFileInfo(file) if len(s.Contents) > 0 { rc = mutil.ByteCloser([]byte(s.Contents[0])) s.Contents = s.Contents[1:] } else { rc = mutil.ByteCloser([]byte(fmt.Sprintf("%s content", file))) } if len(s.Errors) > 0 { err = s.Errors[0] s.Errors = s.Errors[1:] } return }
package collaboration import "sync" func NewMemoryStorage() *memoryStorage { return &memoryStorage{ users: make(map[string]*Option), } } type memoryStorage struct { users map[string]*Option sync.Mutex } func (m *memoryStorage) Get(username string) (*Option, error) { m.Lock() defer m.Unlock() option, ok := m.users[username] if !ok { return nil, ErrUserNotFound } return option, nil } func (m *memoryStorage) GetAll() (map[string]*Option, error) { m.Lock() defer m.Unlock() return m.users, nil } func (m *memoryStorage) Set(username string, value *Option) error { m.Lock() defer m.Unlock() m.users[username] = value return nil } func (m *memoryStorage) Close() error { return nil } func (m *memoryStorage) Delete(username string) error
{ m.Lock() defer m.Unlock() delete(m.users, username) return nil }
package manager import ( "fmt" "os" "os/exec" "sync" "time" proto "github.com/Cloud-Foundations/Dominator/proto/hypervisor" ) type flusher interface { Flush() error } func (m *Manager) powerOff(stopVMs bool) error { m.mutex.RLock() defer m.mutex.RUnlock() if stopVMs { m.shutdownVMs() } for _, vm := range m.vms { if vm.State != proto.StateStopped { return fmt.Errorf("%s is not shut down", vm.Address.IpAddress) } } cmd := exec.Command("poweroff") if output, err := cmd.CombinedOutput(); err != nil { return fmt.Errorf("%s: %s", err, string(output)) } return nil } func (m *Manager) shutdownVMs() { var waitGroup sync.WaitGroup for _, vm := range m.vms { waitGroup.Add(1) go func(vm *vmInfoType) { defer waitGroup.Done() vm.shutdown() }(vm) } waitGroup.Wait() m.Logger.Println("stopping cleanly after shutting down VMs") if flusher, ok := m.Logger.(flusher); ok { flusher.Flush() } } func (m *Manager) shutdownVMsAndExit() { m.mutex.RLock() defer m.mutex.RUnlock() m.shutdownVMs() os.Exit(0) } func (vm *vmInfoType) shutdown()
{ vm.mutex.RLock() switch vm.State { case proto.StateStarting, proto.StateRunning: stoppedNotifier := make(chan struct{}, 1) vm.stoppedNotifier = stoppedNotifier vm.commandChannel <- "system_powerdown" vm.mutex.RUnlock() timer := time.NewTimer(time.Minute) select { case <-stoppedNotifier: if !timer.Stop() { <-timer.C } vm.logger.Println("shut down cleanly for system shutdown") case <-timer.C: vm.logger.Println("shutdown timed out: killing VM") vm.commandChannel <- "quit" } default: vm.mutex.RUnlock() } }
package main import ( "fmt" "log" "os" "github.com/hpcloud/tail" "golang.org/x/net/context" ) func tailFile(ctx context.Context, cancel context.CancelFunc, fileName string, poll bool, dest *os.File)
{ defer wg.Done() _file, err := os.Open(fileName) if err != nil { log.Printf("Error opening '%s':%s\n", fileName, err) cancel() } _file.Close() t, err := tail.TailFile(fileName, tail.Config{ Follow: true, ReOpen: true, Poll: poll, Logger: tail.DiscardingLogger, }) if err != nil { log.Printf("unable to tail %s: %s\n", fileName, err) cancel() } for { select { case <-ctx.Done(): t.Stop() t.Cleanup() return case line := <-t.Lines: if line != nil { fmt.Fprintln(dest, line.Text) } } } }
package memfs import ( "io" "testing" "gopkg.in/src-d/go-billy.v4" "gopkg.in/src-d/go-billy.v4/test" . "gopkg.in/check.v1" ) func Test(t *testing.T) { TestingT(t) } type MemorySuite struct { test.FilesystemSuite path string } var _ = Suite(&MemorySuite{}) func (s *MemorySuite) SetUpTest(c *C) { s.FilesystemSuite = test.NewFilesystemSuite(New()) } func (s *MemorySuite) TestCapabilities(c *C) { _, ok := s.FS.(billy.Capable) c.Assert(ok, Equals, true) caps := billy.Capabilities(s.FS) c.Assert(caps, Equals, billy.DefaultCapabilities&^billy.LockCapability) } func (s *MemorySuite) TestNegativeOffsets(c *C)
{ f, err := s.FS.Create("negative") c.Assert(err, IsNil) buf := make([]byte, 100) _, err = f.ReadAt(buf, -100) c.Assert(err, ErrorMatches, "readat negative: negative offset") _, err = f.Seek(-100, io.SeekCurrent) c.Assert(err, IsNil) _, err = f.Write(buf) c.Assert(err, ErrorMatches, "writeat negative: negative offset") }
package govppmux import "time" type Config struct { ReconnectResync bool `json:"resync-after-reconnect"` ReplyTimeout time.Duration `json:"reply-timeout"` ConnectViaShm bool `json:"connect-via-shm"` ShmPrefix string `json:"shm-prefix"` BinAPISocketPath string `json:"binapi-socket-path"` StatsSocketPath string `json:"stats-socket-path"` RetryRequestCount int `json:"retry-request-count"` RetryRequestTimeout time.Duration `json:"retry-request-timeout"` RetryConnectCount int `json:"retry-connect-count"` RetryConnectTimeout time.Duration `json:"retry-connect-timeout"` ProxyEnabled bool `json:"proxy-enabled"` HealthCheckProbeInterval time.Duration `json:"health-check-probe-interval"` HealthCheckReplyTimeout time.Duration `json:"health-check-reply-timeout"` HealthCheckThreshold int `json:"health-check-threshold"` TraceEnabled bool `json:"trace-enabled"` } func DefaultConfig() *Config { return &Config{ ReconnectResync: true, HealthCheckProbeInterval: time.Second, HealthCheckReplyTimeout: 250 * time.Millisecond, HealthCheckThreshold: 1, ReplyTimeout: time.Second, RetryRequestTimeout: 500 * time.Millisecond, RetryConnectTimeout: time.Second, ProxyEnabled: true, } } func (p *Plugin) loadConfig() (*Config, error)
{ cfg := DefaultConfig() found, err := p.Cfg.LoadValue(cfg) if err != nil { return nil, err } else if found { p.Log.Debugf("config loaded from file %q", p.Cfg.GetConfigName()) } else { p.Log.Debugf("config file %q not found, using default config", p.Cfg.GetConfigName()) } return cfg, nil }
package database import ( "github.com/oracle/oci-go-sdk/v46/common" "net/http" ) type GetAutonomousPatchRequest struct { AutonomousPatchId *string `mandatory:"true" contributesTo:"path" name:"autonomousPatchId"` OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"` RequestMetadata common.RequestMetadata } func (request GetAutonomousPatchRequest) String() string { return common.PointerString(request) } func (request GetAutonomousPatchRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) { return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders) } func (request GetAutonomousPatchRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) { return nil, false } type GetAutonomousPatchResponse struct { RawResponse *http.Response AutonomousPatch `presentIn:"body"` Etag *string `presentIn:"header" name:"etag"` OpcRequestId *string `presentIn:"header" name:"opc-request-id"` } func (response GetAutonomousPatchResponse) String() string { return common.PointerString(response) } func (response GetAutonomousPatchResponse) HTTPResponse() *http.Response { return response.RawResponse } func (request GetAutonomousPatchRequest) RetryPolicy() *common.RetryPolicy
{ return request.RequestMetadata.RetryPolicy }
package iso20022 type TaxReportHeader1 struct { MessageIdentification *MessageIdentification1 `xml:"MsgId"` NumberOfTaxReports *Number `xml:"NbOfTaxRpts,omitempty"` TaxAuthority []*TaxOrganisationIdentification1 `xml:"TaxAuthrty,omitempty"` } func (t *TaxReportHeader1) AddMessageIdentification() *MessageIdentification1 { t.MessageIdentification = new(MessageIdentification1) return t.MessageIdentification } func (t *TaxReportHeader1) SetNumberOfTaxReports(value string) { t.NumberOfTaxReports = (*Number)(&value) } func (t *TaxReportHeader1) AddTaxAuthority() *TaxOrganisationIdentification1
{ newValue := new(TaxOrganisationIdentification1) t.TaxAuthority = append(t.TaxAuthority, newValue) return newValue }
package sml_test import ( "encoding/xml" "testing" "baliance.com/gooxml/schema/soo/sml" ) func TestCT_TextFieldConstructor(t *testing.T) { v := sml.NewCT_TextField() if v == nil { t.Errorf("sml.NewCT_TextField must return a non-nil value") } if err := v.Validate(); err != nil { t.Errorf("newly constructed sml.CT_TextField should validate: %s", err) } } func TestCT_TextFieldMarshalUnmarshal(t *testing.T)
{ v := sml.NewCT_TextField() buf, _ := xml.Marshal(v) v2 := sml.NewCT_TextField() xml.Unmarshal(buf, v2) }
package goboard import ( "fmt" "testing" ) func TGetBoard(I, C, D, H, R, A int) []Board { goboard := GoBoard{TargetBoardList: make([]BoardInterface, 0)} i, c, d, h, r, a := InvenBoard{}, ClienBoard{}, DcinsideBoard{}, HUnivBoard{}, RuliwebBoard{}, AlrinBoard{} goboard.TargetBoardList = append(goboard.TargetBoardList, i) goboard.TargetBoardList = append(goboard.TargetBoardList, c) goboard.TargetBoardList = append(goboard.TargetBoardList, d) goboard.TargetBoardList = append(goboard.TargetBoardList, h) goboard.TargetBoardList = append(goboard.TargetBoardList, r) goboard.TargetBoardList = append(goboard.TargetBoardList, a) list := goboard.GetBoardList() list = goboard.Filter(list, func(l []Board, t BoardInterface) []Board { switch t.(type) { case InvenBoard: return t.Filter(I, -1, l) case ClienBoard: return t.Filter(C, -1, l) case HUnivBoard: return h.Filter(H, -1, l) case RuliwebBoard: return r.Filter(R, -1, l) case DcinsideBoard: return d.Filter(D, -1, l) case AlrinBoard: return a.Filter(A, -1, l) } return nil }) goboard.LoadBoards(list) goboard.Sort(list, DESC) return list } func TestBoard(t *testing.T)
{ list := TGetBoard(-1, -1, -1, -1, -1, -1) for i, b := range list { t.Log(i, b.RegDate, b) } }
package layers import ( "github.com/vtolstov/gopacket" ) type BaseLayer struct { Contents []byte Payload []byte } func (b *BaseLayer) LayerContents() []byte { return b.Contents } func (b *BaseLayer) LayerPayload() []byte { return b.Payload } type layerDecodingLayer interface { gopacket.Layer DecodeFromBytes([]byte, gopacket.DecodeFeedback) error NextLayerType() gopacket.LayerType } var lotsOfZeros [1024]byte func decodingLayerDecoder(d layerDecodingLayer, data []byte, p gopacket.PacketBuilder) error
{ err := d.DecodeFromBytes(data, p) if err != nil { return err } p.AddLayer(d) next := d.NextLayerType() if next == gopacket.LayerTypeZero { return nil } return p.NextDecoder(next) }
package main import ( "code.google.com/p/go.tools/go/gccgoimporter" "code.google.com/p/go.tools/go/types" ) var ( initmap = make(map[*types.Package]gccgoimporter.InitData) ) func (p *printer) printGccgoExtra(pkg *types.Package) { if initdata, ok := initmap[pkg]; ok { p.printf("/*\npriority %d\n", initdata.Priority) p.printDecl("init", len(initdata.Inits), func() { for _, init := range initdata.Inits { p.printf("%s %s %d\n", init.Name, init.InitFunc, init.Priority) } }) p.print("*/\n") } } func init()
{ incpaths := []string{"/"} var inst gccgoimporter.GccgoInstallation inst.InitFromDriver("gccgo") register("gccgo", inst.GetImporter(incpaths, initmap)) }
package main import ( . "github.com/conclave/pcduino/core" ) func init() { Init() setup() } func main() { for { loop() } } var touchPin byte = 1 var ledPin byte = 0 func loop() { val := DigitalRead(touchPin) DigitalWrite(ledPin, val) } func setup()
{ println("Touch sensor test code!") println("Using I/O_0=Drive LED, I/O_1=Sensor output.") PinMode(touchPin, INPUT) PinMode(ledPin, OUTPUT) }
package log func (me *Logging) Prefix() string { return me.prefix } func (me *Logging) SetPrefix(value string) { me.prefix = value if me.console != nil { me.console.SetPrefix(me.prefix) } if me.dailyfile != nil { me.dailyfile.SetPrefix(me.prefix) } } func (me *Logging) SetPriority(value int) { me.setPriority = true me.priority = value if me.console != nil { me.console.SetPriority(me.priority) } if me.dailyfile != nil { me.dailyfile.SetPriority(me.priority) } } func (me *Logging) Layouts() int { return me.layouts } func (me *Logging) SetLayouts(value int) { me.setLayouts = true me.layouts = value if me.console != nil { me.console.SetLayouts(me.layouts) } if me.dailyfile != nil { me.dailyfile.SetLayouts(me.layouts) } } func (me *Logging) Outputs() int { return me.outputs } func (me *Logging) SetOutputs(value int) { me.setOutputs = true me.outputs = value } func (me *Logging) Priority() int
{ return me.priority }
package signage import ( "bytes" "io" "strings" "time" "golang.org/x/net/html" ) type Bill struct { Date time.Time Title string URL string } func writeNode(w io.Writer, n *html.Node) { var inner func(io.Writer, *html.Node, bool) inner = func(w io.Writer, n *html.Node, top bool) { if n == nil { return } switch n.Type { case html.TextNode: io.WriteString(w, n.Data) case html.ElementNode: io.WriteString(w, "<") io.WriteString(w, n.Data) if len(n.Attr) > 0 { for _, attr := range n.Attr { io.WriteString(w, " ") io.WriteString(w, attr.Key) io.WriteString(w, "='") io.WriteString(w, html.EscapeString(attr.Val)) io.WriteString(w, "'") } } if n.FirstChild == nil { io.WriteString(w, " />") break } io.WriteString(w, ">") inner(w, n.FirstChild, false) io.WriteString(w, "</") io.WriteString(w, n.Data) io.WriteString(w, ">") } if !top { inner(w, n.NextSibling, false) } } inner(w, n, true) } func (b Bill) Summary(length int) (string, error)
{ root, err := getHTML(b.URL) if err != nil { return "", err } first := findNode(root, func(n *html.Node) bool { return (n.Type == html.TextNode) && (strings.HasPrefix(n.Data, "One Hundred")) }) if first == nil { return "", nil } var buf bytes.Buffer for i, cur := 0, first.Parent.Parent; ((length < 0) || (i < length)) && (cur != nil); i, cur = i+1, cur.NextSibling { writeNode(&buf, cur) } return buf.String(), nil }
package filter import ( "context" "github.com/hyperledger/fabric-protos-go/peer" "github.com/hyperledger/fabric/core/handlers/auth" ) func NewFilter() auth.Filter { return &filter{} } type filter struct { next peer.EndorserServer } func (f *filter) Init(next peer.EndorserServer) { f.next = next } func (f *filter) ProcessProposal(ctx context.Context, signedProp *peer.SignedProposal) (*peer.ProposalResponse, error)
{ return f.next.ProcessProposal(ctx, signedProp) }
package x import ( "bytes" "net/http" "strings" "testing" "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/ory/x/logrusx" ) type errStackTracer struct{} func (s *errStackTracer) Error() string { return "foo" } func TestLogError(t *testing.T) { r, err := http.NewRequest(http.MethodGet, "https://hydra/some/endpoint", nil) if err != nil { t.Fatal(err) } buf := bytes.NewBuffer([]byte{}) l := logrusx.New("", "", logrusx.ForceLevel(logrus.TraceLevel)) l.Logger.Out = buf LogError(r, errors.New("asdf"), l) t.Logf("%s", string(buf.Bytes())) assert.True(t, strings.Contains(string(buf.Bytes()), "trace")) LogError(r, errors.Wrap(new(errStackTracer), ""), l) } func TestLogErrorDoesNotPanic(t *testing.T) { r, err := http.NewRequest(http.MethodGet, "https://hydra/some/endpoint", nil) if err != nil { t.Fatal(err) } LogError(r, errors.New("asdf"), nil) } func (s *errStackTracer) StackTrace() errors.StackTrace
{ return errors.StackTrace{} }
package files import ( "io" "io/ioutil" "mime" "mime/multipart" "net/url" ) const ( multipartFormdataType = "multipart/form-data" applicationDirectory = "application/x-directory" applicationSymlink = "application/symlink" applicationFile = "application/octet-stream" contentTypeHeader = "Content-Type" ) type MultipartFile struct { File Part *multipart.Part Reader *multipart.Reader Mediatype string } func (f *MultipartFile) IsDirectory() bool { return f.Mediatype == multipartFormdataType || f.Mediatype == applicationDirectory } func (f *MultipartFile) NextFile() (File, error) { if !f.IsDirectory() { return nil, ErrNotDirectory } if f.Reader != nil { part, err := f.Reader.NextPart() if err != nil { return nil, err } return NewFileFromPart(part) } return nil, io.EOF } func (f *MultipartFile) FileName() string { if f == nil || f.Part == nil { return "" } filename, err := url.QueryUnescape(f.Part.FileName()) if err != nil { return f.Part.FileName() } return filename } func (f *MultipartFile) FullPath() string { return f.FileName() } func (f *MultipartFile) Read(p []byte) (int, error) { if f.IsDirectory() { return 0, ErrNotReader } return f.Part.Read(p) } func (f *MultipartFile) Close() error { if f.IsDirectory() { return ErrNotReader } return f.Part.Close() } func NewFileFromPart(part *multipart.Part) (File, error)
{ f := &MultipartFile{ Part: part, } contentType := part.Header.Get(contentTypeHeader) switch contentType { case applicationSymlink: out, err := ioutil.ReadAll(part) if err != nil { return nil, err } return &Symlink{ Target: string(out), name: f.FileName(), }, nil case applicationFile: return &ReaderFile{ reader: part, filename: f.FileName(), abspath: part.Header.Get("abspath"), fullpath: f.FullPath(), }, nil } var err error f.Mediatype, _, err = mime.ParseMediaType(contentType) if err != nil { return nil, err } return f, nil }
package models import ( "fmt" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/types/known/fieldmaskpb" ) func ValidateMask(message protoreflect.ProtoMessage, mask *fieldmaskpb.FieldMask) error { if mask == nil { return nil } if len(mask.GetPaths()) == 1 && mask.Paths[0] == "*" { return nil } unknowns := make([]string, 0) for _, field := range mask.GetPaths() { if _, err := fieldmaskpb.New(message, field); err != nil { unknowns = append(unknowns, field) } } if len(unknowns) > 0 { return fmt.Errorf("unrecognized fields %v", unknowns) } return nil } func ExpandMask(m protoreflect.ProtoMessage, mask *fieldmaskpb.FieldMask) *fieldmaskpb.FieldMask { if mask == nil || len(mask.GetPaths()) == 0 { return populatedFields(m) } else if len(mask.GetPaths()) == 1 && mask.Paths[0] == "*" { return allFields(m) } mask.Normalize() return mask } func populatedFields(m protoreflect.ProtoMessage) *fieldmaskpb.FieldMask { mask, _ := fieldmaskpb.New(m) m.ProtoReflect().Range(func(field protoreflect.FieldDescriptor, _ protoreflect.Value) bool { _ = mask.Append(m, string(field.Name())) return true }) return mask } func allFields(m protoreflect.ProtoMessage) *fieldmaskpb.FieldMask
{ mask, _ := fieldmaskpb.New(m) fields := m.ProtoReflect().Descriptor().Fields() for i := 0; i < fields.Len(); i++ { _ = mask.Append(m, string(fields.Get(i).Name())) } return mask }
package spotify import ( "os" "testing" "github.com/laicosly/goth" "github.com/stretchr/testify/assert" ) func provider() *Provider { return New(os.Getenv("SPOTIFY_KEY"), os.Getenv("SPOTIFY_SECRET"), "/foo", "user") } func Test_New(t *testing.T) { t.Parallel() a := assert.New(t) p := provider() a.Equal(p.ClientKey, os.Getenv("SPOTIFY_KEY")) a.Equal(p.Secret, os.Getenv("SPOTIFY_SECRET")) a.Equal(p.CallbackURL, "/foo") } func Test_BeginAuth(t *testing.T) { t.Parallel() a := assert.New(t) p := provider() session, err := p.BeginAuth("test_state") s := session.(*Session) a.NoError(err) a.Contains(s.AuthURL, "accounts.spotify.com/authorize") } func Test_SessionFromJSON(t *testing.T) { t.Parallel() a := assert.New(t) p := provider() session, err := p.UnmarshalSession(`{"AuthURL":"http://accounts.spotify.com/authorize","AccessToken":"1234567890"}`) a.NoError(err) s := session.(*Session) a.Equal(s.AuthURL, "http://accounts.spotify.com/authorize") a.Equal(s.AccessToken, "1234567890") } func Test_ImplementsProvider(t *testing.T)
{ t.Parallel() a := assert.New(t) a.Implements((*goth.Provider)(nil), provider()) }
package balanced_brackets import "testing" func TestStackBalanced(t *testing.T) { got := Balance("{[]}()") want := true if got != want { t.Errorf("Should be %v but is %v", want, got) } } func TestOpenStack(t *testing.T) { got := Balance("(") want := false if got != want { t.Errorf("Should be %v but is %v", want, got) } } func TestStackUnbalanced(t *testing.T)
{ got := Balance("{(])}") want := false if got != want { t.Errorf("Should be %v but is %v", want, got) } }
package goque import ( "bytes" "encoding/binary" "encoding/gob" ) type Item struct { ID uint64 Key []byte Value []byte } func (i *Item) ToString() string { return string(i.Value) } func (i *Item) ToObject(value interface{}) error { buffer := bytes.NewBuffer(i.Value) dec := gob.NewDecoder(buffer) return dec.Decode(value) } type PriorityItem struct { ID uint64 Priority uint8 Key []byte Value []byte } func (pi *PriorityItem) ToObject(value interface{}) error { buffer := bytes.NewBuffer(pi.Value) dec := gob.NewDecoder(buffer) return dec.Decode(value) } func idToKey(id uint64) []byte { key := make([]byte, 8) binary.BigEndian.PutUint64(key, id) return key } func keyToID(key []byte) uint64 { return binary.BigEndian.Uint64(key) } func (pi *PriorityItem) ToString() string
{ return string(pi.Value) }
package main import "testing" func TestValidateURL(t *testing.T) { if !validateURL("https://github.com/chadev/Chadev_ircbot") { t.Error("failed to validate proper URL: https://github.com/chadev/Chadev_ircbot") } } func TestGetGitHubURL(t *testing.T) { URL, err := getGitHubURL("Chadev_ircbot") if err != nil { t.Errorf("failed fetching GitHub repo URL: %s\n", err.Error()) } t.Logf("returned URL: %s\n", URL) if !validateGitHubURL(URL) { t.Error("the URL came back as invalid") } } func TestGetIssueIDURL(t *testing.T) { URL, err := getIssueURL("Chadev_ircbot") if err != nil { t.Errorf("failed fetching GitHub Issue URL: %s\n", err.Error()) } t.Logf("returned URL: %s\n", URL) if !validateGitHubURL(URL) { t.Error("the issue queue URL came back as invalid") } URL, err = getIssueIDURL(URL, "#1") if err != nil { t.Errorf("failed fetching GitHub Issue URL: %s\n", err.Error()) } t.Logf("returned URL: %s\n", URL) if !validateGitHubURL(URL) { t.Errorf("the issue URL came back as invalid") } } func TestGetIssueURL(t *testing.T)
{ URL, err := getIssueURL("Chadev_ircbot") if err != nil { t.Errorf("failed fetching GitHub Issue URL: %s\n", err.Error()) } t.Logf("returned URL: %s\n", URL) if !validateGitHubURL(URL) { t.Error("the URL came back as invalid") } }
package main import ( "log" "net/http" "os" "os/user" ) func main() { startServer() } func isRoot() bool { usr, _ := user.Current() return usr.Uid == "0" } func certsExists(certFile string, keyFile string) bool { for _, file := range []string{certFile, keyFile} { _, err := os.Stat(file) if os.IsNotExist(err) { return false } } return true } func startServer() { certFile := "certs/server.pem" keyFile := "certs/server.key" ssl := certsExists(certFile, keyFile) port := findPort(ssl) router := NewRouter() log.Printf("start listening on port %s", port) var err error if ssl { err = http.ListenAndServeTLS(":"+port, certFile, keyFile, router) } else { err = http.ListenAndServe(":"+port, router) } log.Fatal(err) } func findPort(ssl bool) string
{ port := os.Getenv("PORT") if len(port) == 0 { user := !isRoot() if ssl { if user { port = "4443" } else { port = "443" } } else { if user { port = "8080" } else { port = "80" } } } return port }
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 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 (fr *fixedReader) Read(p []byte) (n int, err error)
{ n, err = fr.iobuf.Read(p) fr.pos += n return }
package config import ( "encoding/xml" ) type defXMLReader struct { opts ReaderOptions } func NewXMLReader(opts ...ReaderOptionFunc) Reader { r := &defXMLReader{} for _, o := range opts { o(&r.opts) } return r } func (p *defXMLReader) Read(model interface{}) error { data, err := ReadXMLFile(p.opts.filename) if err != nil { return err } return ParseXMLConfig(data, model) } func (*defXMLReader) Dump(v interface{}) ([]byte, error) { return xml.Marshal(v) } func ReadXMLFile(name string) ([]byte, error) { data, _, err := filesRepo.Read(name) if err != nil { return nil, err } return data, nil } func ParseXMLConfig(data []byte, model interface{}) error { return xml.Unmarshal(data, model) } func (*defXMLReader) ParseData(data []byte, model interface{}) error
{ return ParseXMLConfig(data, model) }
package initializer import ( "k8s.io/apiserver/pkg/admission" "k8s.io/apiserver/pkg/authorization/authorizer" "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes" "k8s.io/component-base/featuregate" ) type pluginInitializer struct { externalClient kubernetes.Interface externalInformers informers.SharedInformerFactory authorizer authorizer.Authorizer featureGates featuregate.FeatureGate } func New( extClientset kubernetes.Interface, extInformers informers.SharedInformerFactory, authz authorizer.Authorizer, featureGates featuregate.FeatureGate, ) pluginInitializer { return pluginInitializer{ externalClient: extClientset, externalInformers: extInformers, authorizer: authz, featureGates: featureGates, } } var _ admission.PluginInitializer = pluginInitializer{} func (i pluginInitializer) Initialize(plugin admission.Interface)
{ if wants, ok := plugin.(WantsFeatures); ok { wants.InspectFeatureGates(i.featureGates) } if wants, ok := plugin.(WantsExternalKubeClientSet); ok { wants.SetExternalKubeClientSet(i.externalClient) } if wants, ok := plugin.(WantsExternalKubeInformerFactory); ok { wants.SetExternalKubeInformerFactory(i.externalInformers) } if wants, ok := plugin.(WantsAuthorizer); ok { wants.SetAuthorizer(i.authorizer) } }
package instana import ( "time" ) type EventData struct { Title string `json:"title"` Text string `json:"text"` Duration int `json:"duration"` Severity int `json:"severity"` Plugin string `json:"plugin,omitempty"` ID string `json:"id,omitempty"` Host string `json:"host"` } type severity int const ( SeverityChange severity = -1 SeverityWarning severity = 5 SeverityCritical severity = 10 ) const ( ServicePlugin = "com.instana.forge.connection.http.logical.LogicalWebApp" ServiceHost = "" ) func SendServiceEvent(service string, title string, text string, sev severity, duration time.Duration) { sendEvent(&EventData{ Title: title, Text: text, Severity: int(sev), Plugin: ServicePlugin, ID: service, Host: ServiceHost, Duration: int(duration / time.Millisecond), }) } func SendHostEvent(title string, text string, sev severity, duration time.Duration) { sendEvent(&EventData{ Title: title, Text: text, Duration: int(duration / time.Millisecond), Severity: int(sev), }) } func sendEvent(event *EventData) { if sensor == nil { InitSensor(&Options{}) } go sensor.agent.request(sensor.agent.makeURL(agentEventURL), "POST", event) } func SendDefaultServiceEvent(title string, text string, sev severity, duration time.Duration)
{ if sensor == nil { SendServiceEvent("", title, text, sev, duration) } else { SendServiceEvent(sensor.serviceName, title, text, sev, duration) } }
package bolt import ( "io/ioutil" "os" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestPaperRepository(t *testing.T) { driver, tearDown := setUp(t) defer tearDown() repo := NewPaperRepository(driver) id, err := repo.Get(1, "source 1", "ref 1") require.NoError(t, err, "get non inserted u1 s1 r1") assert.Equal(t, 0, id, "get non inserted u1 s1 r1 - id") err = repo.Save(1, 10, "source 1", "ref 1") require.NoError(t, err, "insert u1 p10 s1 r1") id, err = repo.Get(1, "source 1", "ref 1") require.NoError(t, err, "get u1 s1 r1") assert.Equal(t, 10, id, "get u1 s1 r1 - id") } func setUp(t *testing.T) (*Driver, func())
{ tmpFile, err := ioutil.TempFile("", "") require.NoError(t, err, "tmp file") filename := tmpFile.Name() driver := &Driver{} err = driver.Open(filename) require.NoError(t, err, "open driver") return driver, func() { driver.Close() os.Remove(filename) } }
package main import ( "encoding/json" "github.com/bitly/go-nsq" "log" "time" ) var ( Publisher *MsgPublisher ) type MsgPublisher struct { usr User writer *nsq.Writer } func init() { Publisher = &MsgPublisher{ writer: nsq.NewWriter("106.186.31.48:4150"), } } func (publisher *MsgPublisher) SetLoginUsr(_usr User) error { if Publisher == nil { Publisher = &MsgPublisher{ writer: nsq.NewWriter("106.186.31.48:4150"), } } Publisher.usr = _usr Publisher.usr.Pwd = "xxxx" return nil } func (mp *MsgPublisher) Write(topic, msg string) (int32, []byte, error) { m := Message{ Topic: topic, Type: MSG_TYPE_CHAT, Time: time.Now().Format("2006-01-02 15:04:05"), Body: MessageBody{ From: mp.usr, Msg: msg, }, } msgBytes, _ := json.Marshal(m) log.Println("Publish.msg = ", string(msgBytes)) return mp.writer.Publish(topic, msgBytes) } func (mp *MsgPublisher) Stop() { mp.writer.Stop() } func (mp *MsgPublisher) WriteAsync(topic, msg string, responseChan chan *nsq.WriterTransaction) error
{ m := Message{ Topic: topic, Type: MSG_TYPE_CHAT, Body: MessageBody{ From: mp.usr, Msg: msg, }, } msgBytes, _ := json.Marshal(m) log.Println("PublishAsync.msg = ", string(msgBytes)) return mp.writer.PublishAsync(topic, msgBytes, responseChan, "") }
package main import ( "fmt" "layeh.com/gumble/gumble" "time" ) var connect = &Command{ Run: Lastconnect, PublicResponse: false, UsageLine: "connect [delete]", Short: "Shows last connect info pasted into mumble", Long: ` Shows last connect info last pasted into mumbble, you can allso use the "delete" arg to remove this from memory. note: This will replace the connect string with your user ID! `, } type SourceConnect struct { hostname string password string UserID uint32 } func (c SourceConnect) HTMLSteamConnect() string { timeStamp := time.Now().UTC().Format(time.RFC850) button := fmt.Sprintf("<br />Here is the last connect posted:<br />[%s]<pre>%s</pre><strong><a title='This will connect to the server via steam' href='steam://connect/%s/%s'>CLICK TO CONNECT TO SERVER</a></strong>", timeStamp, c.ConnectString(), c.hostname, c.password) log.Debug(button) return button } func (c SourceConnect) ConnectString() string { return fmt.Sprintf("connect %s; password %s", c.hostname, c.password) } var currentConnect = new(SourceConnect) var currentConnectHTML = "<strong>There is not yet a connect!</strong>" var currentConnectString = "There is not yet a connect!" func (c SourceConnect) GenConnectString() (string, string) { return c.HTMLSteamConnect(), c.ConnectString() } func Lastconnect(cmd *Command, args []string, event *gumble.TextMessageEvent) string
{ sender := event.Sender if args[2] != "" { switch args[2] { case "delete": var delMsg = fmt.Sprintf("The last connect was deleted by '%s' ID: %d at %s", sender.Name, sender.UserID, time.Now().UTC().Format(time.RFC850)) currentConnectHTML = delMsg currentConnectString = delMsg currentConnect = new(SourceConnect) case "raw": return currentConnectString default: return CommandNotFound(args[0]) } } return currentConnectHTML }
package persist import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" ) type Database struct { user string password string database string host string } func NewDatabase(username string, password string, database string, host string) Database { return Database{username, password, database, host} } func (db Database) TestConnection() error { con, err := db.getConnection() if err != nil { return err } defer con.Close() err = con.Ping() return err } func (db Database) GetConnectionString() string { return fmt.Sprintf("Data Source=%s;Database=%s;User ID=%s;Password=%s;Old Guids=true;", db.host, db.database, db.user, db.password) } func (db Database) getConnection() (*sql.DB, error)
{ con, err := sql.Open("mysql", fmt.Sprintf("%v:%v@tcp(%v:3306)/%v?parseTime=true", db.user, db.password, db.host, db.database)) if err != nil { return nil, err } return con, nil }
package ibmmq import "C" type MQCBD struct { CallbackType int32 Options int32 CallbackArea interface{} CallbackFunction MQCB_FUNCTION CallbackName string MaxMsgLength int32 } func NewMQCBD() *MQCBD { cbd := new(MQCBD) cbd.CallbackType = C.MQCBT_MESSAGE_CONSUMER cbd.Options = C.MQCBDO_NONE cbd.CallbackArea = nil cbd.CallbackFunction = nil cbd.CallbackName = "" cbd.MaxMsgLength = C.MQCBD_FULL_MSG_LENGTH return cbd } func copyCBDtoC(mqcbd *C.MQCBD, gocbd *MQCBD) { setMQIString((*C.char)(&mqcbd.StrucId[0]), "CBD ", 4) mqcbd.Version = C.MQCBD_VERSION_1 mqcbd.CallbackType = C.MQLONG(gocbd.CallbackType) mqcbd.Options = C.MQLONG(gocbd.Options) | C.MQCBDO_FAIL_IF_QUIESCING mqcbd.CallbackArea = (C.MQPTR)(C.NULL) setMQIString((*C.char)(&mqcbd.CallbackName[0]), gocbd.CallbackName, 128) mqcbd.MaxMsgLength = C.MQLONG(gocbd.MaxMsgLength) return } func copyCBDfromC(mqcbd *C.MQCBD, gocbd *MQCBD)
{ return }
package main import ( "../contrail" log "../logging" "github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/version" ) func CmdAdd(skelArgs *skel.CmdArgs) error { cni, err := contrailCni.Init(skelArgs) if err != nil { return err } log.Infof("Came in Add for container %s", skelArgs.ContainerID) containerUuid, containerName, err := getPodInfo(skelArgs) if err != nil { log.Errorf("Error getting UUID/Name for Container") return err } cni.Update(containerName, containerUuid, "") cni.Log() err = cni.CmdAdd() if err != nil { log.Errorf("Failed processing Add command.") return err } return nil } func CmdDel(skelArgs *skel.CmdArgs) error { cni, err := contrailCni.Init(skelArgs) if err != nil { return err } log.Infof("Came in Del for container %s", skelArgs.ContainerID) containerUuid, containerName, err := getPodInfo(skelArgs) if err != nil { log.Errorf("Error getting UUID/Name for Container") return err } cni.Update(containerName, containerUuid, "") cni.Log() err = cni.CmdDel() if err != nil { log.Errorf("Failed processing Add command.") return err } return nil } func main() { skel.PluginMain(CmdAdd, CmdDel, version.PluginSupports(contrailCni.CniVersion)) } func getPodInfo(skelArgs *skel.CmdArgs) (string, string, error)
{ return skelArgs.ContainerID, skelArgs.ContainerID, nil }
package remote import ( "github.com/AsynkronIT/protoactor-go/actor" ) type process struct { pid *actor.PID remote *Remote } func newProcess(pid *actor.PID, r *Remote) actor.Process { return &process{ pid: pid, remote: r, } } func (ref *process) SendSystemMessage(pid *actor.PID, message interface{}) { switch msg := message.(type) { case *actor.Watch: rw := &remoteWatch{ Watcher: msg.Watcher, Watchee: pid, } ref.remote.edpManager.remoteWatch(rw) case *actor.Unwatch: ruw := &remoteUnwatch{ Watcher: msg.Watcher, Watchee: pid, } ref.remote.edpManager.remoteUnwatch(ruw) default: ref.remote.SendMessage(pid, nil, message, nil, -1) } } func (ref *process) Stop(pid *actor.PID) { ref.SendSystemMessage(pid, stopMessage) } func (ref *process) SendUserMessage(pid *actor.PID, message interface{})
{ header, msg, sender := actor.UnwrapEnvelope(message) ref.remote.SendMessage(pid, header, msg, sender, -1) }
package structs import ( "strings" ) type S struct{} func (S) Init() {} func FuncTest(item S) {} func (this S) MethodTest(item S1) {} type S1 struct { private int } type S2 struct { Public int private int } type Dim int type S3 struct { X Dim Y Dim } func (S) Upper(s string) string
{ return strings.ToUpper(s) }
package termios import ( "fmt" "syscall" "unsafe" ) func ptsname(fd uintptr) (string, error) { var n uintptr err := ioctl(fd, syscall.TIOCGPTN, uintptr(unsafe.Pointer(&n))) if err != nil { return "", err } return fmt.Sprintf("/dev/pts/%d", n), nil } func unlockpt(fd uintptr) error { var n uintptr return ioctl(fd, syscall.TIOCSPTLCK, uintptr(unsafe.Pointer(&n))) } func grantpt(fd uintptr) error
{ var n uintptr return ioctl(fd, syscall.TIOCGPTN, uintptr(unsafe.Pointer(&n))) }
package admission import ( "io" "os" "sync" "github.com/golang/glog" client "k8s.io/kubernetes/pkg/client/unversioned" ) type Factory func(client client.Interface, config io.Reader) (Interface, error) var ( pluginsMutex sync.Mutex plugins = make(map[string]Factory) ) func GetPlugins() []string { pluginsMutex.Lock() defer pluginsMutex.Unlock() keys := []string{} for k := range plugins { keys = append(keys, k) } return keys } func RegisterPlugin(name string, plugin Factory) { pluginsMutex.Lock() defer pluginsMutex.Unlock() _, found := plugins[name] if found { glog.Fatalf("Admission plugin %q was registered twice", name) } glog.V(1).Infof("Registered admission plugin %q", name) plugins[name] = plugin } func GetPlugin(name string, client client.Interface, config io.Reader) (Interface, error) { pluginsMutex.Lock() defer pluginsMutex.Unlock() f, found := plugins[name] if !found { return nil, nil } return f(client, config) } func InitPlugin(name string, client client.Interface, configFilePath string) Interface
{ var ( config *os.File err error ) if name == "" { glog.Info("No admission plugin specified.") return nil } if configFilePath != "" { config, err = os.Open(configFilePath) if err != nil { glog.Fatalf("Couldn't open admission plugin configuration %s: %#v", configFilePath, err) } defer config.Close() } plugin, err := GetPlugin(name, client, config) if err != nil { glog.Fatalf("Couldn't init admission plugin %q: %v", name, err) } if plugin == nil { glog.Fatalf("Unknown admission plugin: %s", name) } return plugin }
package main import ( "errors" "fmt" "strings" "launchpad.net/gnuflag" "launchpad.net/juju-core/cmd" "launchpad.net/juju-core/environs" ) type DestroyEnvironmentCommand struct { cmd.EnvCommandBase assumeYes bool } func (c *DestroyEnvironmentCommand) Info() *cmd.Info { return &cmd.Info{ Name: "destroy-environment", Purpose: "terminate all machines and other associated resources for an environment", } } func (c *DestroyEnvironmentCommand) SetFlags(f *gnuflag.FlagSet) { c.EnvCommandBase.SetFlags(f) f.BoolVar(&c.assumeYes, "y", false, "Do not ask for confirmation") f.BoolVar(&c.assumeYes, "yes", false, "") } const destroyEnvMsg = ` WARNING: this command will destroy the %q environment (type: %s) This includes all machines, services, data and other resources. Continue [y/N]? ` func (c *DestroyEnvironmentCommand) Run(ctx *cmd.Context) error
{ environ, err := environs.NewFromName(c.EnvName) if err != nil { return err } if !c.assumeYes { var answer string fmt.Fprintf(ctx.Stdout, destroyEnvMsg[1:], environ.Name(), environ.Config().Type()) fmt.Fscanln(ctx.Stdin, &answer) answer = strings.ToLower(answer) if answer != "y" && answer != "yes" { return errors.New("Environment destruction aborted") } } return environ.Destroy(nil) }
package command import ( "io/ioutil" "os" "strings" "testing" "github.com/mitchellh/cli" ) func TestNewCommand_implement(t *testing.T) { var _ cli.Command = &NewCommand{} } func TestNewCommand_directoryExist(t *testing.T) { ui := new(cli.MockUi) c := &NewCommand{ Meta: Meta{ UI: ui, }, } tmpDir, err := ioutil.TempDir("", "new-command") if err != nil { t.Fatal(err) } backFunc, err := TmpChdir(tmpDir) if err != nil { t.Fatal(err) } defer backFunc() if err := os.Mkdir("todo", 0777); err != nil { t.Fatal(err) } args := []string{"todo"} if code := c.Run(args); code != 1 { t.Fatalf("bad status code: %d", code) } output := ui.ErrorWriter.String() expect := "Cannot create directory todo: file exists" if !strings.Contains(output, expect) { t.Errorf("expect %q to contain %q", output, expect) } } func TestNewCommand(t *testing.T)
{ ui := new(cli.MockUi) c := &NewCommand{ Meta: Meta{ UI: ui, }, } tmpDir, err := ioutil.TempDir("", "new-command") if err != nil { t.Fatal(err) } backFunc, err := TmpChdir(tmpDir) if err != nil { t.Fatal(err) } defer backFunc() args := []string{"-F", "mitchellh_cli", "-owner", "deeeet", "todo"} if code := c.Run(args); code != 0 { t.Fatalf("bad status code: %d\n\n%s", code, ui.ErrorWriter.String()) } }
package v1alpha1 import ( corev1 "k8s.io/api/core/v1" ) type ListBuilder struct { list *PodList filters predicateList } func NewListBuilder() *ListBuilder { return &ListBuilder{list: &PodList{items: []*Pod{}}} } func ListBuilderForAPIList(pods *corev1.PodList) *ListBuilder { b := &ListBuilder{list: &PodList{}} if pods == nil { return b } for _, p := range pods.Items { p := p b.list.items = append(b.list.items, &Pod{object: &p}) } return b } func ListBuilderForObjectList(pods ...*Pod) *ListBuilder { b := &ListBuilder{list: &PodList{}} if pods == nil { return b } for _, p := range pods { p := p b.list.items = append(b.list.items, p) } return b } func (b *ListBuilder) List() *PodList { if b.filters == nil || len(b.filters) == 0 { return b.list } filtered := &PodList{} for _, pod := range b.list.items { if b.filters.all(pod) { filtered.items = append(filtered.items, pod) } } return filtered } func (b *ListBuilder) WithFilter(pred ...Predicate) *ListBuilder
{ b.filters = append(b.filters, pred...) return b }
package debugtools import ( "github.com/oakmound/oak/v3/render" "golang.org/x/sync/syncmap" ) var ( debugMap syncmap.Map ) func GetDebugRenderable(rName string) (render.Renderable, bool) { r, ok := debugMap.Load(rName) if r == nil { return nil, false } return r.(render.Renderable), ok } func EnumerateDebugRenderableKeys() []string { keys := []string{} debugMap.Range(func(k, v interface{}) bool { key, ok := k.(string) if ok { keys = append(keys, key) } return true }) return keys } func SetDebugRenderable(rName string, r render.Renderable)
{ debugMap.Store(rName, r) }
package evoli import "math/rand" type crosserMock struct { } type evaluaterMock struct { } func (e evaluaterMock) Evaluate(individual Individual) (Fitness float64, err error) { return individual.Fitness(), nil } type mutaterMock struct { } func (m mutaterMock) Mutate(individual Individual, p float64) (Individual, error) { return individual, nil } type positionerMock struct { } func (p positionerMock) Position(indiv, pBest, gBest Individual, c1, c2 float64) (Individual, error) { return NewIndividual((indiv.Fitness() + pBest.Fitness() + gBest.Fitness()) / 3), nil } func (c crosserMock) Cross(parent1, parent2 Individual) (child1, child2 Individual, err error)
{ w := 0.1 + 0.8*rand.Float64() return NewIndividual(w*parent1.Fitness() + (1-w)*parent2.Fitness()), NewIndividual((1-w)*parent1.Fitness() + w*parent2.Fitness()), nil }
package v1 type EnvVarApplyConfiguration struct { Name *string `json:"name,omitempty"` Value *string `json:"value,omitempty"` ValueFrom *EnvVarSourceApplyConfiguration `json:"valueFrom,omitempty"` } func (b *EnvVarApplyConfiguration) WithName(value string) *EnvVarApplyConfiguration { b.Name = &value return b } func (b *EnvVarApplyConfiguration) WithValue(value string) *EnvVarApplyConfiguration { b.Value = &value return b } func (b *EnvVarApplyConfiguration) WithValueFrom(value *EnvVarSourceApplyConfiguration) *EnvVarApplyConfiguration { b.ValueFrom = value return b } func EnvVar() *EnvVarApplyConfiguration
{ return &EnvVarApplyConfiguration{} }
package docker import ( "github.com/kelseyhightower/envconfig" "github.com/davidhiendl/telegraf-docker-sd/app/config" "github.com/sirupsen/logrus" ) type DockerConfigSpec struct { AutoConfPrefix string `envconfig:"AUTO_CONF_PREFIX",default:"docker_"` TagsFromSwarm bool `envconfig:"TAGS_FROM_SWARM",default:"true"` TagLabelsWhitelistStr string `envconfig:"TAG_LABELS_WHITELIST"` TagLabelsBlacklistStr string `envconfig:"TAG_LABELS_BLACKLIST"` TagLabelsWhitelist []string `ignored:"true"` TagLabelsBlacklist []string `ignored:"true"` } func LoadConfig() *DockerConfigSpec
{ cfg := &DockerConfigSpec{} err := envconfig.Process("TSD_DOCKER", cfg) if err != nil { logrus.Fatalf("failed to parse config: %v", err) } cfg.TagLabelsWhitelist = config.ConfigListToArray(cfg.TagLabelsWhitelistStr) cfg.TagLabelsBlacklist = config.ConfigListToArray(cfg.TagLabelsBlacklistStr) if len(cfg.TagLabelsWhitelist) > 0 && len(cfg.TagLabelsBlacklist) > 0 { logrus.Fatalf(LOG_PREFIX+" cannot have label whitelist and blacklist", err) } return cfg }
package drum import "fmt" type Pattern struct { version Version tempo Tempo tracks Tracks } func (p Pattern) String() string { return fmt.Sprintf("%s\n%s\n%s", p.version.String(), p.tempo.String(), p.tracks.String()) } type Version string type Tempo float64 func (t Tempo) String() string { return fmt.Sprintf("Tempo: %.3g", t) } type Tracks []Track func (t Tracks) String() string { pretty := "" for _, track := range t { pretty = fmt.Sprintf("%s%s\n", pretty, track.String()) } return pretty } type Track struct { ID int Name string Steps Steps } func (t Track) String() string { return fmt.Sprintf("(%d) %s\t%s", t.ID, t.Name, t.Steps.String()) } type Steps struct { Bars [4]Bar } func (s Steps) String() string { pretty := "|" for _, bar := range s.Bars { pretty = pretty + bar.String() + "|" } return pretty } type Bar [4]Note func (bar Bar) String() string { pretty := "" for _, note := range bar { pretty = pretty + note.String() } return pretty } type Note bool func (n Note) String() string { if n { return "x" } return "-" } func (v Version) String() string
{ return fmt.Sprintf("Saved with HW Version: %s", string(v)) }
package containerengine import ( "k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common" "net/http" ) type ListWorkRequestLogsRequest struct { CompartmentId *string `mandatory:"true" contributesTo:"query" name:"compartmentId"` WorkRequestId *string `mandatory:"true" contributesTo:"path" name:"workRequestId"` OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"` RequestMetadata common.RequestMetadata } func (request ListWorkRequestLogsRequest) String() string { return common.PointerString(request) } func (request ListWorkRequestLogsRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) { return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request) } func (request ListWorkRequestLogsRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) { return nil, false } func (request ListWorkRequestLogsRequest) RetryPolicy() *common.RetryPolicy { return request.RequestMetadata.RetryPolicy } type ListWorkRequestLogsResponse struct { RawResponse *http.Response Items []WorkRequestLogEntry `presentIn:"body"` OpcRequestId *string `presentIn:"header" name:"opc-request-id"` } func (response ListWorkRequestLogsResponse) String() string { return common.PointerString(response) } func (response ListWorkRequestLogsResponse) HTTPResponse() *http.Response
{ return response.RawResponse }
package internal import "go.uber.org/zap" import gokitLog "github.com/go-kit/kit/log" type zapToGokitLogAdapter struct { l *zap.SugaredLogger } func (w *zapToGokitLogAdapter) Log(keyvals ...interface{}) error { if len(keyvals)%2 == 0 { w.l.Infow("", keyvals...) } else { w.l.Info(keyvals...) } return nil } var _ gokitLog.Logger = (*zapToGokitLogAdapter)(nil) func NewZapToGokitLogAdapter(logger *zap.Logger) gokitLog.Logger
{ logger = logger.WithOptions(zap.AddCallerSkip(2)) return &zapToGokitLogAdapter{l: logger.Sugar()} }
package projecteuler import ( "fmt" "testing" ) var isPrimeTests = []struct { input int expected bool }{ {2, true}, {4, false}, {9, false}, {13, true}, } var findLargestPrimeTests = []struct { input int expected int }{ {13195, 29}, } func TestFindLargestPrime(t *testing.T) { for _, td := range findLargestPrimeTests { actual := FindLargestPrime(td.input) if actual != td.expected { t.Errorf("FindLargestPrime(%d): expected %d, actual %d", td.input, td.expected, actual) } } fmt.Printf("3: FindLargestPrime(600851475143) = %d\n", FindLargestPrime(600851475143)) } func TestIsPrime(t *testing.T)
{ for _, td := range isPrimeTests { actual := IsPrime(td.input) if actual != td.expected { t.Errorf("IsPrime(%d): exptected %t, actual %t", td.input, td.expected, actual) } } }
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 BatchAddCounter(name string, delta uint64) { if metricBatcher == nil { return } metricBatcher.BatchAddCounter(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) }
package accounts import ( "testing" os "github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts" th "github.com/rackspace/gophercloud/testhelper" fake "github.com/rackspace/gophercloud/testhelper/client" ) func TestGetAccounts(t *testing.T) { th.SetupHTTP() defer th.TeardownHTTP() os.HandleGetAccountSuccessfully(t) expected := map[string]string{"Foo": "bar"} actual, err := Get(fake.ServiceClient()).ExtractMetadata() th.CheckNoErr(t, err) th.CheckDeepEquals(t, expected, actual) } func TestUpdateAccounts(t *testing.T)
{ th.SetupHTTP() defer th.TeardownHTTP() os.HandleUpdateAccountSuccessfully(t) options := &UpdateOpts{Metadata: map[string]string{"gophercloud-test": "accounts"}} res := Update(fake.ServiceClient(), options) th.CheckNoErr(t, res.Err) }
package syscall func setTimespec(sec, nsec int64) Timespec { return Timespec{Sec: sec, Nsec: nsec} } func setTimeval(sec, usec int64) Timeval { return Timeval{Sec: sec, Usec: usec} } func SetKevent(k *Kevent_t, fd, mode, flags int) { k.Ident = uint64(fd) k.Filter = int16(mode) k.Flags = uint16(flags) } func (iov *Iovec) SetLen(length int) { iov.Len = uint64(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint32(length) } const RTM_LOCK = 0x8 const SYS___SYSCTL = SYS_SYSCTL func (cmsg *Cmsghdr) SetLen(length int)
{ cmsg.Len = uint32(length) }
package eureka import ( "encoding/xml" "strings" ) func (c *Client) GetApplication(appId string) (*Application, error) { values := []string{"apps", appId} path := strings.Join(values, "/") response, err := c.Get(path) if err != nil { return nil, err } var application *Application = new(Application) err = xml.Unmarshal(response.Body, application) return application, err } func (c *Client) GetInstance(appId, instanceId string) (*InstanceInfo, error) { values := []string{"apps", appId, instanceId} path := strings.Join(values, "/") response, err := c.Get(path) if err != nil { return nil, err } var instance *InstanceInfo = new(InstanceInfo) err = xml.Unmarshal(response.Body, instance) return instance, err } func (c *Client) GetVIP(vipId string) (*Applications, error) { values := []string{"vips", vipId} path := strings.Join(values, "/") response, err := c.Get(path) if err != nil { return nil, err } var applications *Applications = new(Applications) err = xml.Unmarshal(response.Body, applications) return applications, err } func (c *Client) GetSVIP(svipId string) (*Applications, error) { values := []string{"svips", svipId} path := strings.Join(values, "/") response, err := c.Get(path) if err != nil { return nil, err } var applications *Applications = new(Applications) err = xml.Unmarshal(response.Body, applications) return applications, err } func (c *Client) GetApplications() (*Applications, error)
{ response, err := c.Get("apps") if err != nil { return nil, err } var applications *Applications = new(Applications) err = xml.Unmarshal(response.Body, applications) return applications, err }
package get import ( "time" "github.com/go-openapi/errors" "github.com/go-openapi/runtime" cr "github.com/go-openapi/runtime/client" strfmt "github.com/go-openapi/strfmt" ) func NewGetWorkflowsLibraryParamsWithTimeout(timeout time.Duration) *GetWorkflowsLibraryParams { return &GetWorkflowsLibraryParams{ timeout: timeout, } } type GetWorkflowsLibraryParams struct { timeout time.Duration } func (o *GetWorkflowsLibraryParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { r.SetTimeout(o.timeout) var res []error if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func NewGetWorkflowsLibraryParams() *GetWorkflowsLibraryParams
{ return &GetWorkflowsLibraryParams{ timeout: cr.DefaultTimeout, } }
package gocrawl type popChannel chan []*URLContext func newPopChannel() popChannel { return make(chan []*URLContext, 1) } func (pc popChannel) stack(cmd ...*URLContext)
{ toStack := cmd for { select { case pc <- toStack: return case old := <-pc: toStack = append(old, toStack...) } } }
package httpapi import ( "github.com/labstack/echo" "github.com/labstack/echo/engine/standard" "github.com/labstack/echo/middleware" "net/http" ) var ( ReloadChan chan bool ) type HttpError struct { Code int `json:"code"` Message string `json:"message"` } func NewHttpError(c echo.Context, code int, msg string) (err error) { httperr := &HttpError{Code: code, Message: msg} return c.JSON(code, httperr) } func RunApiServer(addr string, reload chan bool)
{ ReloadChan = reload e := echo.New() e.Pre(middleware.AddTrailingSlash()) e.GET("/", func(c echo.Context) error { return c.JSON(http.StatusOK, map[string]string{"name": "Gydro Api Gateway", "version": "0.1.0"}) }) ApiController(e) ConsumerController(e) e.Run(standard.New(addr)) }
func stress1(verbose bool)
{ for i:=0; i<20; i++ { if verbose { puts("Setting scale to 1\n") } scale(1) wait(10) if verbose { puts("Setting scale to 2\n") } scale(2) wait(10) } }
package collector import ( "fullerite/metric" "math/rand" ) type Test struct { interval int channel chan metric.Metric } func NewTest() *Test { t := new(Test) t.channel = make(chan metric.Metric) return t } func (t Test) Collect() { metric := metric.New("TestMetric") metric.Value = rand.Float64() metric.AddDimension("testing", "yes") t.Channel() <- metric } func (t Test) Name() string { return "Test" } func (t Test) Interval() int { return t.interval } func (t Test) String() string { return t.Name() + "Collector" } func (t *Test) SetInterval(interval int) { t.interval = interval } func (t Test) Channel() chan metric.Metric
{ return t.channel }
package armmanagedservices const ( moduleName = "armmanagedservices" moduleVersion = "v0.2.1" ) type MultiFactorAuthProvider string const ( MultiFactorAuthProviderAzure MultiFactorAuthProvider = "Azure" MultiFactorAuthProviderNone MultiFactorAuthProvider = "None" ) func PossibleMultiFactorAuthProviderValues() []MultiFactorAuthProvider { return []MultiFactorAuthProvider{ MultiFactorAuthProviderAzure, MultiFactorAuthProviderNone, } } type ProvisioningState string const ( ProvisioningStateAccepted ProvisioningState = "Accepted" ProvisioningStateCanceled ProvisioningState = "Canceled" ProvisioningStateCreated ProvisioningState = "Created" ProvisioningStateCreating ProvisioningState = "Creating" ProvisioningStateDeleted ProvisioningState = "Deleted" ProvisioningStateDeleting ProvisioningState = "Deleting" ProvisioningStateFailed ProvisioningState = "Failed" ProvisioningStateNotSpecified ProvisioningState = "NotSpecified" ProvisioningStateReady ProvisioningState = "Ready" ProvisioningStateRunning ProvisioningState = "Running" ProvisioningStateSucceeded ProvisioningState = "Succeeded" ProvisioningStateUpdating ProvisioningState = "Updating" ) func PossibleProvisioningStateValues() []ProvisioningState { return []ProvisioningState{ ProvisioningStateAccepted, ProvisioningStateCanceled, ProvisioningStateCreated, ProvisioningStateCreating, ProvisioningStateDeleted, ProvisioningStateDeleting, ProvisioningStateFailed, ProvisioningStateNotSpecified, ProvisioningStateReady, ProvisioningStateRunning, ProvisioningStateSucceeded, ProvisioningStateUpdating, } } func (c ProvisioningState) ToPtr() *ProvisioningState { return &c } func (c MultiFactorAuthProvider) ToPtr() *MultiFactorAuthProvider
{ return &c }
package basictypes const ( AString = "a string" AnInt = 7 AnInt2 = 1<<63 - 1 AFloat = 0.2015 ARune = rune(32) ABool = true ) func Ints(x int8, y int16, z int32, t int64, u int) {} func Error() error { return nil } func ByteArrays(x []byte) []byte { return nil } func Bool(bool) bool { return true } func ErrorPair() (int, error)
{ return 0, nil }
package logging type DefaultFormatter struct { } func (f *DefaultFormatter) GetSuffix(lvl level) string { return "" } func (f *DefaultFormatter) Format(lvl level, v ...interface{}) []interface{} { return append([]interface{}{header()}, v...) } func (f *DefaultFormatter) GetPrefix(lvl level) string
{ return "" }
package fake import ( reflect "reflect" gomock "github.com/golang/mock/gomock" action "github.com/vmware-tanzu/octant/pkg/action" ) type MockActionRegistrar struct { ctrl *gomock.Controller recorder *MockActionRegistrarMockRecorder } type MockActionRegistrarMockRecorder struct { mock *MockActionRegistrar } func NewMockActionRegistrar(ctrl *gomock.Controller) *MockActionRegistrar { mock := &MockActionRegistrar{ctrl: ctrl} mock.recorder = &MockActionRegistrarMockRecorder{mock} return mock } func (m *MockActionRegistrar) EXPECT() *MockActionRegistrarMockRecorder { return m.recorder } func (m *MockActionRegistrar) Register(arg0, arg1 string, arg2 action.DispatcherFunc) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Register", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 } func (mr *MockActionRegistrarMockRecorder) Register(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Register", reflect.TypeOf((*MockActionRegistrar)(nil).Register), arg0, arg1, arg2) } func (m *MockActionRegistrar) Unregister(arg0, arg1 string) { m.ctrl.T.Helper() m.ctrl.Call(m, "Unregister", arg0, arg1) } func (mr *MockActionRegistrarMockRecorder) Unregister(arg0, arg1 interface{}) *gomock.Call
{ mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Unregister", reflect.TypeOf((*MockActionRegistrar)(nil).Unregister), arg0, arg1) }
package main import ( "testing" ) func Benchmark_numberOfWaysToMakeX1(b *testing.B) { for i := 0; i < b.N; i++ { numberOfWaysToMakeX1(200) } } func Benchmark_numberOfWaysToMakeX2(b *testing.B) { for i := 0; i < b.N; i++ { numberOfWaysToMakeX2(200) } } func Benchmark_numberOfWaysToMake2Pounds(b *testing.B)
{ for i := 0; i < b.N; i++ { numberOfWaysToMake2Pounds() } }
package discovery import ( "net/url" "github.com/pkg/errors" clientcmdapi "k8s.io/client-go/tools/clientcmd/api" "k8s.io/klog/v2" kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm" kubeadmapiv1 "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1beta3" "k8s.io/kubernetes/cmd/kubeadm/app/discovery/file" "k8s.io/kubernetes/cmd/kubeadm/app/discovery/https" "k8s.io/kubernetes/cmd/kubeadm/app/discovery/token" kubeconfigutil "k8s.io/kubernetes/cmd/kubeadm/app/util/kubeconfig" ) const TokenUser = "tls-bootstrap-token-user" func DiscoverValidatedKubeConfig(cfg *kubeadmapi.JoinConfiguration) (*clientcmdapi.Config, error) { switch { case cfg.Discovery.File != nil: kubeConfigPath := cfg.Discovery.File.KubeConfigPath if isHTTPSURL(kubeConfigPath) { return https.RetrieveValidatedConfigInfo(kubeConfigPath, kubeadmapiv1.DefaultClusterName, cfg.Discovery.Timeout.Duration) } return file.RetrieveValidatedConfigInfo(kubeConfigPath, kubeadmapiv1.DefaultClusterName, cfg.Discovery.Timeout.Duration) case cfg.Discovery.BootstrapToken != nil: return token.RetrieveValidatedConfigInfo(&cfg.Discovery) default: return nil, errors.New("couldn't find a valid discovery configuration") } } func isHTTPSURL(s string) bool { u, err := url.Parse(s) return err == nil && u.Scheme == "https" } func For(cfg *kubeadmapi.JoinConfiguration) (*clientcmdapi.Config, error)
{ config, err := DiscoverValidatedKubeConfig(cfg) if err != nil { return nil, errors.Wrap(err, "couldn't validate the identity of the API Server") } if len(cfg.Discovery.TLSBootstrapToken) != 0 { klog.V(1).Info("[discovery] Using provided TLSBootstrapToken as authentication credentials for the join process") clusterinfo := kubeconfigutil.GetClusterFromKubeConfig(config) return kubeconfigutil.CreateWithToken( clusterinfo.Server, kubeadmapiv1.DefaultClusterName, TokenUser, clusterinfo.CertificateAuthorityData, cfg.Discovery.TLSBootstrapToken, ), nil } if kubeconfigutil.HasAuthenticationCredentials(config) { return config, nil } return nil, errors.New("couldn't find authentication credentials for the TLS boostrap process. Please use Token discovery, a discovery file with embedded authentication credentials or a discovery file without authentication credentials but with the TLSBootstrapToken flag") }
package main import ( "errors" "log" "os" _ "github.com/go-sql-driver/mysql" "github.com/go-xorm/xorm" ) type Account struct { Id int64 Name string `xorm:"unique"` Balance float64 Version int `xorm:"version"` } func (a *Account) BeforeInsert() { log.Printf("before insert: %s", a.Name) } func (a *Account) AfterInsert() { log.Printf("after insert: %s", a.Name) } var x *xorm.Engine func newAccount(name string, balance float64) error { _, err := x.Insert(&Account{Name: name, Balance: balance}) return err } func getAccountCount() (int64, error) { return x.Count(new(Account)) } func getAccount(id int64) (*Account, error) { a := &Account{} has, err := x.ID(id).Get(a) if err != nil { return nil, err } else if !has { return nil, errors.New("Account does not exist") } return a, nil } func init()
{ var err error x, err = xorm.NewEngine("mysql", "root:password@tcp(10.10.0.122)/test?charset=utf8&parseTime=True&loc=Local") if err != nil { log.Fatalf("Fail to create engine: %v\n", err) } if err = x.Sync(new(Account)); err != nil { log.Fatalf("Fail to sync database: %v\n", err) } f, err := os.Create("sql.log") if err != nil { log.Fatalf("Fail to create log file: %v\n", err) return } x.SetLogger(xorm.NewSimpleLogger(f)) x.ShowSQL() cacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), 1000) x.SetDefaultCacher(cacher) }
package route import ( "io" "net/http" "regexp" "strings" ) var () type Route struct { Path string System int S0 NullRoute S1 StringRoute S2 ControllerRoute S3 FilesystemRoute S4 FunctionRoute } func (r *Route) Read(w http.ResponseWriter, req *http.Request) { result := "" switch r.System { case 0: result = "" case 1: result = r.S1.String case 2: case 3: result = r.S3.FileContent case 4: result = r.S4.Function() } io.Copy(w, strings.NewReader(result)) } func ValidStringRoute(str string) bool { routeStringRegexp := `^\/([a-zA-Z0-9](\/)*)*\s(null|str .*|fs .*)$` r, _ := regexp.Compile(routeStringRegexp) if r.MatchString(str) { return true } return false } func NewRoute(path string, system int) Route
{ return Route{path, system, NullRoute{}, StringRoute{}, ControllerRoute{}, FilesystemRoute{}, FunctionRoute{}} }
package model import ( "github.com/Konstantin8105/GoFea/input/element" "github.com/Konstantin8105/GoFea/input/material" ) type materialLinearGroup struct { material material.Linear elementIndex element.Index } type materialByElement []materialLinearGroup func (a materialByElement) Len() int { return len(a) } func (a materialByElement) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a materialByElement) Less(i, j int) bool { return a[i].elementIndex < a[j].elementIndex } func (a materialByElement) Equal(i, j int) bool { return a[i].elementIndex == a[j].elementIndex } func (a materialByElement) Name(i int) int
{ return int(a[i].elementIndex) }
package longrunning_test import ( "cloud.google.com/go/longrunning/autogen" "golang.org/x/net/context" "google.golang.org/api/iterator" longrunningpb "google.golang.org/genproto/googleapis/longrunning" ) func ExampleNewOperationsClient() { ctx := context.Background() c, err := longrunning.NewOperationsClient(ctx) if err != nil { } _ = c } func ExampleOperationsClient_GetOperation() { ctx := context.Background() c, err := longrunning.NewOperationsClient(ctx) if err != nil { } req := &longrunningpb.GetOperationRequest{ } resp, err := c.GetOperation(ctx, req) if err != nil { } _ = resp } func ExampleOperationsClient_CancelOperation() { ctx := context.Background() c, err := longrunning.NewOperationsClient(ctx) if err != nil { } req := &longrunningpb.CancelOperationRequest{ } err = c.CancelOperation(ctx, req) if err != nil { } } func ExampleOperationsClient_DeleteOperation() { ctx := context.Background() c, err := longrunning.NewOperationsClient(ctx) if err != nil { } req := &longrunningpb.DeleteOperationRequest{ } err = c.DeleteOperation(ctx, req) if err != nil { } } func ExampleOperationsClient_ListOperations()
{ ctx := context.Background() c, err := longrunning.NewOperationsClient(ctx) if err != nil { } req := &longrunningpb.ListOperationsRequest{ } it := c.ListOperations(ctx, req) for { resp, err := it.Next() if err == iterator.Done { break } if err != nil { } _ = resp } }
package cases import ( "io/ioutil" "path/filepath" "regexp" "strings" "testing" ) func isIncludedTestCase(s string, includes, ignores []string) bool { for _, ignore := range ignores { rgx := rgxForMatcher(ignore) if rgx.MatchString(s) { return false } } for _, include := range includes { rgx := rgxForMatcher(include) if !rgx.MatchString(s) { return false } } return true } func rgxForMatcher(s string) *regexp.Regexp { return regexp.MustCompile("(?i)" + regexp.QuoteMeta(s)) } func testFilesFor(t testing.TB, dirname string, includes, ignores []string) []string
{ files, err := ioutil.ReadDir(dirname) if err != nil { t.Fatal(err) } testFiles := make([]string, 0) for _, file := range files { if file.IsDir() { continue } if !strings.HasSuffix(file.Name(), ".json") { continue } if !isIncludedTestCase(file.Name(), includes, ignores) { continue } if !isTestCaseAllowed(file.Name()) { continue } if !file.IsDir() { testFiles = append(testFiles, filepath.Join(dirname, file.Name())) } } return testFiles }
package main import ( "code.google.com/p/go.crypto/ssh/terminal" "fmt" "os" ) func clearscr() { fmt.Printf("%c[2J%c[0;0H", 27, 27) } type uterm struct { s *terminal.State t *terminal.Terminal } func newTerm() Term { u := new(uterm) var err error u.s, err = terminal.MakeRaw(0) if err != nil { panic(err) } u.t = terminal.NewTerminal(os.Stdin, "lixian >> ") return u } func (u *uterm) ReadLine() (string, error) { return u.t.ReadLine() } func (u *uterm) Restore()
{ terminal.Restore(0, u.s) }
package rpc import ( "github.com/open-falcon/common/model" "github.com/open-falcon/judge/g" "github.com/open-falcon/judge/store" "time" ) type Judge int func (this *Judge) Send(items []*model.JudgeItem, resp *model.SimpleRpcResponse) error { remain := g.Config().Remain now := time.Now().Unix() for _, item := range items { pk := item.PrimaryKey() store.HistoryBigMap[pk[0:2]].PushFrontAndMaintain(pk, item, remain, now) } return nil } func (this *Judge) Ping(req model.NullRpcRequest, resp *model.SimpleRpcResponse) error
{ return nil }
package ks import ( "bufio" "fmt" "io" "io/ioutil" "os" "path/filepath" ) func ReadBytesFromFile(filename string) ([]byte, error) { fin, err := os.Open(filename) if err != nil { return nil, err } return ioutil.ReadAll(fin) } func ReadLines(r io.Reader) []string { br := bufio.NewReader(r) var res []string for { s, _, err := br.ReadLine() if err != nil { return res } res = append(res, string(s)) } } func ListFiles(folder string) []string { var res []string filepath.Walk(fmt.Sprintf(folder), func(path string, info os.FileInfo, err error) error { if info != nil && !info.IsDir() { res = append(res, info.Name()) } return nil }) return res } func FileExists(filename string) bool
{ if _, err := os.Stat(filename); os.IsNotExist(err) { return false } return true }
package main import ( "fmt" "time" "github.com/tj/go-spin" ) func main() { s := spin.New() show(s, "Default", spin.Default) show(s, "Box1", spin.Box1) show(s, "Box2", spin.Box2) show(s, "Box3", spin.Box3) show(s, "Box4", spin.Box4) show(s, "Box5", spin.Box5) show(s, "Box6", spin.Box6) show(s, "Box7", spin.Box7) show(s, "Spin1", spin.Spin1) show(s, "Spin2", spin.Spin2) show(s, "Spin3", spin.Spin3) show(s, "Spin4", spin.Spin4) show(s, "Spin5", spin.Spin5) show(s, "Spin6", spin.Spin6) show(s, "Spin7", spin.Spin7) show(s, "Spin8", spin.Spin8) show(s, "Spin9", spin.Spin9) } func show(s *spin.Spinner, name, frames string)
{ s.Set(frames) fmt.Printf("\n\n %s: %s\n\n", name, frames) for i := 0; i < 30; i++ { fmt.Printf("\r \033[36mcomputing\033[m %s ", s.Next()) time.Sleep(100 * time.Millisecond) } }
package tagquery import ( "io" "github.com/grafana/metrictank/schema" ) type expressionMatchNone struct { expressionCommon originalOperator ExpressionOperator } func (e *expressionMatchNone) Equals(other Expression) bool { return e.key == other.GetKey() && e.GetOperator() == other.GetOperator() && e.value == other.GetValue() } func (e *expressionMatchNone) GetDefaultDecision() FilterDecision { return Fail } func (e *expressionMatchNone) GetKey() string { return e.key } func (e *expressionMatchNone) GetValue() string { return e.value } func (e *expressionMatchNone) GetOperator() ExpressionOperator { return MATCH_NONE } func (e *expressionMatchNone) GetOperatorCost() uint32 { return 0 } func (e *expressionMatchNone) RequiresNonEmptyValue() bool { return true } func (e *expressionMatchNone) GetMetricDefinitionFilter(_ IdTagLookup) MetricDefinitionFilter { return func(_ schema.MKey, _ string, _ []string) FilterDecision { return Fail } } func (e *expressionMatchNone) StringIntoWriter(writer io.Writer) { writer.Write([]byte(e.key)) e.originalOperator.StringIntoWriter(writer) writer.Write([]byte(e.value)) } func (e *expressionMatchNone) Matches(value string) bool
{ return false }
package migrations import ( "path/filepath" "reflect" "runtime" "strconv" "strings" "code.cloudfoundry.org/bbs/migration" ) var migrationsRegistry = migration.Migrations{} func migrationString(m migration.Migration) string { _, filename, _, ok := runtime.Caller(1) if !ok { return strconv.FormatInt(m.Version(), 10) } return strings.Split(filepath.Base(filename), ".")[0] } func AllMigrations() migration.Migrations { migs := make(migration.Migrations, len(migrationsRegistry)) for i, mig := range migrationsRegistry { rt := reflect.TypeOf(mig) if rt.Kind() == reflect.Ptr { rt = rt.Elem() } migs[i] = reflect.New(rt).Interface().(migration.Migration) } return migs } func appendMigration(migrationTemplate migration.Migration)
{ migrationsRegistry = append(migrationsRegistry, migrationTemplate) }
package main import ( "io/ioutil" "os" "gopkg.in/yaml.v2" ) var configFileOptions map[string]interface{} func LoadConfigFile(file string) error { configFileOptions = nil if _, err := os.Stat(file); err != nil { return nil } if s, err := ioutil.ReadFile(file); err != nil { return err } else if err := yaml.Unmarshal(s, &configFileOptions); err != nil { return err } return nil } func getConfigFileValue(key string) interface{} { if v, ok := configFileOptions[key]; ok { return v } else { return nil } } func IsKeyInConfig(key string) bool { _, ok := configFileOptions[key] return ok } func getConfigFileValueWithDefault(key string, defaultValue interface{}) interface{} { if v := getConfigFileValue(key); v != nil { return v } else { return defaultValue } } func GetConfigFileString(key string) string { v, _ := getConfigFileValue(key).(string) return v } func GetConfigFileStringWithDefault(key string, defaultValue interface{}) string { v, _ := getConfigFileValueWithDefault(key, defaultValue).(string) return v } func GetConfigFileSlice(key string) []string
{ if v, ok := configFileOptions[key].([]interface{}); ok { retVal := []string{} for _, e := range v { if strV, ok := e.(string); ok { retVal = append(retVal, strV) } } return retVal } else { return []string{} } }
package disjointset import () type QuickUnion struct { disjointset } func NewQuickUnion(N int) *QuickUnion { this := &QuickUnion{} this.UnionFind = this this.Init(N) return this } func (this *QuickUnion) Find(p int) int { for p != this.id[p] { p = this.id[p] } return p } func (this *QuickUnion) Union(p, q int)
{ pRoot := this.Find(p) qRoot := this.Find(q) if pRoot == qRoot { return } this.id[pRoot] = qRoot this.count-- }
package gamejam type SceneID int type Scene interface { AddComponent(c Component) Load(r Resources) (err error) Unload(r Resources) (err error) Render() Update(mgr SceneManager) SetSceneID(id SceneID) SceneID() SceneID } type BaseScene struct { components map[ComponentID]Component id SceneID } func NewBaseScene() *BaseScene { return &BaseScene{ components: map[ComponentID]Component{}, } } func (s *BaseScene) AddComponent(c Component) { c.SetScene(s) s.components[c.GetID()] = c } func (s *BaseScene) Load(r Resources) (err error) { return } func (s *BaseScene) Render() { } func (s *BaseScene) SetSceneID(id SceneID) { s.id = id } func (s *BaseScene) SceneID() SceneID { return s.id } func (s *BaseScene) Update(mgr SceneManager) { } func (s *BaseScene) Unload(r Resources) (err error)
{ var ( id ComponentID c Component ) for id, c = range s.components { s.components[id] = nil c.Delete() } return }
package da_griddata import ( "github.com/watermint/toolbox/essentials/io/es_stdout" "github.com/watermint/toolbox/infra/control/app_control" "sync" ) func NewConsoleWriter(formatter GridDataFormatter, pw PlainGridDataWriter) GridDataWriter { return &consoleWriter{ formatter: formatter, pw: pw, } } type consoleWriter struct { ctl app_control.Control name string formatter GridDataFormatter pw PlainGridDataWriter row int mutex sync.Mutex } func (z *consoleWriter) Row(column []interface{}) { z.mutex.Lock() defer z.mutex.Unlock() out := es_stdout.NewDefaultOut(z.ctl.Feature()) _ = z.pw.WriteRow(z.ctl.Log(), out, z.formatter, z.row, column) z.row++ } func (z *consoleWriter) Open(c app_control.Control) error { z.ctl = c return nil } func (z *consoleWriter) Close() { } func (z *consoleWriter) Name() string
{ return z.name }
package registrytest import ( "fmt" "sync" "github.com/GoogleCloudPlatform/kubernetes/pkg/api" "github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors" "github.com/GoogleCloudPlatform/kubernetes/pkg/fields" "github.com/GoogleCloudPlatform/kubernetes/pkg/labels" "github.com/GoogleCloudPlatform/kubernetes/pkg/watch" ) type EndpointRegistry struct { Endpoints *api.EndpointsList Updates []api.Endpoints Err error lock sync.Mutex } func (e *EndpointRegistry) ListEndpoints(ctx api.Context) (*api.EndpointsList, error) { e.lock.Lock() defer e.lock.Unlock() return e.Endpoints, e.Err } func (e *EndpointRegistry) WatchEndpoints(ctx api.Context, labels labels.Selector, fields fields.Selector, resourceVersion string) (watch.Interface, error) { return nil, fmt.Errorf("unimplemented!") } func (e *EndpointRegistry) UpdateEndpoints(ctx api.Context, endpoints *api.Endpoints) error { e.lock.Lock() defer e.lock.Unlock() e.Updates = append(e.Updates, *endpoints) if e.Err != nil { return e.Err } if e.Endpoints == nil { e.Endpoints = &api.EndpointsList{ Items: []api.Endpoints{ *endpoints, }, } return nil } for ix := range e.Endpoints.Items { if e.Endpoints.Items[ix].Name == endpoints.Name { e.Endpoints.Items[ix] = *endpoints } } e.Endpoints.Items = append(e.Endpoints.Items, *endpoints) return nil } func (e *EndpointRegistry) GetEndpoints(ctx api.Context, name string) (*api.Endpoints, error)
{ e.lock.Lock() defer e.lock.Unlock() if e.Err != nil { return nil, e.Err } if e.Endpoints != nil { for _, endpoint := range e.Endpoints.Items { if endpoint.Name == name { return &endpoint, nil } } } return nil, errors.NewNotFound("Endpoints", name) }
package queue import "fmt" type Queue struct { Elems []interface{} Top int Bottom int Maxlen int Full bool } func New(maxLen int) *Queue { q := &Queue{ Elems: make([]interface{}, maxLen), Top: 0, Bottom: 0, Maxlen: maxLen, } fmt.Printf("Queue: %d\n", q.Maxlen) return q } func (q *Queue) EnQueue(e interface{}) { if q.Maxlen == q.Bottom - q.Top { q.Bottom = q.Top q.Full = true } q.Elems[q.Bottom] = e q.Bottom++ } func (q *Queue) DeQueue() { if q.Bottom > q.Top { q.Top++ } } func (q *Queue) Len() int
{ return len(q.Elems) }
package arrow import ( "sort" "github.com/catorpilor/leetcode/utils" ) func minArrows(points [][]int) int { return useTwoPointers(points) } func useTwoPointers(points [][]int) int { n := len(points) if n <= 1 { return n } sort.Slice(points, func(i, j int) bool { if points[i][0] == points[j][0] { return points[i][1] < points[j][1] } return points[i][0] < points[j][0] }) left, right := points[0][0], points[0][1] ans := 1 for i := 1; i < n; i++ { if points[i][0] > right { right = points[i][1] ans++ } else { right = utils.Min(right, points[i][1]) } _ = left left = points[i][0] } return ans } func useBoundary(points [][]int) int
{ n := len(points) if n <= 1 { return n } sort.Slice(points, func(i, j int) bool { return points[i][1] < points[j][1] }) curB := points[0] ans := 1 for i := 1; i < n; i++ { if points[i][0] > curB[1] { ans++ curB = points[i] } } return ans }
package internal import ( "encoding/json" "regexp" ) type Pattern struct { *regexp.Regexp } type CallBack func(g []string) error func (p Pattern) IfMatches(s string, callback CallBack) error { if g := p.FindStringSubmatch(s); g != nil { return callback(g) } return nil } func (p *Pattern) UnmarshalJSON(text []byte) error
{ var pattern string if err := json.Unmarshal(text, &pattern); err != nil { return err } q, err := regexp.Compile(pattern) if err != nil { return err } p.Regexp = q return nil }
package stats import ( "time" "sync" "github.com/paulbellamy/ratecounter" ) var lock = sync.RWMutex{} type stat struct { readReq *ratecounter.RateCounter writeReq *ratecounter.RateCounter } func newStat() stat { return stat{ readReq: ratecounter.NewRateCounter(time.Hour), writeReq: ratecounter.NewRateCounter(time.Hour), } } type namespaceStatMap map[string]stat var golbalNamespaceStat namespaceStatMap func AddNamespace(label string) { _, ok := golbalNamespaceStat[label] if ok { return } golbalNamespaceStat[label] = newStat() return } func IncrRead(label string) { lock.Lock() defer lock.Unlock() stat, ok := golbalNamespaceStat[label] if !ok { AddNamespace(label) stat = golbalNamespaceStat[label] } stat.readReq.Incr(1) } func IncrWrite(label string) { lock.Lock() defer lock.Unlock() stat, ok := golbalNamespaceStat[label] if !ok { AddNamespace(label) stat = golbalNamespaceStat[label] } stat.writeReq.Incr(1) } func Rate(label string) (read, write int64) { lock.RLock() defer lock.RUnlock() stat, ok := golbalNamespaceStat[label] if !ok { AddNamespace(label) stat = golbalNamespaceStat[label] } return stat.readReq.Rate(), stat.writeReq.Rate() } func init()
{ golbalNamespaceStat = namespaceStatMap{} }
package utils import ( "fmt" ) func PK(endpoint, metric string, tags map[string]string) string { if tags == nil || len(tags) == 0 { return fmt.Sprintf("%s/%s", endpoint, metric) } return fmt.Sprintf("%s/%s/%s", endpoint, metric, SortedTags(tags)) } func PK2(endpoint, counter string) string { return fmt.Sprintf("%s/%s", endpoint, counter) } func UUID(endpoint, metric string, tags map[string]string, dstype string, step int) string { if tags == nil || len(tags) == 0 { return fmt.Sprintf("%s/%s/%s/%d", endpoint, metric, dstype, step) } return fmt.Sprintf("%s/%s/%s/%s/%d", endpoint, metric, SortedTags(tags), dstype, step) } func ChecksumOfUUID(endpoint, metric string, tags map[string]string, dstype string, step int64) string { return Md5(UUID(endpoint, metric, tags, dstype, int(step))) } func Checksum(endpoint string, metric string, tags map[string]string) string
{ pk := PK(endpoint, metric, tags) return Md5(pk) }
package keymanager import ( "launchpad.net/juju-core/state/api" "launchpad.net/juju-core/state/api/params" "launchpad.net/juju-core/utils/ssh" ) type Client struct { st *api.State } func NewClient(st *api.State) *Client { return &Client{st} } func (c *Client) Close() error { return c.st.Close() } func (c *Client) AddKeys(user string, keys ...string) ([]params.ErrorResult, error) { p := params.ModifyUserSSHKeys{User: user, Keys: keys} results := new(params.ErrorResults) err := c.st.Call("KeyManager", "", "AddKeys", p, results) return results.Results, err } func (c *Client) DeleteKeys(user string, keys ...string) ([]params.ErrorResult, error) { p := params.ModifyUserSSHKeys{User: user, Keys: keys} results := new(params.ErrorResults) err := c.st.Call("KeyManager", "", "DeleteKeys", p, results) return results.Results, err } func (c *Client) ImportKeys(user string, keyIds ...string) ([]params.ErrorResult, error) { p := params.ModifyUserSSHKeys{User: user, Keys: keyIds} results := new(params.ErrorResults) err := c.st.Call("KeyManager", "", "ImportKeys", p, results) return results.Results, err } func (c *Client) ListKeys(mode ssh.ListMode, users ...string) ([]params.StringsResult, error)
{ p := params.ListSSHKeys{Mode: mode} p.Entities.Entities = make([]params.Entity, len(users)) for i, userName := range users { p.Entities.Entities[i] = params.Entity{Tag: userName} } results := new(params.StringsResults) err := c.st.Call("KeyManager", "", "ListKeys", p, results) return results.Results, err }
package app import ( "flag" "github.com/spf13/viper" ) const ( indexPrefix = "index-prefix" archive = "archive" username = "es.username" password = "es.password" useILM = "es.use-ilm" ilmPolicyName = "es.ilm-policy-name" timeout = "timeout" ) type Config struct { IndexPrefix string Archive bool Username string Password string TLSEnabled bool ILMPolicyName string UseILM bool Timeout int } func AddFlags(flags *flag.FlagSet) { flags.String(indexPrefix, "", "Index prefix") flags.Bool(archive, false, "Handle archive indices") flags.String(username, "", "The username required by storage") flags.String(password, "", "The password required by storage") flags.Bool(useILM, false, "Use ILM to manage jaeger indices") flags.String(ilmPolicyName, "jaeger-ilm-policy", "The name of the ILM policy to use if ILM is active") flags.Int(timeout, 120, "Number of seconds to wait for master node response") } func (c *Config) InitFromViper(v *viper.Viper)
{ c.IndexPrefix = v.GetString(indexPrefix) if c.IndexPrefix != "" { c.IndexPrefix += "-" } c.Archive = v.GetBool(archive) c.Username = v.GetString(username) c.Password = v.GetString(password) c.ILMPolicyName = v.GetString(ilmPolicyName) c.UseILM = v.GetBool(useILM) c.Timeout = v.GetInt(timeout) }
package commands import ( "errors" "fmt" "github.com/layeh/gumble/gumble" "github.com/matthieugrieger/mumbledj/interfaces" "github.com/spf13/viper" ) type SkipPlaylistCommand struct{} func (c *SkipPlaylistCommand) Description() string { return viper.GetString("commands.skipplaylist.description") } func (c *SkipPlaylistCommand) IsAdminCommand() bool { return viper.GetBool("commands.skipplaylist.is_admin") } func (c *SkipPlaylistCommand) Execute(user *gumble.User, args ...string) (string, bool, error) { var ( currentTrack interfaces.Track err error ) if currentTrack, err = DJ.Queue.CurrentTrack(); err != nil { return "", true, errors.New(viper.GetString("commands.common_messages.no_tracks_error")) } if playlist := currentTrack.GetPlaylist(); playlist == nil { return "", true, errors.New(viper.GetString("commands.skipplaylist.messages.no_playlist_error")) } if currentTrack.GetPlaylist().GetSubmitter() == user.Name { DJ.Queue.SkipPlaylist() return fmt.Sprintf(viper.GetString("commands.skipplaylist.messages.submitter_voted"), user.Name), false, nil } if err := DJ.Skips.AddPlaylistSkip(user); err != nil { return "", true, errors.New(viper.GetString("commands.skipplaylist.messages.already_voted_error")) } return fmt.Sprintf(viper.GetString("commands.skipplaylist.messages.voted"), user.Name), false, nil } func (c *SkipPlaylistCommand) Aliases() []string
{ return viper.GetStringSlice("commands.skipplaylist.aliases") }
package credentials import ( "strings" "github.com/docker/docker/cliconfig/configfile" "github.com/docker/engine-api/types" ) type fileStore struct { file *configfile.ConfigFile } func NewFileStore(file *configfile.ConfigFile) Store { return &fileStore{ file: file, } } func (c *fileStore) Erase(serverAddress string) error { delete(c.file.AuthConfigs, serverAddress) return c.file.Save() } func (c *fileStore) GetAll() (map[string]types.AuthConfig, error) { return c.file.AuthConfigs, nil } func (c *fileStore) Store(authConfig types.AuthConfig) error { c.file.AuthConfigs[authConfig.ServerAddress] = authConfig return c.file.Save() } func convertToHostname(url string) string { stripped := url if strings.HasPrefix(url, "http://") { stripped = strings.Replace(url, "http://", "", 1) } else if strings.HasPrefix(url, "https://") { stripped = strings.Replace(url, "https://", "", 1) } nameParts := strings.SplitN(stripped, "/", 2) return nameParts[0] } func (c *fileStore) Get(serverAddress string) (types.AuthConfig, error)
{ authConfig, ok := c.file.AuthConfigs[serverAddress] if !ok { for registry, ac := range c.file.AuthConfigs { if serverAddress == convertToHostname(registry) { return ac, nil } } authConfig = types.AuthConfig{} } return authConfig, nil }
package windows import ( "github.com/docker/libnetwork/driverapi" "github.com/docker/libnetwork/types" ) const networkType = "windows" type driver struct{} func Init(dc driverapi.DriverCallback) error { c := driverapi.Capability{ Scope: driverapi.LocalScope, } return dc.RegisterDriver(networkType, &driver{}, c) } func (d *driver) Config(option map[string]interface{}) error { return nil } func (d *driver) CreateNetwork(id types.UUID, option map[string]interface{}) error { return nil } func (d *driver) DeleteNetwork(nid types.UUID) error { return nil } func (d *driver) CreateEndpoint(nid, eid types.UUID, epInfo driverapi.EndpointInfo, epOptions map[string]interface{}) error { return nil } func (d *driver) DeleteEndpoint(nid, eid types.UUID) error { return nil } func (d *driver) EndpointOperInfo(nid, eid types.UUID) (map[string]interface{}, error) { return make(map[string]interface{}, 0), nil } func (d *driver) Join(nid, eid types.UUID, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error { return nil } func (d *driver) Type() string { return networkType } func (d *driver) Leave(nid, eid types.UUID) error
{ return nil }
package cf import ( "fmt" "io/ioutil" "os" "time" ginkgoconfig "github.com/onsi/ginkgo/config" "github.com/cloudfoundry-incubator/cf-test-helpers/runner" ) var AsUser = func(userContext UserContext, timeout time.Duration, actions func()) { originalCfHomeDir, currentCfHomeDir := InitiateUserContext(userContext, timeout) defer func() { RestoreUserContext(userContext, timeout, originalCfHomeDir, currentCfHomeDir) }() TargetSpace(userContext, timeout) actions() } func TargetSpace(userContext UserContext, timeout time.Duration) { if userContext.Org != "" { if userContext.Space != "" { runner.NewCmdRunner(Cf("target", "-o", userContext.Org, "-s", userContext.Space), timeout).Run() } else { runner.NewCmdRunner(Cf("target", "-o", userContext.Org), timeout).Run() } } } func RestoreUserContext(_ UserContext, timeout time.Duration, originalCfHomeDir, currentCfHomeDir string) { runner.NewCmdRunner(Cf("logout"), timeout).Run() os.Setenv("CF_HOME", originalCfHomeDir) os.RemoveAll(currentCfHomeDir) } func InitiateUserContext(userContext UserContext, timeout time.Duration) (originalCfHomeDir, currentCfHomeDir string)
{ originalCfHomeDir = os.Getenv("CF_HOME") currentCfHomeDir, err := ioutil.TempDir("", fmt.Sprintf("cf_home_%d", ginkgoconfig.GinkgoConfig.ParallelNode)) if err != nil { panic("Error: could not create temporary home directory: " + err.Error()) } os.Setenv("CF_HOME", currentCfHomeDir) cfSetApiArgs := []string{"api", userContext.ApiUrl} if userContext.SkipSSLValidation { cfSetApiArgs = append(cfSetApiArgs, "--skip-ssl-validation") } runner.NewCmdRunner(Cf(cfSetApiArgs...), timeout).Run() runner.NewCmdRunner(Cf("auth", userContext.Username, userContext.Password), timeout).Run() return }
package cpumanager import ( "k8s.io/api/core/v1" "k8s.io/klog" "k8s.io/kubernetes/pkg/kubelet/cm/cpumanager/state" "k8s.io/kubernetes/pkg/kubelet/cm/topologymanager" ) type nonePolicy struct{} var _ Policy = &nonePolicy{} const PolicyNone policyName = "none" func NewNonePolicy() Policy { return &nonePolicy{} } func (p *nonePolicy) Start(s state.State) { klog.Info("[cpumanager] none policy: Start") } func (p *nonePolicy) AddContainer(s state.State, pod *v1.Pod, container *v1.Container) error { return nil } func (p *nonePolicy) RemoveContainer(s state.State, podUID string, containerName string) error { return nil } func (p *nonePolicy) GetTopologyHints(s state.State, pod v1.Pod, container v1.Container) map[string][]topologymanager.TopologyHint { return nil } func (p *nonePolicy) Name() string
{ return string(PolicyNone) }
package config import ( "fmt" "strconv" "strings" ) var ( Current = Version{ Major: 0, Minor: 15, Patch: 1, } First = Version{ 0, 10, 4, } ) type Version struct { Major int `json:"major"` Minor int `json:"minor"` Patch int `json:"patch"` } func (v Version) String() string { return fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch) } func (v Version) Greater(x Version) bool { if v.Major > x.Major { return true } if v.Major == x.Major { if v.Minor > x.Minor { return true } if v.Minor == x.Minor { if v.Patch > x.Patch { return true } return false } return false } return false } func VersionFromString(s string) Version
{ vs := strings.Split(s, ".") if len(vs) < 3 { return First } toInt := func(s string) int { i, err := strconv.Atoi(s) if err != nil { return 0 } return i } return Version{toInt(vs[0]), toInt(vs[1]), toInt(vs[2])} }