input
stringlengths
24
2.11k
output
stringlengths
7
948
package internalversion import ( "k8s.io/apimachinery/pkg/api/errors" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" authentication "k8s.io/kubernetes/pkg/apis/authentication" ) type TokenReviewLister interface { List(selector labels.Selector) (ret []*...
{ key := &authentication.TokenReview{ObjectMeta: v1.ObjectMeta{Name: name}} obj, exists, err := s.indexer.Get(key) if err != nil { return nil, err } if !exists { return nil, errors.NewNotFound(authentication.Resource("tokenreview"), name) } return obj.(*authentication.TokenReview), nil }
package ivona_test import ( "log" ivona "github.com/jpadilla/ivona-go" ) func ExampleIvona_ListVoices() { client := ivona.New("IVONA_ACCESS_KEY", "IVONA_SECRET_KEY") r, err := client.ListVoices(ivona.Voice{}) if err != nil { log.Fatal(err) } log.Printf("%v\n", len(r.Voices)) } func ExampleIvona_CreateS...
{ client := ivona.New("IVONA_ACCESS_KEY", "IVONA_SECRET_KEY") options := ivona.NewSpeechOptions("Hello World") r, err := client.CreateSpeech(options) if err != nil { log.Fatal(err) } log.Printf("%v\n", len(r.Audio)) log.Printf("%v\n", r.ContentType) log.Printf("%v\n", r.RequestID) }
package resolvers import ( "context" "time" "github.com/emwalker/digraph/cmd/frontend/loaders" "github.com/emwalker/digraph/cmd/frontend/models" "github.com/volatiletech/sqlboiler/queries/qm" ) type organizationResolver struct { *Resolver } func getOrganizationLoader(ctx context.Context) *loaders.Organization...
{ repo, err := org.Repositories(qm.Where("system")).One(ctx, r.DB) if err != nil { return nil, err } return repo, nil }
package nacos import ( "context" "github.com/asim/go-micro/v3/config/source" "github.com/nacos-group/nacos-sdk-go/v2/common/constant" ) type addressKey struct{} type configKey struct{} type groupKey struct{} type dataIdKey struct{} type encoderKey struct{} func WithClientConfig(cc constant.ClientConfig) sour...
{ return func(o *source.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, addressKey{}, addrs) } }
package util import ( "github.com/go-kit/kit/log" "net/http" "path" "strings" ) type catchAllFileHandler struct { FS http.FileSystem InnerHandler http.Handler serveInstead string Logger log.Logger } func (f *catchAllFileHandler) ServeFallback(w http.ResponseWriter, r *http.Request) { file,...
{ return &catchAllFileHandler{ FS: root, InnerHandler: http.FileServer(root), serveInstead: serveInstead, Logger: logger, } }
package sardata import ( "io" "github.com/luci/luci-go/common/errors" ) const Magic = "SAR" const Version byte = 1 var magicVer []byte func init() { magicVer = []byte(Magic + string(Version)) } func WriteMagic(w io.Writer) error { _, err := w.Write(magicVer) return err } func ReadMagic(r io.Reader) ...
{ buf := make([]byte, 4) if _, err = io.ReadFull(r, buf); err != nil { return } sBuf := string(buf[:3]) if Magic != sBuf { err = errors.Reason("bad magic: %(magic)q").D("magic", sBuf).Err() return } version = buf[3] if version > Version { err = errors.Reason("bad version: %(ver)d > %(ours)d"). D("v...
package core import ( "github.com/oracle/oci-go-sdk/v46/common" "net/http" ) type CreateNatGatewayRequest struct { CreateNatGatewayDetails `contributesTo:"body"` OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"` OpcRequestId *string `mandatory:"false" contributesTo:"...
{ return common.PointerString(response) }
package util import ( "golang.org/x/net/context" "testing" ) func TestHeartbeatUtil(t *testing.T) { defer func() { if r := recover(); r != nil { t.Fatalf("TestHeartbeatUtil failed") } }() HeartbeatUtil(context.Background(), "", "", "") } func TestKeepAliveLease(t *testing.T)
{ _, err := KeepAliveLease(context.Background(), "", "", "", -1) if err == nil { t.Fatalf("KeepAliveLease -1 failed") } _, err = KeepAliveLease(context.Background(), "", "", "", 0) if err != nil { t.Fatalf("KeepAliveLease failed") } }
package messages import ( "bytes" "message-delivery-system/src/utils" ) type ListResponse struct { List []uint64 Receiver uint64 } func NewListResponse(data []byte) ListResponse { buf := bytes.NewReader(data) list, _ := utils.ByteArrayToUint64List(buf, data) return ListResponse{List:list} } func (l Lis...
{ return ListResponseMessage }
package migrations_test import ( "io/ioutil" "testing" ) func assertCorrectFileContents(t *testing.T, filePath string, expectedFileContents string) { fileContents, err := ioutil.ReadFile(filePath) if err != nil { t.Fatal(err) } if string(fileContents) != expectedFileContents { t.Fatal("Incorrect file cont...
{ repoVer, err := ioutil.ReadFile(verPath) if err != nil { t.Fatal(err) } if string(repoVer) != expectedRepoVer { t.Fatal("Failed to write new repo version") } }
package main import ( "fmt" "html/template" "log" "net/http" "github.com/gorilla/websocket" ) var upgrader = websocket.Upgrader{} func Echo(w http.ResponseWriter, r *http.Request) { ws, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Print("upgrade:", err) return } fmt.Println("start websocket!"...
{ t, _ := template.ParseFiles("index.html") t.Execute(w, nil) }
package http import ( "net" "time" ) type TimeoutConn struct { QuirkConn readTimeout time.Duration writeTimeout time.Duration } func (c *TimeoutConn) setReadTimeout() { if c.readTimeout != 0 && c.canSetReadDeadline() { c.SetReadDeadline(time.Now().UTC().Add(c.readTimeout)) } } func (c *TimeoutConn) Re...
{ if c.writeTimeout != 0 { c.SetWriteDeadline(time.Now().UTC().Add(c.writeTimeout)) } }
package chipmunk import ( "github.com/Dethrail/chipmunk/transform" "github.com/Dethrail/chipmunk/vect" "math" ) const ( RadianConst = math.Pi / 180 DegreeConst = 180 / math.Pi ) type Group int type Layer int type Shape struct { DefaultHash ShapeClass Body *Body BB AABB IsSensor bool e vect.Float u v...
{ return shape.Body.v, shape.velocityIndexed }
package glib import "C" import "unsafe" type IActionMap interface { Native() uintptr LookupAction(actionName string) *Action AddAction(action IAction) RemoveAction(actionName string) } type ActionMap struct { *Object } func (v *ActionMap) native() *C.GActionMap { if v == nil || v.GObject == nil { ...
{ return &ActionMap{obj} }
package core import ( "sync" "barista.run/bar" l "barista.run/logging" "barista.run/sink" ) type ModuleSet struct { modules []*Module updateCh chan int outputs []bar.Segments outputsMu sync.RWMutex } func NewModuleSet(modules []bar.Module) *ModuleSet { set := &ModuleSet{ modules: make([]*Module...
{ m.outputsMu.RLock() defer m.outputsMu.RUnlock() cp := make([]bar.Segments, len(m.outputs)) copy(cp, m.outputs) return cp }
package main type Move struct { Src Point Dest Point } var EmptyMove = Move{Point{0, 0}, Point{0, 0}} func NewMove(src Point, dest Point) Move { s, d := src, dest if s.X > d.X { s.X, d.X = d.X, s.X } if s.Y > d.Y { s.Y, d.Y = d.Y, s.Y } return Move{src, dest} } func (m Move) Valid(table Table) bool ...
{ return m.Src.String() + ">" + m.Dest.String() }
package cemi type Priority uint8 const ( PrioSystem Priority = 0 PrioNormal Priority = 1 PrioUrgent Priority = 2 PrioLow Priority = 3 ) type ControlField1 uint8 const ( Control1StdFrame ControlField1 = 1 << 7 Control1NoRepeat ControlField1 = 1 << 5 Control1NoSysBroadcast ControlField1 = 1 << 4 Contr...
{ return ControlField1(prio&3) << 2 }
package vm import ( "math/big" "github.com/burnoutcoin/go-burnout/common" ) type destinations map[common.Hash][]byte func (d destinations) has(codehash common.Hash, code []byte, dest *big.Int) bool { udest := dest.Uint64() if dest.BitLen() >= 63 || udest >= uint64(len(code)) { return false } m, analyse...
{ m := make([]byte, len(code)/8+1) for pc := uint64(0); pc < uint64(len(code)); pc++ { op := OpCode(code[pc]) if op == JUMPDEST { m[pc/8] |= 1 << (pc % 8) } else if op >= PUSH1 && op <= PUSH32 { a := uint64(op) - uint64(PUSH1) + 1 pc += a } } return m }
package security import ( "net/http" "github.com/goharbor/harbor/src/common/security" "github.com/goharbor/harbor/src/lib" "github.com/goharbor/harbor/src/lib/config" "github.com/goharbor/harbor/src/lib/log" "github.com/goharbor/harbor/src/server/middleware" ) var ( generators = []generator{ &secret{}, &o...
{ return middleware.New(func(w http.ResponseWriter, r *http.Request, next http.Handler) { log := log.G(r.Context()) mode, err := config.AuthMode(r.Context()) if err == nil { r = r.WithContext(lib.WithAuthMode(r.Context(), mode)) } else { log.Warningf("failed to get auth mode: %v", err) } for _, gener...
package provider import ( "strings" ) type DomainFilter struct { filters []string exclude []string } func NewDomainFilterWithExclusions(domainFilters []string, excludeDomains []string) DomainFilter { return DomainFilter{prepareFilters(domainFilters), prepareFilters(excludeDomains)} } func NewDomainFilter(...
{ fs := make([]string, len(filters)) for i, domain := range filters { fs[i] = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(domain), ".")) } return fs }
package soap import ( "github.com/vmware/govmomi/vim25/types" "github.com/vmware/govmomi/vim25/xml" ) type Envelope struct { XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Envelope"` Header *Header `xml:",omitempty"` Body interface{} } type Header struct { XMLName xml.Name `xml:"http://s...
{ return f.Detail.Fault }
package loads import "jvmgo/ch09/instructions/base" import "jvmgo/ch09/rtda" type ILOAD struct{ base.Index8Instruction } type ILOAD_0 struct{ base.NoOperandsInstruction } func (self *ILOAD_0) Execute(frame *rtda.Frame) { _iload(frame, 0) } type ILOAD_1 struct{ base.NoOperandsInstruction } func (self *ILOAD_1)...
{ _iload(frame, self.Index) }
package rbac import ( v3 "github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3" typesrbacv1 "github.com/rancher/rancher/pkg/generated/norman/rbac.authorization.k8s.io/v1" rbacv1 "k8s.io/api/rbac/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k...
{ if key == "" || obj == nil { return nil, nil } if owner, ok := obj.Annotations[clusterRoleOwner]; ok { _, err := c.roleTemplateLister.Get("", owner) if err != nil { if apierrors.IsNotFound(err) { return obj, c.clusterRoles.Delete(obj.Name, &metav1.DeleteOptions{}) } return obj, err } } ret...
package token import ( "strings" "github.com/carlcui/expressive/locator" ) type Token struct { TokenType Type Raw string Locator locator.Locator } func (tok *Token) String() string { return tok.TokenType.String() + ": " + tok.Raw } func (tok *Token) GetLocation() string { if tok.Locator == nil { ...
{ if tokenType, isKeyword := keywords[reading]; isKeyword { return &Token{TokenType: tokenType, Raw: reading} } return nil }
package glacier import ( "fmt" "net/http" "net/url" "github.com/rdwilliamson/aws" ) type Connection struct { Client *http.Client Signature *aws.Signature } func (c *Connection) client() *http.Client { if c.Client == nil { return http.DefaultClient } return c.Client } func (c *Connection) vault(vault ...
{ return "https://" + c.Signature.Region.Glacier + "/-/policies/" + policy }
package mysql import ( _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" "github.com/stellar/federation/db" ) type MysqlDriver struct { database *sqlx.DB } func (d *MysqlDriver) GetByStellarAddress(name, query string) (*db.FederationRecord, error) { var record db.FederationRecord err := d.database...
{ d.database, err = sqlx.Connect("mysql", url) return }
package test import ( "github.com/tidepool-org/platform/data/types/bolus/combination" dataTypesBolusTest "github.com/tidepool-org/platform/data/types/bolus/test" "github.com/tidepool-org/platform/pointer" "github.com/tidepool-org/platform/test" ) func NewCombination() *combination.Combination { datum := combinat...
{ if datum == nil { return nil } clone := combination.New() clone.Duration = pointer.CloneInt(datum.Duration) clone.DurationExpected = pointer.CloneInt(datum.DurationExpected) clone.Extended = pointer.CloneFloat64(datum.Extended) clone.ExtendedExpected = pointer.CloneFloat64(datum.ExtendedExpected) clone.Bolu...
package proxy import ( "bytes" "net/http" ) type Response interface { Status() int Header() http.Header Body() []byte } type WriterRecorder struct { http.ResponseWriter status int body bytes.Buffer } func (w *WriterRecorder) WriteHeader(status int) { w.ResponseWriter.WriteHeader(status) w.status = statu...
{ return w.body.Bytes() }
package unifi import ( "strconv" ) type fuzzyFloat float64 func (f *fuzzyFloat) UnmarshalJSON(b []byte) error
{ s := string(b) if len(s) == 0 { return nil } if s[0] == '"' && s[len(s)-1] == '"' { s = s[1 : len(s)-1] } if s == "" || s == "null" { return nil } v, err := strconv.ParseFloat(s, 64) if err != nil { return err } *f = fuzzyFloat(v) return nil }
package comment import ( "time" "github.com/google/go-github/github" ) type Matcher interface { Match(comment *github.IssueComment) bool } type CreatedAfter time.Time func (c CreatedAfter) Match(comment *github.IssueComment) bool { if comment == nil || comment.CreatedAt == nil { return false } return co...
{ if comment == nil || comment.CreatedAt == nil { return false } return comment.CreatedAt.Before(time.Time(c)) }
package macaron import ( "net/http" "reflect" "gitea.com/macaron/inject" ) type ReturnHandler func(*Context, []reflect.Value) func canDeref(val reflect.Value) bool { return val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr } func isByteSlice(val reflect.Value) bool { return val.Kind() == refl...
{ _, ok := val.Interface().(error) return ok }
package graphql import ( "net/http" middleware "github.com/go-openapi/runtime/middleware" models "github.com/semi-technologies/weaviate/entities/models" ) type GraphqlBatchHandlerFunc func(GraphqlBatchParams, *models.Principal) middleware.Responder func (fn GraphqlBatchHandlerFunc) Handle(params GraphqlBat...
{ route, rCtx, _ := o.Context.RouteInfo(r) if rCtx != nil { r = rCtx } var Params = NewGraphqlBatchParams() uprinc, aCtx, err := o.Context.Authorize(r, route) if err != nil { o.Context.Respond(rw, r, route.Produces, route, err) return } if aCtx != nil { r = aCtx } var principal *models.Principal if ...
package sflib import ( "fmt" ) type APIStatusResponse struct { OK bool `json:"ok"` Error string `json:"error"` } func (asr *APIStatusResponse) CheckAPIStatus() error { if (asr.OK != true) || (asr.Error != "") { return APIFailureError{asr.Error} } return nil } type APIFailureError struct { s st...
{ return fmt.Sprintf("api returned error: %s", afe.s) }
package opt import ( "encoding/json" "reflect" ) type DisableTypoToleranceOnAttributesOption struct { value []string } func DisableTypoToleranceOnAttributes(v ...string) *DisableTypoToleranceOnAttributesOption { return &DisableTypoToleranceOnAttributesOption{v} } func (o DisableTypoToleranceOnAttributes...
{ if o == nil { return []string{} } return o.value }
package upgrader import ( "github.com/juju/juju/agent/tools" "github.com/juju/juju/version" ) type UpgradeReadyError struct { AgentName string OldTools version.Binary NewTools version.Binary DataDir string } func (e *UpgradeReadyError) ChangeAgentTools() error { agentTools, err := tools.ChangeAgent...
{ return "must restart: an agent upgrade is available" }
package sendgrid import ( "fmt" "log" "errors" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/terraform" ) func Provider() terraform.ResourceProvider { return &schema.Provider{ Schema: map[string]*schema.Schema{ "api_key": &schema.Schema{ Type: schema.TypeString,...
{ config := Config{ APIKey: d.Get("api_key").(string), } log.Println("[INFO] Initializing Sendgrid client") client := config.Client() fmt.Println("Validate template") ok, err := client.Validate() if err != nil { return client, err } if ok == false { return client, errors.New(`No valid credential sour...
package main import ( "log" "net/http" "gopkg.in/pivo.v2/ws" ) const websocketChatUri = `/` type websocket struct { conn *ws.Conn } func (ws *websocket) OnClose(why error) error { chat.hub.Leave(ws.conn) return nil } func (ws *websocket) OnTextRead(text string) error { chat.pub <- ws.conn.TextMessage(for...
{ return ErrProtocolViolation }
package buckettree import ( "testing" "github.com/TarantulaTechnology/fabric/core/ledger/testutil" ) func TestDataKeyGetBucketKey(t *testing.T) { conf = newConfig(26, 3, fnvHash) newDataKey("chaincodeID1", "key1").getBucketKey() newDataKey("chaincodeID1", "key2").getBucketKey() newDataKey("chaincodeID2", "ke...
{ conf = newConfig(26, 3, fnvHash) dataKey := newDataKey("chaincodeID", "key") encodedBytes := dataKey.getEncodedBytes() dataKeyFromEncodedBytes := newDataKeyFromEncodedBytes(encodedBytes) testutil.AssertEquals(t, dataKey, dataKeyFromEncodedBytes) }
package cli import ( "fmt" "io/ioutil" "os" "path" "strconv" ) func CheckError(err error) { if err != nil { fmt.Println(err) os.Exit(1) } } func CheckFatalError(err error) { if err != nil { CheckError(fmt.Errorf("Fatal error: %v", err)) } } func FileExists(path string) bool { _, err := os.Stat(pa...
{ os.Remove(pidfile) os.Exit(code) }
package service import ( "context" "time" upgrpc "go-common/app/service/main/up/api/v1" "go-common/app/service/main/up/model/data" xtime "go-common/library/time" ) func (s *Service) UpBaseStats(c context.Context, req *upgrpc.UpStatReq) (res *upgrpc.UpBaseStatReply, err error)
{ res = new(upgrpc.UpBaseStatReply) if req.Date.Time().IsZero() { req.Date = xtime.Time(time.Now().Add(-12*time.Hour).AddDate(0, 0, -1).Unix()) } var stat *data.UpBaseStat if stat, err = s.Data.BaseUpStat(c, req.Mid, req.Date.Time().Format("20060102")); err != nil { return } stat.CopyToReply(res) return }
package diffsquares func SquareOfSums(n int) int { s := int(n) s *= s + 1 s /= 2 return s * s } func Difference(n int) int { return SquareOfSums(n) - SumOfSquares(n) } func SumOfSquares(n int) int
{ s := int(n) s = 2*s*s*s + 3*s*s + s s /= 6 return s }
package module import ( "fmt" "os" "syscall" ) func inode(path string) (uint64, error)
{ stat, err := os.Stat(path) if err != nil { return 0, err } if st, ok := stat.Sys().(*syscall.Stat_t); ok { return st.Ino, nil } return 0, fmt.Errorf("could not determine file inode") }
package gutil import ( "bufio" "os" "strings" ) func NewReadForString(str string) *bufio.Reader { return bufio.NewReader(strings.NewReader(str)) } func ReadPath(path string) []string { if file, err := os.Open(path); CheckSucceed(err) { var strs []string buff := bufio.NewReader(file) for { if str, ...
{ line, _, err := red.ReadLine() if err != nil { return "", false } return string(line), true }
package container var _ LogEntry = (*logEntry)(nil) func NewLogEntry(container, line string) logEntry { return logEntry{ container: container, line: line, } } type logEntry struct { line string container string } func (l logEntry) Line() string { return l.line } func (l logEntry) Container() s...
{ return l.container }
package ethutil import "fmt" type StorageSize float64 func (self StorageSize) String() string
{ if self > 1000000 { return fmt.Sprintf("%.2f mB", self/1000000) } else if self > 1000 { return fmt.Sprintf("%.2f kB", self/1000) } else { return fmt.Sprintf("%.2f B", self) } }
package github import ( . "github.com/ErintLabs/trellohub/genapi" "log" ) type Label struct { Name string `json:"name"` } type GitUser struct { Name string `json:"login"` } func (issue *Issue) SetLabels(lbls []Label) { lst := make([]string, len(lbls)) for i, v := range lbls { lst[i] =...
{ log.Printf("Adding user %s to %s", user, issue.String()) payload := userAssignRequest{ []string{ user } } GenPOSTJSON(issue.github, issue.ApiURL() + "/assignees", nil, &payload) }
package db import ( "database/sql" _ "github.com/go-sql-driver/mysql" ) type DB struct { DriverName string DriverSourceName string DataBase *sql.DB } func (this *DB) Open() (err error) { this.DataBase, err = sql.Open(this.DriverName, this.DriverSourceName) if err != nil { return err } re...
{ return &DB{ DriverName: drivername, DriverSourceName: driversourcename, } }
package protocol var ( Version13HelloMagic uint32 = 0x9F79BC40 ) type Version13HelloMessage struct { DeviceName string ClientName string ClientVersion string } func (m Version13HelloMessage) Magic() uint32 { return Version13HelloMagic } func (m Version13HelloMessage) Marshal() ([]byte, error)
{ return m.MarshalXDR() }
package wire import ( "fmt" "io" ) type MsgPong struct { Nonce uint64 } func (msg *MsgPong) BtcEncode(w io.Writer, pver uint32) error { if pver <= BIP0031Version { str := fmt.Sprintf("pong message invalid for protocol "+ "version %d", pver) return messageError("MsgPong.BtcEncode", str) } ret...
{ if pver <= BIP0031Version { str := fmt.Sprintf("pong message invalid for protocol "+ "version %d", pver) return messageError("MsgPong.BtcDecode", str) } return readElement(r, &msg.Nonce) }
package model import ( "testing" ) func TestConsumerMessage(t *testing.T)
{ t.SkipNow() }
package events import ( "io" "time" "github.com/gravitational/teleport/lib/session" ) type DiscardAuditLog struct { } func (d *DiscardAuditLog) Close() error { return nil } func (d *DiscardAuditLog) EmitAuditEvent(eventType string, fields EventFields) error { return nil } func (d *DiscardAuditLog) PostSessi...
{ return nil }
package limiter type SimpleLimiter chan struct{} func (l SimpleLimiter) Enter() { l <- struct{}{} } func NewSimpleLimiter(l int) SimpleLimiter { return make(chan struct{}, l) } func (l SimpleLimiter) Leave()
{ <-l }
package dosingdecision import ( "github.com/tidepool-org/platform/structure" ) const ( RecommendedBasalDurationMaximum = 86400000 RecommendedBasalDurationMinimum = 0 RecommendedBasalRateMaximum = 100 RecommendedBasalRateMinimum = 0 ) type RecommendedBasal struct { Rate *float64 `json:"rate,omitempt...
{ r.Rate = parser.Float64("rate") r.Duration = parser.Int("duration") }
package render import ( "github.com/gin-gonic/gin" ) func Error(c *gin.Context, msg string)
{ String(c, msg, 400) }
package couchdb import ( "encoding/json" "net/http" kivik "github.com/go-kivik/kivik/v3" ) func encodeKey(i interface{}) (string, error) { if raw, ok := i.(json.RawMessage); ok { return string(raw), nil } raw, err := json.Marshal(i) if err != nil { err = &kivik.Error{HTTPStatus: http.StatusBadRequest, Er...
{ for _, key := range jsonKeys { if v, ok := opts[key]; ok { new, err := encodeKey(v) if err != nil { return err } opts[key] = new } } return nil }
package model type Weight struct { time int requirements map[*Reward]int } func (weight *Weight) Time() int { return weight.time } func (weight *Weight) Requirements() map[*Reward]int { return weight.requirements } func (weight *Weight) AddRequirement(reward *Reward, quantity int) { weight.requirem...
{ return a[i].Time() < a[j].Time() }
package tests import ( "path/filepath" "testing" ) func TestTransactions(t *testing.T) { err := RunTransactionTests(filepath.Join(transactionTestDir, "ttTransactionTest.json"), TransSkipTests) if err != nil { t.Fatal(err) } } func TestWrongRLPTransactions(t *testing.T) { err := RunTransactionTests(filepath.J...
{ err := RunTransactionTests(filepath.Join(transactionTestDir, "tt10mbDataField.json"), TransSkipTests) if err != nil { t.Fatal(err) } }
package entrapped import ( "github.com/SKatiyar/entrapped/Godeps/_workspace/src/github.com/julienschmidt/httprouter" "net/http" ) const ( size int = 7 numBombs int = 10 lifes int = 5 numBonusLifes int = 2 ) func addPlayer(rw http.ResponseWriter, req *http.Request, params httprouter.Para...
{ if len(addr) == 0 { addr = ":7000" } go ch.run() router := httprouter.New() router.GET("/", home) router.ServeFiles("/statics/*filepath", http.Dir("client/dist/statics")) router.GET("/players/:id", addPlayer) listenErr := http.ListenAndServe(addr, router) if listenErr != nil { logger.Println(listenE...
package travel import ( "os" "github.com/akerl/speculate/v2/creds" ) func clearEnvironment() error { for varName := range creds.Translations["envvar"] { logger.InfoMsgf("Unsetting env var: %s", varName) err := os.Unsetenv(varName) if err != nil { return err } } return nil } func stringInSlice(list [...
{ var res []string for _, item := range a { if stringInSlice(b, item) { res = append(res, item) } } return res }
package testing import ( "github.com/markdaws/gohome/pkg/cmd" "github.com/markdaws/gohome/pkg/gohome" ) type extension struct { gohome.NullExtension } func (e *extension) BuilderForDevice(sys *gohome.System, d *gohome.Device) cmd.Builder { switch d.ModelNumber { case "testing.hardware": return &cmdBuilder{M...
{ return "testing" }
package core import ( "fmt" ) type BuiltInClass struct { name Instance supers []Class slots []Instance } func NewBuiltInClass(name string, super Class, slots ...string) Class { slotNames := []Instance{} for _, slot := range slots { slotNames = append(slotNames, NewSymbol(slot)) } return BuiltInClass{New...
{ return fmt.Sprint(p.name) }
package main import ( "fmt" "github.com/robfig/cron" ) type Sync struct{} func (s *Sync) Help() string { return "glr sync Help" } func (s *Sync) Synopsis() string { return "Synchronize local git repository with remote at once" } type status struct { c *cron.Cron repositories []string schedules...
{ _, err := SyncRepository() if err != nil { return 1 } return 0 }
package storageos import ( "context" "encoding/json" "fmt" "net/http" "github.com/storageos/go-api/types" ) var ( HealthAPIPrefix = "health" ) func (c *Client) CPHealth(ctx context.Context, hostname string) (*types.CPHealthStatus, error) { url := fmt.Sprintf("http://%s:%s/v1/%s", hostname, DefaultPort, Hea...
{ url := fmt.Sprintf("http://%s:%s/v1/%s", hostname, DataplaneHealthPort, HealthAPIPrefix) req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } req.Header.Set("User-Agent", userAgent) if c.username != "" && c.secret != "" { req.SetBasicAuth(c.username, c.secret) } resp, err := c...
package api import ( "io" "github.com/dghubble/sling" ) const SdkDebugKey = "SdkDebug" type Client struct { sling.Doer *sling.Sling } type ApiKeyClientOption func(*ApiKeyClientOptions) type ApiKeyClientOptions struct { InsecureSkipVerify bool InsecureUsePlaintext bool EnableRoot bool Product string ...
{ return func(o *ApiKeyClientOptions) { o.DebugWriter = w } }
package memcachep import ( "fmt" "os" "runtime" "strconv" ) type Stats map[string]fmt.Stringer type FuncStat struct { Callable func() string } func (f *FuncStat) String() string { return f.Callable() } type StaticStat struct { Value string } func (s *StaticStat) String() string { return s.Value } type...
{ s := make(Stats) s["pid"] = &StaticStat{strconv.Itoa(os.Getpid())} s["version"] = &StaticStat{VERSION} s["golang"] = &StaticStat{runtime.Version()} s["goroutines"] = &FuncStat{func() string { return strconv.Itoa(runtime.NumGoroutine()) }} s["cpu_num"] = &StaticStat{strconv.Itoa(runtime.NumCPU())} s["total_conn...
package http import ( "context" "github.com/go-kit/kit/endpoint" "github.com/kryptn/modulario/proto" ) func MakeLoginEndpoint(svc HttpService) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (interface{}, error) { req := request.(proto.LoginRequest) resp, err := svc.Login(ctx, req) ...
{ return func(ctx context.Context, request interface{}) (interface{}, error) { req := request.(proto.ViewPostRequest) return svc.ViewPost(ctx, req) } }
package intsort type Uints []uint func (s Uints) Len() int { return len(s) } func (s Uints) Less(i int, j int) bool { return s[i] < s[j] } func (s Uints) Swap(i int, j int)
{ s[i], s[j] = s[j], s[i] }
package bunyan import "fmt" type Logger struct { sink Sink record Record } func NewLogger(target Sink) *Logger { return &Logger{target, NewRecord()} } func (l *Logger) Write(record Record) error { record.TemplateMerge(l.record) return l.sink.Write(record) } func (l *Logger) Include(info Info) Log { r...
{ l.send(FATAL, msg, args...) }
package armcosmos_test import ( "context" "log" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cosmos/armcosmos" ) func ExampleCollectionPartitionClient_ListUsages() { cred, err := azidentity.NewDef...
{ cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client := armcosmos.NewCollectionPartitionClient("<subscription-id>", cred, nil) res, err := client.ListMetrics(ctx, "<resource-group-name>", "<account-...
package keyseq import ( "testing" ) func checkTrieNode(t *testing.T, n Node, k Key, value int) { if n == nil { t.Fatal("TrieNode is null") } if l := n.Label(); l != k { t.Errorf("TrieNode.Label() expected:'%c' actual:'%c'", k, l) } if v := n.Value().(int); v != value { t.Errorf("TrieNode.Value() expected:...
{ trie := NewTrie() for i := 1; i <= 5; i++ { trie.Put(KeyList{Key{0, 0, rune(i)}}, 111*i) } nodes := Children(trie.Root()) for i := 0; i < 5; i++ { checkTrieNode(t, nodes[i], Key{0, 0, rune(i + 1)}, 111*(i+1)) } if s := trie.Size(); s != 5 { t.Errorf("trie.Size() returns not 5: %d", s) } }
package stopwatch import ( "testing" "time" ) func TestSyncStopwatch_Mark(t *testing.T)
{ s := NewSync() s.Start() time.Sleep(time.Millisecond * 100) s.Mark("sleep1") time.Sleep(time.Millisecond * 100) s.Mark("sleep2") s.Stop() println(s.Report()) }
package core import ( "github.com/oracle/oci-go-sdk/common" "net/http" ) type CreateBootVolumeRequest struct { CreateBootVolumeDetails `contributesTo:"body"` OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"` OpcRequestId *string `mandatory:"false" contributesTo:"header" ...
{ return request.RequestMetadata.RetryPolicy }
package realtime import ( "io" ) type Reader interface { io.Reader realtime() } func NewReader(input io.Reader, rthandler func(Message)) Reader { if rthandler == nil { return &discardReader{input} } return &reader{input, rthandler} } type reader struct { input io.Reader handler func(Message) ...
{ var bf = make([]byte, 1) for { if n == len(target) { return } _, err = r.input.Read(bf) if err != nil { return } if bf[0] < 0xF8 { target[n] = bf[0] n++ continue } if m := dispatch(bf[0]); m != nil { r.handler(m) } } }
package sml_test import ( "encoding/xml" "testing" "baliance.com/gooxml/schema/soo/sml" ) func TestCT_TextFieldMarshalUnmarshal(t *testing.T) { v := sml.NewCT_TextField() buf, _ := xml.Marshal(v) v2 := sml.NewCT_TextField() xml.Unmarshal(buf, v2) } 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) } }
package common import ( "encoding/json" "my/util" "net/http" "regexp" "sso/user" ) func Myinfo(res http.ResponseWriter, req *http.Request) { callback := req.FormValue("cb") var sweet map[string]interface{} = make(map[string]interface{}) sweet["state"] = 0 reg := regexp.MustCompile(`"|'|<|\s`) callback = r...
{ cookie := req.URL.Query().Get("token") if cookie == "" { return false, nil } userA := byToken(cookie) if userA == nil { return false, nil } if userA.Id == 0 { return false, nil } return true, userA }
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"` Request...
{ return response.RawResponse }
package augeas import "C" import ( "fmt" ) type ErrorCode int const ( CouldNotInitialize ErrorCode = -2 NoMatch = -1 NoError = 0 ENOMEM EINTERNAL EPATHX ENOMATCH EMMATCH ESYNTAX ENOLENS EMXFM ENOSPAN EMVDESC ECMDRUN EBADARG ) type Error struct { Code ErrorCo...
{ return C.GoString(C.aug_error_minor_message(a.handle)) }
package zipkin import ( "github.com/jaegertracing/jaeger/thrift-gen/zipkincore" ) func IsServerCore(anno string) bool { return anno == zipkincore.SERVER_SEND || anno == zipkincore.SERVER_RECV } func IsClientCore(anno string) bool { return anno == zipkincore.CLIENT_SEND || anno == zipkincore.CLIENT_RECV } func...
{ for _, anno := range span.Annotations { endpoint := anno.GetHost() if endpoint == nil { continue } if IsCore(anno.Value) && endpoint.GetServiceName() != "" { return endpoint.GetServiceName() } } return "" }
package local import ( "os" "path/filepath" "strings" "syscall" "time" "github.com/tiborvass/docker/errdefs" "github.com/pkg/errors" ) type optsConfig struct{} func (r *Root) scopedPath(realPath string) bool { if strings.HasPrefix(realPath, filepath.Join(r.scope, volumesPathName)) && realPath != filepath...
{ if len(opts) > 0 { return errdefs.InvalidParameter(errors.New("options are not supported on this platform")) } return nil }
package echo type ( Group struct { echo Echo } ) func (g *Group) Use(m ...Middleware) { for _, h := range m { g.echo.middleware = append(g.echo.middleware, wrapMiddleware(h)) } } func (g *Group) Connect(path string, h Handler) { g.echo.Connect(path, h) } func (g *Group) Delete(path string, h Handler) { g....
{ g.echo.WebSocket(path, h) }
package main import ( "fmt" "math" ) type geometry interface { area() float64 perim() float64 } type square struct { width, heigth float64 } type circle struct { radius float64 } func (s square) perim() float64 { return 2*s.width + 2*s.heigth } func (c circle) area() float64 { return math.Pi * c.radius ...
{ return s.width * s.heigth }
package rest import ( "fmt" ) type imagecache struct { ca cache } type pic struct { png []byte pkthsh hashcode } func makeImageCache() imagecache { ic := imagecache{} ic.ca = makeCache(pic{}) return ic } func (ic imagecache) put(hsh hashcode, png []byte) { sz := 0 if __DEBUG { sz = len(png) } deb...
{ return p.pkthsh }
package utils import "bytes" type CompositeError []error func (c *CompositeError) AppendError(err error) { if err != nil { *c = append(*c, err) } } func (c *CompositeError) Empty() bool { return c == nil || len(*c) == 0 } func NewCompositeError(errors ...error) error { res := &CompositeError{} for ...
{ var b bytes.Buffer for ind, err := range *c { _, _ = b.WriteString(err.Error()) if ind == len(*c)-1 { break } _, _ = b.WriteRune('\n') } return b.String() }
package utils import ( "html/template" "testing" ) func TestCompressedContent(t *testing.T)
{ htmlContent1 := template.HTML(` <html> <body> <h1>Test</h1> <p>CompressedContent</p> </body> </html> `) htmlContent2 := htmlContent1 CompressedContent(&htmlContent2) t.Log(len(htmlContent1) > len(htmlContent2)) }
package common import ( "bytes" "encoding/binary" "github.com/pkg/errors" ) type NodeMetastate struct { LedgerHeight uint64 } func (n *NodeMetastate) Bytes() ([]byte, error) { buffer := new(bytes.Buffer) err := binary.Write(buffer, binary.BigEndian, *n) if err != nil { return nil, errors.WithStack(e...
{ return &NodeMetastate{height} }
package model import ( "testing" ) func TestGetUsers(t *testing.T) { users := GetUsers() if len(users) != 50 { t.Errorf("Should have returned a list of 50 users") } } func TestGetUsersById(t *testing.T)
{ user, err := GetUserByID(3) if err != nil { t.Fatal(err) } if user.FirstName != "Jonathan" { t.Errorf("should have returned the first name of %s", user.FirstName) } }
package hugot import "context" type BackgroundHandler interface { Describer StartBackground(ctx context.Context, w ResponseWriter) } type baseBackgroundHandler struct { name string desc string bhf BackgroundFunc } type BackgroundFunc func(ctx context.Context, w ResponseWriter) func (bbh *baseBackgrou...
{ return &baseBackgroundHandler{ name: name, desc: desc, bhf: f, } }
package dialects import ( "fmt" "strings" ) type Filter interface { Do(sql string) string } type SeqFilter struct { Prefix string Start int } func (s *SeqFilter) Do(sql string) string { return convertQuestionMark(sql, s.Prefix, s.Start) } func convertQuestionMark(sql, prefix string, start int) string
{ var buf strings.Builder var beginSingleQuote bool var index = start for _, c := range sql { if !beginSingleQuote && c == '?' { buf.WriteString(fmt.Sprintf("%s%v", prefix, index)) index++ } else { if c == '\'' { beginSingleQuote = !beginSingleQuote } buf.WriteRune(c) } } return buf.Strin...
package derive import ( "go/types" "strings" ) type Named struct { Fields []*Field Reflect bool } type Field struct { name string external bool Type types.Type typeStr func() string } func (f *Field) Name(recv string, unsafePkg Import) string { if !f.Private() || !f.external { return recv + ...
{ numFields := typ.NumFields() n := &Named{ Fields: make([]*Field, numFields), } for i := 0; i < numFields; i++ { field := typ.Field(i) fieldType := field.Type() fieldName := field.Name() n.Fields[i] = &Field{ name: fieldName, external: external, Type: fieldType, typeStr: func() string...
package model import ( "reflect" "testing" ) func TestSubmitBenckmark(t *testing.T) { testData1 := testData0 testData1.Bm = Bm{ Switch: true, N: 10, C: 1, } resp, err := SubmitModel.Submit(testData1) if err != nil { panic(err) } t.Log(resp.Bm) if resp.Bm == "" { t.Fatal("no benchmark...
{ testResp := Response{ ReqUrl: testSrv.URL + "?k1=v1&k2=v2", Status: "200 OK", Test: "k1=v1&k2=v2 k3=v3&k4=v4", ReqBody: "k3=v3&k4=v4", } resp, err := SubmitModel.Submit(testData0) if err != nil { panic(err) } t.Logf("%#v", resp) if !reflect.DeepEqual(testResp, resp) { t.Fatal("response not e...
package speak import ( "errors" "os/exec" ) var Voices = []string{"Agnes", "Kathy", "Princess", "Vicki", "Victoria", "Bruce", "Fred", "Junior", "Ralph", "Albert", "Bahh", "Bells", "Boing", "Bubbles", "Cellos", "Deranged", "Hysterical", "Trinoids", "Whisper", "Zarvox"} func GetVoice(req string) string { f...
{ if str == "" { return errors.New("Problem executing: No message provided.") } cmd := exec.Command("say", "-v", GetVoice(voice), str) return cmd.Run() }
package outlet import ( "fmt" "l2met/bucket" "l2met/store" "time" ) type BucketReader struct { Store store.Store Interval time.Duration Partition string Ttl uint64 NumOutlets int NumScanners int Inbox chan *bucket.Bucket Outbox chan *bucket.Bucket } func NewBucketReader(sz,...
{ r.Outbox = out go r.scan() for i := 0; i < r.NumOutlets; i++ { go r.outlet() } }
package main import ( "github.com/conformal/winsvc/eventlog" "github.com/conformal/winsvc/mgr" "fmt" "os" "path/filepath" ) func installService(name, desc string) error { exepath, err := exePath() if err != nil { return err } m, err := mgr.Connect() if err != nil { return err } defer m.Disconnect() ...
{ prog := os.Args[0] p, err := filepath.Abs(prog) if err != nil { return "", err } fi, err := os.Stat(p) if err == nil { if !fi.Mode().IsDir() { return p, nil } err = fmt.Errorf("%s is directory", p) } if filepath.Ext(p) == "" { p += ".exe" fi, err := os.Stat(p) if err == nil { if !fi.Mode()...
package main import ( "net/http" "github.com/flynn/flynn/Godeps/_workspace/src/github.com/julienschmidt/httprouter" "github.com/flynn/flynn/Godeps/_workspace/src/gopkg.in/inconshreveable/log15.v2" "github.com/flynn/flynn/appliance/postgresql/client" "github.com/flynn/flynn/appliance/postgresql/state" "github.co...
{ res := &pgmanager.Status{ Peer: h.peer.Info(), } var err error res.Postgres, err = h.pg.Info() if err != nil { h.log.Error("error getting postgres info", "err", err) } httphelper.JSON(w, 200, res) }
package sftp import "os" type FileOpenFlags struct { Read, Write, Append, Creat, Trunc, Excl bool } func newFileOpenFlags(flags uint32) FileOpenFlags { return FileOpenFlags{ Read: flags&ssh_FXF_READ != 0, Write: flags&ssh_FXF_WRITE != 0, Append: flags&ssh_FXF_APPEND != 0, Creat: flags&ssh_FXF_CREA...
{ return FileAttrFlags{ Size: (flags & ssh_FILEXFER_ATTR_SIZE) != 0, UidGid: (flags & ssh_FILEXFER_ATTR_UIDGID) != 0, Permissions: (flags & ssh_FILEXFER_ATTR_PERMISSIONS) != 0, Acmodtime: (flags & ssh_FILEXFER_ATTR_ACMODTIME) != 0, } }
package live_data import ( "context" "go-common/app/interface/live/app-interface/conf" ) type Dao struct { c *conf.Config } func (d *Dao) Close() { return } func (d *Dao) Ping(c context.Context) error { return nil } func New(c *conf.Config) (dao *Dao)
{ dao = &Dao{ c: c, } return }
package awstasks import ( "encoding/json" "k8s.io/kops/upup/pkg/fi" ) type realInternetGateway InternetGateway var _ fi.HasLifecycle = &InternetGateway{} func (o *InternetGateway) GetLifecycle() *fi.Lifecycle { return o.Lifecycle } func (o *InternetGateway) SetLifecycle(lifecycle fi.Lifecycle) { o.Lif...
{ var jsonName string if err := json.Unmarshal(data, &jsonName); err == nil { o.Name = &jsonName return nil } var r realInternetGateway if err := json.Unmarshal(data, &r); err != nil { return err } *o = InternetGateway(r) return nil }
package example import ( "fmt" "net/http" ) func foo() int { n := 1 for i := 0; i < 3; i++ { if i == 0 { n++ } else if i == 1 { n += 2 } else { n += 3 } n++ } if n < 0 { n = 0 } n++ n += bar() bar() switch { case n < 20: n++ case n > 20: n-- default: n = 0 fmt.Println...
{ var err error a, b = http.Header{}, err return }
package instructions import "github.com/zxh0/jvm.go/jvmgo/jvm/rtda" type iand struct{ NoOperandsInstruction } type land struct{ NoOperandsInstruction } func (self *land) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopLong() v1 := stack.PopLong() result := v1 & v2 stack.PushLong(r...
{ stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopInt() result := v1 & v2 stack.PushInt(result) }
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) Aliases() []string { return viper.GetStringSlice("commands.skipplaylist.aliases") } fun...
{ return viper.GetString("commands.skipplaylist.description") }