{"input": "package flagutil\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"net/url\"\n\n\t\"github.com/sirupsen/logrus\"\n\n\t\"k8s.io/test-infra/prow/bugzilla\"\n\t\"k8s.io/test-infra/prow/config/secret\"\n)\n\n\ntype BugzillaOptions struct {\n\tendpoint string\n\tgithubExternalTrackerId uint\n\tApiKeyPath string\n}\n\n\nfunc (o *BugzillaOptions) AddFlags(fs *flag.FlagSet) {\n\tfs.StringVar(&o.endpoint, \"bugzilla-endpoint\", \"\", \"Bugzilla's API endpoint.\")\n\tfs.UintVar(&o.githubExternalTrackerId, \"bugzilla-github-external-tracker-id\", 0, \"The ext_type_id for GitHub external bugs, optional.\")\n\tfs.StringVar(&o.ApiKeyPath, \"bugzilla-api-key-path\", \"\", \"Path to the file containing the Bugzilla API key.\")\n}\n\n\nfunc (o *BugzillaOptions) Validate(dryRun bool) error {\n\tif o.endpoint == \"\" {\n\t\tlogrus.Info(\"empty -bugzilla-endpoint, will not create Bugzilla client\")\n\t\treturn nil\n\t}\n\n\tif _, err := url.ParseRequestURI(o.endpoint); err != nil {\n\t\treturn fmt.Errorf(\"invalid -bugzilla-endpoint URI: %q\", o.endpoint)\n\t}\n\n\tif o.ApiKeyPath == \"\" {\n\t\tlogrus.Info(\"empty -bugzilla-api-key-path, will use anonymous Bugzilla client\")\n\t}\n\n\treturn nil\n}\n\n\n\n\nfunc (o *BugzillaOptions) BugzillaClient(secretAgent *secret.Agent) (bugzilla.Client, error) ", "output": "{\n\tif o.endpoint == \"\" {\n\t\treturn nil, fmt.Errorf(\"empty -bugzilla-endpoint, cannot create Bugzilla client\")\n\t}\n\n\tvar generator *func() []byte\n\tif o.ApiKeyPath == \"\" {\n\t\tgeneratorFunc := func() []byte {\n\t\t\treturn []byte{}\n\t\t}\n\t\tgenerator = &generatorFunc\n\t} else {\n\t\tif secretAgent == nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot store token from %q without a secret agent\", o.ApiKeyPath)\n\t\t}\n\t\tgeneratorFunc := secretAgent.GetTokenGenerator(o.ApiKeyPath)\n\t\tgenerator = &generatorFunc\n\t}\n\n\treturn bugzilla.NewClient(*generator, o.endpoint, o.githubExternalTrackerId), nil\n}"} {"input": "package models\n\nimport (\n\t\"github.com/astaxie/beego/orm\"\n)\n\ntype PmpCampaignCreative struct {\n\tId int `orm:\"column(id);auto\"`\n\tCampaignId int `orm:\"column(campaign_id)\"`\n\tName string `orm:\"column(name);size(45);null\"`\n\tWidth int `orm:\"column(width);null\"`\n\tHeight int `orm:\"column(height);null\"`\n\tCreativeUrl string `orm:\"column(creative_url);size(255);null\"`\n\tCreativeStatus int `orm:\"column(creative_status);null\"`\n\tLandingUrl string `orm:\"column(landing_url);size(500);null\"`\n\tImpTrackingUrl string `orm:\"column(imp_tracking_url);size(1000);null\"`\n\tClkTrackingUrl string `orm:\"column(clk_tracking_url);size(1000)\"`\n\tDisplayTitle string `orm:\"column(display_title);size(200);null\"`\n\tDisplayText string `orm:\"column(display_text);size(1000);null\"`\n}\n\nfunc (t *PmpCampaignCreative) TableName() string {\n\treturn \"pmp_campaign_creative\"\n}\n\n\n\nfunc AddPmpCampaignCreative(v *PmpCampaignCreative) (err error) {\n\to := orm.NewOrm()\n\n\t_, err = o.Insert(v)\n\treturn err\n\n}\n\nfunc init() ", "output": "{\n\torm.RegisterModel(new(PmpCampaignCreative))\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n\n\t\"go-common/app/job/openplatform/article/conf\"\n\t\"go-common/app/job/openplatform/article/http\"\n\t\"go-common/app/job/openplatform/article/service\"\n\t\"go-common/library/log\"\n\t\"go-common/library/net/trace\"\n)\n\nfunc main() {\n\tflag.Parse()\n\tinitConf()\n\tinitLog()\n\tdefer log.Close()\n\tlog.Info(\"article-job start\")\n\tsrv := service.New(conf.Conf)\n\thttp.Init(conf.Conf, srv)\n\tinitSignal(srv)\n}\n\n\n\nfunc initLog() {\n\tlog.Init(conf.Conf.Xlog)\n\ttrace.Init(conf.Conf.Tracer)\n\tdefer trace.Close()\n}\n\nfunc initSignal(srv *service.Service) {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)\n\tfor {\n\t\ts := <-c\n\t\tlog.Info(\"article-job get a signal: %s\", s.String())\n\t\tswitch s {\n\t\tcase syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:\n\t\t\tif err := srv.Close(); err != nil {\n\t\t\t\tlog.Error(\"srv close consumer error(%+v)\", err)\n\t\t\t}\n\t\t\treturn\n\t\tcase syscall.SIGHUP:\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc initConf() ", "output": "{\n\tif err := conf.Init(); err != nil {\n\t\tpanic(err)\n\t}\n}"} {"input": "package main\n\nimport (\n\t. \"launchpad.net/gocheck\"\n\t\"launchpad.net/juju-core/charm\"\n\tjujutesting \"launchpad.net/juju-core/juju/testing\"\n\t\"launchpad.net/juju-core/testing\"\n)\n\ntype ExposeSuite struct {\n\tjujutesting.RepoSuite\n}\n\nvar _ = Suite(&ExposeSuite{})\n\nfunc runExpose(c *C, args ...string) error {\n\t_, err := testing.RunCommand(c, &ExposeCommand{}, args)\n\treturn err\n}\n\n\n\nfunc (s *ExposeSuite) TestExpose(c *C) {\n\ttesting.Charms.BundlePath(s.SeriesPath, \"dummy\")\n\terr := runDeploy(c, \"local:dummy\", \"some-service-name\")\n\tc.Assert(err, IsNil)\n\tcurl := charm.MustParseURL(\"local:precise/dummy-1\")\n\ts.AssertService(c, \"some-service-name\", curl, 1, 0)\n\n\terr = runExpose(c, \"some-service-name\")\n\tc.Assert(err, IsNil)\n\ts.assertExposed(c, \"some-service-name\")\n\n\terr = runExpose(c, \"nonexistent-service\")\n\tc.Assert(err, ErrorMatches, `service \"nonexistent-service\" not found`)\n}\n\nfunc (s *ExposeSuite) assertExposed(c *C, service string) ", "output": "{\n\tsvc, err := s.State.Service(service)\n\tc.Assert(err, IsNil)\n\texposed := svc.IsExposed()\n\tc.Assert(exposed, Equals, true)\n}"} {"input": "package wire\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\n\n\n\n\ntype MsgFilterClear struct{}\n\n\n\nfunc (msg *MsgFilterClear) MsgDecode(r io.Reader, pver uint32) error {\n\tif pver < BIP0037Version {\n\t\tstr := fmt.Sprintf(\"filterclear message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgFilterClear.MsgDecode\", str)\n\t}\n\n\treturn nil\n}\n\n\n\n\n\n\n\nfunc (msg *MsgFilterClear) Command() string {\n\treturn CmdFilterClear\n}\n\n\n\nfunc (msg *MsgFilterClear) MaxPayloadLength(pver uint32) uint32 {\n\treturn 0\n}\n\n\n\nfunc NewMsgFilterClear() *MsgFilterClear {\n\treturn &MsgFilterClear{}\n}\n\nfunc (msg *MsgFilterClear) MsgEncode(w io.Writer, pver uint32) error ", "output": "{\n\tif pver < BIP0037Version {\n\t\tstr := fmt.Sprintf(\"filterclear message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgFilterClear.MsgEncode\", str)\n\t}\n\n\treturn nil\n}"} {"input": "package proxy\n\nimport (\n\t\"log\"\n\t\"strconv\"\n\n\t\"../util\"\n)\n\nfunc (s *ProxyServer) handleGetWorkRPC(cs *Session, diff, id string) (reply []string, errorReply *ErrorReply) {\n\tt := s.currentBlockTemplate()\n\tif len(t.Header) == 0 {\n\t\treturn nil, &ErrorReply{Code: -1, Message: \"Work not ready\"}\n\t}\n\ttargetHex := t.Target\n\n\tif !s.rpc().Pool {\n\t\tminerDifficulty, err := strconv.ParseFloat(diff, 64)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Invalid difficulty %v from %v@%v \", diff, id, cs.ip)\n\t\t\tminerDifficulty = 5\n\t\t}\n\t\ttargetHex = util.MakeTargetHex(minerDifficulty)\n\t}\n\treply = []string{t.Header, t.Seed, targetHex}\n\treturn\n}\n\nfunc (s *ProxyServer) handleSubmitRPC(cs *Session, diff string, id string, params []string) (reply bool, errorReply *ErrorReply) {\n\tminer, ok := s.miners.Get(id)\n\tif !ok {\n\t\tminer = NewMiner(id, cs.ip)\n\t\ts.registerMiner(miner)\n\t}\n\n\tt := s.currentBlockTemplate()\n\treply = miner.processShare(s, t, diff, params)\n\treturn\n}\n\n\n\nfunc (s *ProxyServer) handleUnknownRPC(cs *Session, req *JSONRpcReq) *ErrorReply {\n\tlog.Printf(\"Unknown RPC method: %v\", req)\n\treturn &ErrorReply{Code: -1, Message: \"Invalid method\"}\n}\n\nfunc (s *ProxyServer) handleSubmitHashrate(cs *Session, req *JSONRpcReq) bool ", "output": "{\n\treply, _ := s.rpc().SubmitHashrate(req.Params)\n\treturn reply\n}"} {"input": "package iso20022\n\n\ntype PlainCardData4 struct {\n\n\tPAN *Min8Max28NumericText `xml:\"PAN\"`\n\n\tCardSequenceNumber *Min2Max3NumericText `xml:\"CardSeqNb,omitempty\"`\n\n\tEffectiveDate *Max10Text `xml:\"FctvDt,omitempty\"`\n\n\tExpiryDate *Max10Text `xml:\"XpryDt\"`\n\n\tServiceCode *Exact3NumericText `xml:\"SvcCd,omitempty\"`\n\n\tTrackData []*TrackData1 `xml:\"TrckData,omitempty\"`\n\n\tCardSecurityCode *CardSecurityInformation1 `xml:\"CardSctyCd,omitempty\"`\n}\n\nfunc (p *PlainCardData4) SetPAN(value string) {\n\tp.PAN = (*Min8Max28NumericText)(&value)\n}\n\nfunc (p *PlainCardData4) SetCardSequenceNumber(value string) {\n\tp.CardSequenceNumber = (*Min2Max3NumericText)(&value)\n}\n\nfunc (p *PlainCardData4) SetEffectiveDate(value string) {\n\tp.EffectiveDate = (*Max10Text)(&value)\n}\n\nfunc (p *PlainCardData4) SetExpiryDate(value string) {\n\tp.ExpiryDate = (*Max10Text)(&value)\n}\n\nfunc (p *PlainCardData4) SetServiceCode(value string) {\n\tp.ServiceCode = (*Exact3NumericText)(&value)\n}\n\n\n\nfunc (p *PlainCardData4) AddCardSecurityCode() *CardSecurityInformation1 {\n\tp.CardSecurityCode = new(CardSecurityInformation1)\n\treturn p.CardSecurityCode\n}\n\nfunc (p *PlainCardData4) AddTrackData() *TrackData1 ", "output": "{\n\tnewValue := new(TrackData1)\n\tp.TrackData = append(p.TrackData, newValue)\n\treturn newValue\n}"} {"input": "package creditcard\n\nimport (\n\t\"testing\"\n)\n\ntype card struct {\n\tNumber string\n\tType string\n\tValid bool\n}\n\nvar cards = []*card{\n\t&card{\"4242424242424242\", \"Visa\", true}, \n\t&card{\"4213729238347292\", \"Visa\", false}, \n\t&card{\"79927398713\", \"Unknown\", true}, \n\t&card{\"79927398710\", \"Unknown\", false}, \n\t&card{\"6011111111111117\", \"Discover\", true}, \n\t&card{\"6011342393482022\", \"Discover\", false}, \n\t&card{\"344347386473833\", \"AmericanExpress\", false}, \n\t&card{\"374347386473833\", \"AmericanExpress\", false}, \n\t&card{\"30569309025904\", \"DinersClub/Carteblanche\", true}, \n\t&card{\"30569309025905\", \"DinersClub/Carteblanche\", false}, \n\t&card{\"5555555555554444\", \"MasterCard\", true}, \n\t&card{\"5555555555554445\", \"MasterCard\", false}, \n\t&card{\"180034239348202\", \"JCB\", false}, \n}\n\n\n\nfunc TestCardype(t *testing.T) {\n\tfor _, card := range cards {\n\t\tcardType := Cardtype(card.Number)\n\t\tif cardType != card.Type {\n\t\t\tt.Errorf(\"card type [%s]; want [%s]\", cardType, card.Type)\n\t\t}\n\t}\n}\n\nfunc TestGenerateLastDigit(t *testing.T) {\n\tlastDigit := GenerateLastDigit(\"5276 4400 6542 131\")\n\n\tif lastDigit != \"9\" {\n\t\tt.Errorf(\"last digit [%s]; want [%s]\", lastDigit, \"9\")\n\t}\n}\n\nfunc TestValidate(t *testing.T) ", "output": "{\n\tfor _, card := range cards {\n\t\tvalid := Validate(card.Number)\n\t\tif valid != card.Valid {\n\t\t\tt.Errorf(\"card validation [%v]; want [%v]\", valid, card.Valid)\n\t\t}\n\t}\n}"} {"input": "package msgraph\n\nimport \"context\"\n\n\ntype WorkbookFunctionsTanRequestBuilder struct{ BaseRequestBuilder }\n\n\nfunc (b *WorkbookFunctionsRequestBuilder) Tan(reqObj *WorkbookFunctionsTanRequestParameter) *WorkbookFunctionsTanRequestBuilder {\n\tbb := &WorkbookFunctionsTanRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}\n\tbb.BaseRequestBuilder.baseURL += \"/tan\"\n\tbb.BaseRequestBuilder.requestObject = reqObj\n\treturn bb\n}\n\n\ntype WorkbookFunctionsTanRequest struct{ BaseRequest }\n\n\nfunc (b *WorkbookFunctionsTanRequestBuilder) Request() *WorkbookFunctionsTanRequest {\n\treturn &WorkbookFunctionsTanRequest{\n\t\tBaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client, requestObject: b.requestObject},\n\t}\n}\n\n\n\n\nfunc (r *WorkbookFunctionsTanRequest) Post(ctx context.Context) (resObj *WorkbookFunctionResult, err error) ", "output": "{\n\terr = r.JSONRequest(ctx, \"POST\", \"\", r.requestObject, &resObj)\n\treturn\n}"} {"input": "package os\n\nimport \"fmt\"\n\n\n\nfunc Print_os() ", "output": "{\n\tfmt.Println(\"windows\")\n}"} {"input": "package testdata\n\nimport (\n\t\"github.com/semrush/zenrpc/v2\"\n)\n\ntype Group struct {\n\tId int `json:\"id\"`\n\tTitle string `json:\"title\"`\n\tNodes []Group `json:\"nodes\"`\n\tGroups []Group `json:\"group\"`\n\tChildOpt *Group `json:\"child\"`\n\tSub SubGroup `json:\"sub\"`\n}\n\ntype SubGroup struct {\n\tId int `json:\"id\"`\n\tTitle string `json:\"title\"`\n}\n\ntype Campaign struct {\n\tId int `json:\"id\"`\n\tGroups []Group `json:\"group\"`\n}\n\ntype CatalogueService struct{ zenrpc.Service }\n\n\n\nfunc (s CatalogueService) Second(campaigns []Campaign) (bool, error) {\n\treturn true, nil\n}\n\nfunc (s CatalogueService) Third() (Campaign, error) {\n\treturn Campaign{}, nil\n}\n\nfunc (s CatalogueService) First(groups []Group) (bool, error) ", "output": "{\n\treturn true, nil\n}"} {"input": "package helper\n\nimport \"regexp\"\n\n\n\nfunc IsHexString(testString string) bool ", "output": "{\n\treg := regexp.MustCompile(`(\\\\x[0-9a-f]{1,2}])*`)\n\treturn reg.MatchString(testString)\n}"} {"input": "package cl\n\nimport pb \"github.com/emmyzkp/emmy/anauth/cl/clpb\"\n\n\n\n\n\n\ntype PubParams struct {\n\tPubKey *PubKey\n\tRawCred *RawCred \n\tConfig *pb.Params\n}\n\nfunc GetDefaultParamSizes() *pb.Params ", "output": "{\n\treturn &pb.Params{\n\t\tRhoBitLen: 256,\n\t\tNLength: 256, \n\t\tAttrBitLen: 256,\n\t\tHashBitLen: 512,\n\t\tSecParam: 80,\n\t\tEBitLen: 597,\n\t\tE1BitLen: 120,\n\t\tVBitLen: 2724,\n\t\tChallengeSpace: 80,\n\t}\n}"} {"input": "package main\n\n\n\n\n\ntype Scope struct {\n\tparent *Scope \n\tentities map[string]*Decl\n}\n\nfunc NewScope(outer *Scope) *Scope {\n\ts := new(Scope)\n\ts.parent = outer\n\ts.entities = make(map[string]*Decl)\n\treturn s\n}\n\n\nfunc AdvanceScope(s *Scope) (*Scope, *Scope) {\n\tif len(s.entities) == 0 {\n\t\treturn s, s.parent\n\t}\n\treturn NewScope(s), s\n}\n\n\n\n\nfunc (s *Scope) addDecl(name string, d *Decl) *Decl {\n\tdecl, ok := s.entities[name]\n\tif !ok {\n\t\ts.entities[name] = d\n\t\treturn d\n\t}\n\treturn decl\n}\n\nfunc (s *Scope) replaceDecl(name string, d *Decl) {\n\ts.entities[name] = d\n}\n\nfunc (s *Scope) mergeDecl(d *Decl) {\n\tdecl, ok := s.entities[d.Name]\n\tif !ok {\n\t\ts.entities[d.Name] = d\n\t} else {\n\t\tdecl := decl.DeepCopy()\n\t\tdecl.ExpandOrReplace(d)\n\t\ts.entities[d.Name] = decl\n\t}\n}\n\nfunc (s *Scope) lookup(name string) *Decl {\n\tdecl, ok := s.entities[name]\n\tif !ok {\n\t\tif s.parent != nil {\n\t\t\treturn s.parent.lookup(name)\n\t\t} else {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn decl\n}\n\nfunc (s *Scope) addNamedDecl(d *Decl) *Decl ", "output": "{\n\treturn s.addDecl(d.Name, d)\n}"} {"input": "package extractor\n\nimport (\n\t\"archive/tar\"\n\t\"compress/gzip\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\n\tsecurejoin \"github.com/cyphar/filepath-securejoin\"\n)\n\ntype tgzExtractor struct{}\n\nfunc NewTgz() Extractor {\n\treturn &tgzExtractor{}\n}\n\nfunc (e *tgzExtractor) Extract(src, dest string) error {\n\tsrcType, err := mimeType(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch srcType {\n\tcase \"application/x-gzip\":\n\t\terr := extractTgz(src, dest)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"%s is not a tgz archive: %s\", src, srcType)\n\t}\n\n\treturn nil\n}\n\nfunc extractTgz(src, dest string) error {\n\tfd, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fd.Close()\n\n\tgReader, err := gzip.NewReader(fd)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer gReader.Close()\n\n\ttarReader := tar.NewReader(gReader)\n\treturn extractTarArchive(tarReader, dest)\n}\n\nfunc extractTarArchive(tarReader *tar.Reader, dest string) error {\n\tfor {\n\t\thdr, err := tarReader.Next()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif hdr.Name == \".\" {\n\t\t\tcontinue\n\t\t}\n\n\t\terr = extractTarArchiveFile(hdr, dest, tarReader)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\n\nfunc extractTarArchiveFile(header *tar.Header, dest string, input io.Reader) error ", "output": "{\n\tfilePath, err := securejoin.SecureJoin(dest, header.Name)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tfileInfo := header.FileInfo()\n\n\tif fileInfo.IsDir() {\n\t\treturn os.MkdirAll(filePath, fileInfo.Mode())\n\t}\n\n\terr = os.MkdirAll(filepath.Dir(filePath), 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif fileInfo.Mode()&os.ModeSymlink != 0 {\n\t\treturn os.Symlink(header.Linkname, filePath)\n\t}\n\n\tfileCopy, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, fileInfo.Mode())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer fileCopy.Close()\n\n\t_, err = io.Copy(fileCopy, input)\n\treturn err\n}"} {"input": "package metrics\n\nimport \"time\"\n\n\ntype TimeHistogram interface {\n\tWith(Field) TimeHistogram\n\tObserve(time.Duration)\n}\n\ntype timeHistogram struct {\n\tHistogram\n\tunit time.Duration\n}\n\n\n\nfunc NewTimeHistogram(h Histogram, unit time.Duration) TimeHistogram {\n\treturn &timeHistogram{\n\t\tHistogram: h,\n\t\tunit: unit,\n\t}\n}\n\nfunc (h *timeHistogram) With(f Field) TimeHistogram {\n\treturn &timeHistogram{\n\t\tHistogram: h.Histogram.With(f),\n\t\tunit: h.unit,\n\t}\n}\n\n\n\nfunc (h *timeHistogram) Observe(d time.Duration) ", "output": "{\n\th.Histogram.Observe(int64(d / h.unit))\n}"} {"input": "package pointers\n\nimport \"fmt\"\n\n\n\nfunc PtrExample() ", "output": "{\n\n\ti, j := 6, 9\n\n\tp := &i \n\tfmt.Println(*p) \n\tfmt.Printf(\"i : %v, j: %v : ( *p + i = %v )\", i, j, (*p + j))\n}"} {"input": "package tristate\n\ntype StateValue int\n\nconst (\n\tTRISTATE_SUCCESS StateValue = iota\n\tTRISTATE_FAILRUE\n\tTRISTATE_UNKNOWN\n)\n\ntype TriState struct {\n\tState StateValue\n\tErr error\n}\n\nfunc NewSuccess() *TriState {\n\treturn nil\n}\n\n\n\nfunc NewFailure(err error) *TriState {\n\tif err == nil {\n\t\tpanic(\"error not set\")\n\t}\n\treturn &TriState{TRISTATE_FAILRUE, err}\n}\n\nfunc (state *TriState) Error() string {\n\treturn state.Err.Error()\n}\n\nfunc (state *TriState) IsSuccess() bool {\n\treturn state == nil || state.State == TRISTATE_SUCCESS\n}\n\nfunc (state *TriState) IsFailure() bool {\n\treturn state != nil && state.State == TRISTATE_FAILRUE\n}\n\nfunc (state *TriState) IsUnknown() bool {\n\treturn state != nil && state.State == TRISTATE_UNKNOWN\n}\n\nfunc NewUnknown(err error) *TriState ", "output": "{\n\tif err == nil {\n\t\tpanic(\"error not set\")\n\t}\n\treturn &TriState{TRISTATE_UNKNOWN, err}\n}"} {"input": "package service\n\nimport (\n\t\"io/ioutil\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com/jakewright/tutorials/home-automation/04-hue-lights/service.config/domain\"\n)\n\ntype ConfigService struct {\n\tConfig *domain.Config\n\tLocation string\n}\n\n\nfunc (s *ConfigService) Watch(d time.Duration) {\n\tfor {\n\t\terr := s.Reload()\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t}\n\n\t\ttime.Sleep(d)\n\t}\n}\n\n\n\n\nfunc (s *ConfigService) Reload() error ", "output": "{\n\tdata, err := ioutil.ReadFile(s.Location)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = s.Config.SetFromBytes(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package metrics\n\nimport \"github.com/PagerDuty/godspeed\"\n\nvar Metric Metrics = BlackHole{}\n\ntype Metrics interface {\n\tCount(stat string, count float64, tags []string) error\n\tSet(stat string, value float64, tags []string) error\n}\n\ntype BlackHole struct{}\n\nfunc (b BlackHole) Count(stat string, count float64, tags []string) error {\n\treturn nil\n}\n\nfunc (b BlackHole) Set(stat string, value float64, tags []string) error {\n\treturn nil\n}\n\ntype GodSpeed struct {\n\tIP string\n\tPort int\n\tNameSpace string\n}\n\n\n\nfunc (b *GodSpeed) Count(stat string, count float64, tags []string) error {\n\tc, err := b.newConn()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer c.Conn.Close()\n\treturn c.Count(stat, count, tags)\n}\n\nfunc (b *GodSpeed) Set(stat string, value float64, tags []string) error {\n\tc, err := b.newConn()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer c.Conn.Close()\n\treturn c.Set(stat, value, tags)\n}\n\nfunc (b *GodSpeed) newConn() (*godspeed.Godspeed, error) ", "output": "{\n\tgs, err := godspeed.New(b.IP, b.Port, false)\n\tif err != nil {\n\t\treturn gs, err\n\t}\n\tgs.Namespace = b.NameSpace\n\n\treturn gs, err\n}"} {"input": "package olog\n\nimport (\n\t\"fmt\"\n)\n\n\ntype DirectLogger struct {\n\twriters map[string]Writer\n}\n\n\nfunc NewDirectLogger() *DirectLogger {\n\treturn &DirectLogger{\n\t\twriters: make(map[string]Writer),\n\t}\n}\n\n\nfunc (dl *DirectLogger) Log(level Level,\n\tmodule string,\n\tfmtstr string,\n\targs ...interface{}) {\n\tif level == PrintLevel {\n\t\treturn\n\t}\n\tfmtstr = ToString(level) + \" [\" + module + \"] \" + fmtstr\n\tmsg := fmt.Sprintf(fmtstr, args...)\n\tfor _, writer := range dl.writers {\n\t\tif writer.IsEnabled() {\n\t\t\twriter.Write(msg)\n\t\t}\n\t}\n}\n\n\nfunc (dl *DirectLogger) RegisterWriter(writer Writer) {\n\tif writer != nil {\n\t\tdl.writers[writer.UniqueID()] = writer\n\t}\n}\n\n\nfunc (dl *DirectLogger) RemoveWriter(uniqueID string) {\n\tdelete(dl.writers, uniqueID)\n}\n\n\n\n\nfunc (dl *DirectLogger) GetWriter(uniqueID string) (writer Writer) ", "output": "{\n\treturn dl.writers[uniqueID]\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSGlueCrawler_Schedule struct {\n\n\tScheduleExpression string `json:\"ScheduleExpression,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSGlueCrawler_Schedule) AWSCloudFormationType() string {\n\treturn \"AWS::Glue::Crawler.Schedule\"\n}\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\n\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSGlueCrawler_Schedule) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSGlueCrawler_Schedule) SetDependsOn(dependencies []string) ", "output": "{\n\tr._dependsOn = dependencies\n}"} {"input": "package config\n\nimport \"github.com/corestoreio/csfw/utils\"\n\n\n\ntype ScopePerm uint64\n\n\nvar ScopePermAll = ScopePerm(1<\", cred, nil)\n\tpager := client.List(nil)\n\tfor {\n\t\tnextResult := pager.NextPage(ctx)\n\t\tif err := pager.Err(); err != nil {\n\t\t\tlog.Fatalf(\"failed to advance page: %v\", err)\n\t\t}\n\t\tif !nextResult {\n\t\t\tbreak\n\t\t}\n\t\tfor _, v := range pager.PageResponse().Value {\n\t\t\tlog.Printf(\"Pager result: %#v\\n\", v)\n\t\t}\n\t}\n}"} {"input": "package metrics\n\n\ntype Healthcheck interface {\n\tCheck()\n\tError() error\n\tHealthy()\n\tUnhealthy(error)\n}\n\n\n\nfunc NewHealthcheck(f func(Healthcheck)) Healthcheck {\n\tif UseNilMetrics {\n\t\treturn NilHealthcheck{}\n\t}\n\treturn &StandardHealthcheck{nil, f}\n}\n\n\ntype NilHealthcheck struct{}\n\n\nfunc (NilHealthcheck) Check() {}\n\n\nfunc (NilHealthcheck) Error() error { return nil }\n\n\nfunc (NilHealthcheck) Healthy() {}\n\n\nfunc (NilHealthcheck) Unhealthy(error) {}\n\n\n\ntype StandardHealthcheck struct {\n\terr error\n\tf func(Healthcheck)\n}\n\n\n\n\n\nfunc (h *StandardHealthcheck) Error() error {\n\treturn h.err\n}\n\n\nfunc (h *StandardHealthcheck) Healthy() {\n\th.err = nil\n}\n\n\n\nfunc (h *StandardHealthcheck) Unhealthy(err error) {\n\th.err = err\n}\n\nfunc (h *StandardHealthcheck) Check() ", "output": "{\n\th.f(h)\n}"} {"input": "package github\n\nimport (\n . \"github.com/ErintLabs/trellohub/genapi\"\n \"log\"\n)\n\ntype Label struct {\n Name string `json:\"name\"`\n}\n\ntype GitUser struct {\n Name string `json:\"login\"`\n}\n\nfunc (issue *Issue) SetLabels(lbls []Label) {\n lst := make([]string, len(lbls))\n for i, v := range lbls {\n lst[i] = v.Name\n }\n issue.Labels.SetNameable(lst)\n}\n\n\n\n\n\n\nfunc (issue *Issue) AddLabel(label string) {\n log.Printf(\"Adding label %s to %s\", label, issue.String())\n lbls := [...]string { label }\n GenPOSTJSON(issue.github, issue.ApiURL() + \"/labels\", nil, &lbls)\n}\n\n\nfunc (issue *Issue) DelLabel(label string) {\n log.Printf(\"Removing label %s from %s\", label, issue.String())\n GenDEL(issue.github, issue.ApiURL() + \"/labels/\" + label) \n}\n\n\ntype userAssignRequest struct {\n Assigs []string `json:\"assignees\"`\n}\n\nfunc (issue *Issue) AddUser(user string) {\n log.Printf(\"Adding user %s to %s\", user, issue.String())\n payload := userAssignRequest{ []string{ user } }\n GenPOSTJSON(issue.github, issue.ApiURL() + \"/assignees\", nil, &payload)\n}\n\n\nfunc (issue *Issue) DelUser(user string) {\n log.Printf(\"Removing user %s from %s\", user, issue.String())\n payload := userAssignRequest{ []string{ user } }\n GenDELJSON(issue.github, issue.ApiURL() + \"/assignees\", &payload)\n}\n\nfunc (issue *Issue) SetMembers(mbmrs []GitUser) ", "output": "{\n lst := make([]string, len(mbmrs))\n for i, v := range mbmrs {\n lst[i] = v.Name\n }\n issue.Members.SetNameable(lst)\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/gorilla/mux\"\n\t\"net/http\"\n)\n\nfunc Index(w http.ResponseWriter, r *http.Request) {\n\n\tfmt.Fprintln(w, \"Welcome!\")\n}\n\nfunc TestIndex(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintln(w, \"Test Index!\")\n\n\ttodos := Todos{\n\t\tTodo{Name: \"Write presentation\"},\n\t\tTodo{Name: \"Host meetup\"},\n\t}\n\n\tif err := json.NewEncoder(w).Encode(todos); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\n\nfunc TestShow(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tvars := mux.Vars(r)\n\ttestId := vars[\"testId\"]\n\tfmt.Fprintln(w, \"Test show:\", testId)\n}"} {"input": "package ip\n\n\ntype Veth struct {\n\tLink\n\tPeerName string\n}\n\n\nfunc (veth *Veth) additionalArgs() []string {\n\targs := []string{}\n\tif veth.PeerName != \"\" {\n\t\targs = append(args, \"peer\", \"name\", veth.PeerName)\n\t}\n\treturn args\n}\n\n\n\n\nfunc (veth *Veth) Add() error ", "output": "{\n\treturn veth.Link.add(\"veth\", veth.additionalArgs())\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\n\n\n\n\n\nfunc evalPostfixInt(postfix []string) (int, error) {\n\tvar stack []int\n\tfor _, val := range postfix {\n\t\tif isOp(val) {\n\t\t\ta := stack[len(stack)-2]\n\t\t\tb := stack[len(stack)-1]\n\t\t\tretVal := simpleEvalInt(a, b, val)\n\t\t\tstack = append(stack[0:len(stack)-2], retVal)\n\t\t} else {\n\t\t\tnum, err := strconv.Atoi(val)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, nil\n\t\t\t}\n\t\t\tstack = append(stack, num)\n\t\t}\n\t}\n\tif len(stack) != 1 {\n\t\terr := fmt.Errorf(\"error calculating postfix\")\n\t\treturn 0, err\n\t}\n\treturn stack[0], nil\n}\n\n\nfunc power(a, b int) int {\n\tans := 1\n\tfor i := 0; i < b; i++ {\n\t\tans = a * ans\n\t}\n\treturn ans\n}\n\nfunc simpleEvalInt(a, b int, op string) int ", "output": "{\n\tswitch op {\n\tcase \"+\":\n\t\treturn a + b\n\tcase \"-\":\n\t\treturn a - b\n\tcase \"/\":\n\t\treturn a / b\n\tcase \"*\":\n\t\treturn a * b\n\tcase \"^\":\n\t\treturn power(a, b)\n\tdefault:\n\t\treturn 0\n\t}\n}"} {"input": "package smtp\n\nimport (\n\t\"errors\"\n\t\"testing\"\n)\n\ntype EmailRecorder struct {\n\tfrom string\n\tto []string\n\tmsg []byte\n}\n\ntype SMTPMock struct {\n\tr *EmailRecorder\n\terr error\n}\n\n\n\nfunc TestMailService(t *testing.T) {\n\tmailService := MailService{}\n\n\tvar i interface{} = &mailService\n\t_, ok := i.(IMailService)\n\n\tif !ok {\n\t\tt.Fatalf(\"MailService must implement IMailService\")\n\t}\n}\n\nfunc TestSendNormal(t *testing.T) {\n\tbody := \"From: john@doe.com\\r\\n\" +\n\t\t\"To: jane@doe.com\\r\\n\" +\n\t\t\"Subject: test\\r\\n\" +\n\t\t\"\\r\\n\" +\n\t\t\"message\\r\\n\"\n\ts := SMTPMock{err: nil}\n\tmailService := NewMailService(&s)\n\n\terr := mailService.Send(\"message\", \"test\", \"john@doe.com\", \"jane@doe.com\")\n\tif err != nil {\n\t\tt.Fatalf(\"Mustn't return an error\")\n\t}\n\tif string(s.r.msg) != body {\n\t\tt.Errorf(\"wrong message body.\\n\\nexpected: %s\\n got: %s\", body, s.r.msg)\n\t}\n}\n\nfunc TestSendError(t *testing.T) {\n\terr := errors.New(\"Error\")\n\ts := SMTPMock{err: err}\n\tmailService := NewMailService(&s)\n\n\terr = mailService.Send(\"message\", \"test\", \"john@doe.com\", \"jane@doe.com\")\n\tif err == nil {\n\t\tt.Fatalf(\"Must return an error\")\n\t}\n}\n\nfunc (s *SMTPMock) SendMail(from string, to []string, msg []byte) error ", "output": "{\n\ts.r = &EmailRecorder{from, to, msg}\n\treturn s.err\n}"} {"input": "package parsing\n\nimport (\n\t\"testing\"\n)\n\n\nfunc TestConcatIfNotEmpty(t *testing.T) {\n\tx := \"Hello World\"\n\toutput := ConcatIfNotEmpty(\" \", \"Hello\", \"\", \"World\")\n\tif x != output {\n\t\tt.Errorf(\"Unexpected output from ConcatIfNotEmpty: %s\", output)\n\t}\n}\n\n\n\nfunc TestParseYesOrNo(t *testing.T) {\n\tif !ParseYesOrNo(\"YES\") {\n\t\tt.Errorf(\"ParseYesOrNo returned false when it should return true\")\n\t}\n\tif !ParseYesOrNo(\"yes\") {\n\t\tt.Errorf(\"ParseYesOrNo returned false when it should return true\")\n\t}\n}\n\nfunc TestParseIntOrDefault(t *testing.T) ", "output": "{\n\tout := ParseIntOrDefault(\"4\", 0)\n\tif out != 4 {\n\t\tt.Errorf(\"Unexpected output from ParseIntOrDefault: %s\", out)\n\t}\n\tout = ParseIntOrDefault(\"\", 5)\n\tif out != 5 {\n\t\tt.Errorf(\"Unexpected output from ParseIntOrDefault default: %s\", out)\n\t}\n}"} {"input": "package libsecrets\n\nimport (\n\t\"time\"\n\n\t\"github.com/keybase/client/go/protocol/keybase1\"\n)\n\n\ntype Member struct {\n\tIdentifier string\n\tType string\n\tKeybaseUid keybase1.UID\n\tAddedBy string\n\tDateAdded time.Time\n}\n\n\n\n\n\nfunc NewMemberFromKeybaseUser(user *keybase1.User) *Member {\n\treturn NewKeybaseMember(user.Username, user.Uid)\n}\n\nfunc GetMemberListIdentifiers(members []*Member) (identifiers []string) {\n\tfor _, memberPointer := range members {\n\t\tmember := *memberPointer\n\t\tif member.Type != \"keybase\" {\n\t\t\tcontinue\n\t\t}\n\t\tidentifiers = append(identifiers, member.Identifier)\n\t}\n\n\treturn identifiers\n}\n\nfunc NewKeybaseMember(username string, uid keybase1.UID) *Member ", "output": "{\n\treturn &Member{\n\t\tIdentifier: username,\n\t\tType: \"keybase\",\n\t\tKeybaseUid: uid,\n\t\tDateAdded: time.Now(),\n\t}\n}"} {"input": "package iso20022\n\n\ntype CardPaymentTransaction42 struct {\n\n\tSaleReferenceIdentification *Max35Text `xml:\"SaleRefId,omitempty\"`\n\n\tTransactionIdentification *TransactionIdentifier1 `xml:\"TxId\"`\n\n\tRecipientTransactionIdentification *Max35Text `xml:\"RcptTxId,omitempty\"`\n\n\tReconciliationIdentification *Max35Text `xml:\"RcncltnId,omitempty\"`\n\n\tInterchangeData *Max140Text `xml:\"IntrchngData,omitempty\"`\n\n\tTransactionDetails *CardPaymentTransactionDetails22 `xml:\"TxDtls\"`\n}\n\nfunc (c *CardPaymentTransaction42) SetSaleReferenceIdentification(value string) {\n\tc.SaleReferenceIdentification = (*Max35Text)(&value)\n}\n\nfunc (c *CardPaymentTransaction42) AddTransactionIdentification() *TransactionIdentifier1 {\n\tc.TransactionIdentification = new(TransactionIdentifier1)\n\treturn c.TransactionIdentification\n}\n\n\n\nfunc (c *CardPaymentTransaction42) SetReconciliationIdentification(value string) {\n\tc.ReconciliationIdentification = (*Max35Text)(&value)\n}\n\nfunc (c *CardPaymentTransaction42) SetInterchangeData(value string) {\n\tc.InterchangeData = (*Max140Text)(&value)\n}\n\nfunc (c *CardPaymentTransaction42) AddTransactionDetails() *CardPaymentTransactionDetails22 {\n\tc.TransactionDetails = new(CardPaymentTransactionDetails22)\n\treturn c.TransactionDetails\n}\n\nfunc (c *CardPaymentTransaction42) SetRecipientTransactionIdentification(value string) ", "output": "{\n\tc.RecipientTransactionIdentification = (*Max35Text)(&value)\n}"} {"input": "package dns\n\nimport (\n\t\"strings\"\n)\n\nconst etcHostsFile = \"C:/Windows/System32/drivers/etc/hosts\"\n\nfunc getDNSSuffixList() []string {\n\toutput := runCommand(\"powershell\", \"-Command\", \"(Get-DnsClient)[0].SuffixSearchList\")\n\tif len(output) > 0 {\n\t\treturn strings.Split(output, \"\\r\\n\")\n\t}\n\n\tpanic(\"Could not find DNS search list!\")\n}\n\n\n\nfunc getDNSServerList() []string ", "output": "{\n\toutput := runCommand(\"powershell\", \"-Command\", \"(Get-DnsClientServerAddress).ServerAddresses\")\n\tif len(output) > 0 {\n\t\treturn strings.Split(output, \"\\r\\n\")\n\t}\n\n\tpanic(\"Could not find DNS Server list!\")\n}"} {"input": "package stores\n\nimport (\n\t\"HTVM/instructions/base\"\n\t\"HTVM/runtime\"\n)\n\n\ntype ASTORE struct {\n\tbase.Index8Instruction\n}\n\nfunc (self *ASTORE) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, self.Index)\n}\n\ntype ASTORE_0 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_0) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 0)\n}\n\ntype ASTORE_1 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_1) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 1)\n}\n\ntype ASTORE_2 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_2) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 2)\n}\n\ntype ASTORE_3 struct {\n\tbase.NoOperandsInstruction\n}\n\nfunc (self *ASTORE_3) Execute(frame *runtime.Frame) {\n\t_executeRef(frame, 3)\n}\n\ntype ASTORE_4 struct {\n\tbase.NoOperandsInstruction\n}\n\n\n\nfunc _executeRef(frame *runtime.Frame, index uint) {\n\tval := frame.OperateStack().PopRef()\n\tframe.LocalVars().SetRef(index, val)\n}\n\nfunc (self *ASTORE_4) Execute(frame *runtime.Frame) ", "output": "{\n\t_executeRef(frame, 4)\n}"} {"input": "package validation\n\nimport (\n\t\"k8s.io/apimachinery/pkg/util/validation/field\"\n\n\t\"github.com/openshift/origin/pkg/quota/admission/apis/runonceduration\"\n)\n\n\n\n\nfunc ValidateRunOnceDurationConfig(config *runonceduration.RunOnceDurationConfig) field.ErrorList ", "output": "{\n\tallErrs := field.ErrorList{}\n\tif config == nil || config.ActiveDeadlineSecondsLimit == nil {\n\t\treturn allErrs\n\t}\n\tif *config.ActiveDeadlineSecondsLimit <= 0 {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"activeDeadlineSecondsOverride\"), config.ActiveDeadlineSecondsLimit, \"must be greater than 0\"))\n\t}\n\treturn allErrs\n}"} {"input": "package queue\n\nimport (\n\t\"golang.org/x/net/context\"\n\t\"testing\"\n)\n\ntype mockWorker struct {\n\tObject chan interface{}\n}\n\nfunc (h *mockWorker) Handle(ctx context.Context, obj interface{}) {\n\th.Object <- obj\n}\n\n\n\nfunc TestNewEventQueue(t *testing.T) ", "output": "{\n\th := &mockWorker{make(chan interface{}, 1)}\n\n\tq := NewTaskQueue(0)\n\tq.AddWorker(h)\n\n\tq.Do(context.Background(), Task{Object: 1})\n\tif <-h.Object != 1 {\n\t\tt.Fatalf(\"TestNewEventQueue failed\")\n\t}\n\n\tq.Do(context.Background(), Task{Object: 11, Async: true})\n\tif <-h.Object != 11 {\n\t\tt.Fatalf(\"TestNewEventQueue failed\")\n\t}\n\n\tq.Run()\n\tq.Add(Task{Object: 2})\n\tif <-h.Object != 2 {\n\t\tt.Fatalf(\"TestNewEventQueue failed\")\n\t}\n\n\tq.Add(Task{Object: 22, Async: true})\n\tif <-h.Object != 22 {\n\t\tt.Fatalf(\"TestNewEventQueue failed\")\n\t}\n\tq.Stop()\n\tq.Add(Task{Object: 3})\n}"} {"input": "package rpc\n\nimport (\n\t\"github.com/mitchellh/packer/packer\"\n\t\"log\"\n\t\"net/rpc\"\n)\n\n\n\ntype hook struct {\n\tclient *rpc.Client\n\tmux *muxBroker\n}\n\n\n\ntype HookServer struct {\n\thook packer.Hook\n\tmux *muxBroker\n}\n\ntype HookRunArgs struct {\n\tName string\n\tData interface{}\n\tStreamId uint32\n}\n\nfunc (h *hook) Run(name string, ui packer.Ui, comm packer.Communicator, data interface{}) error {\n\tnextId := h.mux.NextId()\n\tserver := newServerWithMux(h.mux, nextId)\n\tserver.RegisterCommunicator(comm)\n\tserver.RegisterUi(ui)\n\tgo server.Serve()\n\n\targs := HookRunArgs{\n\t\tName: name,\n\t\tData: data,\n\t\tStreamId: nextId,\n\t}\n\n\treturn h.client.Call(\"Hook.Run\", &args, new(interface{}))\n}\n\nfunc (h *hook) Cancel() {\n\terr := h.client.Call(\"Hook.Cancel\", new(interface{}), new(interface{}))\n\tif err != nil {\n\t\tlog.Printf(\"Hook.Cancel error: %s\", err)\n\t}\n}\n\nfunc (h *HookServer) Run(args *HookRunArgs, reply *interface{}) error {\n\tclient, err := newClientWithMux(h.mux, args.StreamId)\n\tif err != nil {\n\t\treturn NewBasicError(err)\n\t}\n\tdefer client.Close()\n\n\tif err := h.hook.Run(args.Name, client.Ui(), client.Communicator(), args.Data); err != nil {\n\t\treturn NewBasicError(err)\n\t}\n\n\t*reply = nil\n\treturn nil\n}\n\n\n\nfunc (h *HookServer) Cancel(args *interface{}, reply *interface{}) error ", "output": "{\n\th.hook.Cancel()\n\treturn nil\n}"} {"input": "package disk\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"github.com/vmware/govmomi/vslm\"\n)\n\ntype register struct {\n\t*flags.DatastoreFlag\n}\n\nfunc init() {\n\tcli.Register(\"disk.register\", ®ister{})\n}\n\nfunc (cmd *register) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.DatastoreFlag, ctx = flags.NewDatastoreFlag(ctx)\n\tcmd.DatastoreFlag.Register(ctx, f)\n}\n\n\n\nfunc (cmd *register) Description() string {\n\treturn `Register existing disk on DS.\n\nExamples:\n govc disk.register disks/disk1.vmdk my-disk`\n}\n\nfunc (cmd *register) Run(ctx context.Context, f *flag.FlagSet) error {\n\tds, err := cmd.Datastore()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm := vslm.NewObjectManager(ds.Client())\n\n\tpath := ds.NewURL(f.Arg(0)).String()\n\n\tobj, err := m.RegisterDisk(ctx, path, f.Arg(1))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(obj.Config.Id.Id)\n\n\treturn nil\n}\n\nfunc (cmd *register) Usage() string ", "output": "{\n\treturn \"PATH [NAME]\"\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"os/exec\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\n\nfunc memorySize() (int64, error) ", "output": "{\n\tcmd := exec.Command(\"sysctl\", \"hw.memsize\")\n\tout, err := cmd.Output()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tfs := strings.Fields(string(out))\n\tif len(fs) != 2 {\n\t\treturn 0, errors.New(\"sysctl parse error\")\n\t}\n\tbytes, err := strconv.ParseInt(fs[1], 10, 64)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn bytes, nil\n}"} {"input": "package redis\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype ManagementClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient {\n\treturn ManagementClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}\n\nfunc New(subscriptionID string) ManagementClient ", "output": "{\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}"} {"input": "package leet_25\n\ntype ListNode struct {\n\tVal int\n\tNext *ListNode\n}\n\ntype dequeue struct {\n\tbuff []*ListNode\n}\n\nfunc (q *dequeue) lpop() *ListNode {\n\tif 0 == len(q.buff) {\n\t\treturn nil\n\t}\n\tp := q.buff[0]\n\tq.buff = q.buff[1:]\n\treturn p\n}\n\nfunc (q *dequeue) rpop() *ListNode {\n\tif 0 == len(q.buff) {\n\t\treturn nil\n\t}\n\tlast := len(q.buff) - 1\n\tp := q.buff[last]\n\tq.buff = q.buff[:last]\n\treturn p\n}\n\n\n\nfunc (q *dequeue) clear() {\n\tq.buff = buff[:0]\n}\n\nvar buff []*ListNode\n\nfunc reverseKGroup(head *ListNode, k int) *ListNode {\n\tif head == nil {\n\t\treturn nil\n\t}\n\tif k <= 1 {\n\t\treturn head\n\t}\n\tbuff = make([]*ListNode, 0, k)\n\tqueue := &dequeue{buff: buff}\n\tcount := 0\n\tcur := head\n\tfor cur != nil {\n\t\tcount++\n\t\tqueue.rpush(cur)\n\t\tif count == k {\n\t\t\tcount = 0\n\t\t\tfor {\n\t\t\t\tl := queue.lpop()\n\t\t\t\tr := queue.rpop()\n\t\t\t\tif l == nil || r == nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tl.Val, r.Val = r.Val, l.Val\n\t\t\t}\n\t\t\tqueue.clear()\n\t\t}\n\t\tcur = cur.Next\n\t}\n\treturn head\n}\n\nfunc (q *dequeue) rpush(p *ListNode) ", "output": "{\n\tq.buff = append(q.buff, p)\n}"} {"input": "package irc\n\nimport msg \"github.com/fudanchii/sifr/irc/message\"\n\ntype pingHandler struct{}\n\n\n\nfunc (p *pingHandler) Handle(c *Client, m *msg.Message) ", "output": "{\n\tc.Pong(m.Body)\n}"} {"input": "package test\n\nimport \"testing\"\n\n\n\n\nfunc Subtest(t *testing.T, name string, f func(*testing.T)) ", "output": "{\n\tf(t)\n}"} {"input": "package packets\n\nimport (\n\t\"fmt\"\n\t\"github.com/google/uuid\"\n\t\"io\"\n)\n\n\n\ntype PubcompPacket struct {\n\tFixedHeader\n\tMessageID uint16\n\tuuid uuid.UUID\n}\n\nfunc (pc *PubcompPacket) String() string {\n\tstr := fmt.Sprintf(\"%s\\n\", pc.FixedHeader)\n\tstr += fmt.Sprintf(\"MessageID: %d\", pc.MessageID)\n\treturn str\n}\n\nfunc (pc *PubcompPacket) Write(w io.Writer) error {\n\tvar err error\n\tpc.FixedHeader.RemainingLength = 2\n\tpacket := pc.FixedHeader.pack()\n\tpacket.Write(encodeUint16(pc.MessageID))\n\t_, err = packet.WriteTo(w)\n\n\treturn err\n}\n\nfunc (pc *PubcompPacket) Unpack(b io.Reader) {\n\tpc.MessageID = decodeUint16(b)\n}\n\n\n\nfunc (pc *PubcompPacket) UUID() uuid.UUID {\n\treturn pc.uuid\n}\n\nfunc (pc *PubcompPacket) Details() Details ", "output": "{\n\treturn Details{Qos: pc.Qos, MessageID: pc.MessageID}\n}"} {"input": "package utils\n\nimport (\n\t\"testing\"\n)\n\nfunc TestStringSlicesEqual(t *testing.T) {\n\ttests := []struct {\n\t\tl []string\n\t\tr []string\n\t\texpected bool\n\t}{\n\t\t{\n\t\t\tl: []string{\"a\", \"b\"},\n\t\t\tr: []string{\"a\"},\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tl: []string{\"a\", \"b\"},\n\t\t\tr: []string{\"a\", \"c\"},\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tl: []string{\"a\", \"b\"},\n\t\t\tr: []string{\"a\", \"b\"},\n\t\t\texpected: true,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tresult := StringSlicesEqual(test.l, test.r)\n\t\tif test.expected != result {\n\t\t\tt.Errorf(\"Expected %v, got %v\", test.expected, result)\n\t\t}\n\t}\n}\n\n\n\nfunc TestStringSlicesEqualIgnoreOrder(t *testing.T) ", "output": "{\n\ttests := []struct {\n\t\tl []string\n\t\tr []string\n\t\texpected bool\n\t}{\n\t\t{\n\t\t\tl: []string{\"a\", \"b\"},\n\t\t\tr: []string{\"a\"},\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tl: []string{\"a\", \"b\"},\n\t\t\tr: []string{\"a\", \"c\"},\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tl: []string{\"a\", \"b\"},\n\t\t\tr: []string{\"b\", \"a\"},\n\t\t\texpected: true,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tresult := StringSlicesEqualIgnoreOrder(test.l, test.r)\n\t\tif test.expected != result {\n\t\t\tt.Errorf(\"Expected %v, got %v\", test.expected, result)\n\t\t}\n\t}\n}"} {"input": "package cdn\n\nimport (\n\t. \"aliyun-openapi-go-sdk/core\"\n\t\"strconv\"\n)\n\ntype OpenCdnServiceRequest struct {\n\tRpcRequest\n\tOwnerId int\n\tResourceOwnerAccount string\n\tResourceOwnerId int\n\tInternetChargeType string\n}\n\nfunc (r *OpenCdnServiceRequest) SetOwnerId(value int) {\n\tr.OwnerId = value\n\tr.QueryParams.Set(\"OwnerId\", strconv.Itoa(value))\n}\nfunc (r *OpenCdnServiceRequest) GetOwnerId() int {\n\treturn r.OwnerId\n}\nfunc (r *OpenCdnServiceRequest) SetResourceOwnerAccount(value string) {\n\tr.ResourceOwnerAccount = value\n\tr.QueryParams.Set(\"ResourceOwnerAccount\", value)\n}\nfunc (r *OpenCdnServiceRequest) GetResourceOwnerAccount() string {\n\treturn r.ResourceOwnerAccount\n}\nfunc (r *OpenCdnServiceRequest) SetResourceOwnerId(value int) {\n\tr.ResourceOwnerId = value\n\tr.QueryParams.Set(\"ResourceOwnerId\", strconv.Itoa(value))\n}\nfunc (r *OpenCdnServiceRequest) GetResourceOwnerId() int {\n\treturn r.ResourceOwnerId\n}\nfunc (r *OpenCdnServiceRequest) SetInternetChargeType(value string) {\n\tr.InternetChargeType = value\n\tr.QueryParams.Set(\"InternetChargeType\", value)\n}\nfunc (r *OpenCdnServiceRequest) GetInternetChargeType() string {\n\treturn r.InternetChargeType\n}\n\n\n\ntype OpenCdnServiceResponse struct {\n}\n\nfunc OpenCdnService(req *OpenCdnServiceRequest, accessId, accessSecret string) (*OpenCdnServiceResponse, error) {\n\tvar pResponse OpenCdnServiceResponse\n\tbody, err := ApiHttpRequest(accessId, accessSecret, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tApiUnmarshalResponse(req.GetFormat(), body, &pResponse)\n\treturn &pResponse, err\n}\n\nfunc (r *OpenCdnServiceRequest) Init() ", "output": "{\n\tr.RpcRequest.Init()\n\tr.SetVersion(Version)\n\tr.SetAction(\"OpenCdnService\")\n\tr.SetProduct(Product)\n}"} {"input": "package implementation\n\nimport (\n\t\"crypto/tls\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/go-openapi/swag\"\n\t\"github.com/go-swagger/go-swagger/examples/auto-configure/restapi/operations\"\n)\n\ntype ConfigureImpl struct {\n\tflags Flags\n}\n\ntype Flags struct {\n\tExample1 string `long:\"example1\" description:\"Sample for showing how to configure cmd-line flags\"`\n\tExample2 string `long:\"example2\" description:\"Further info at https://github.com/jessevdk/go-flags\"`\n}\n\n\n\nfunc (i *ConfigureImpl) ConfigureTLS(tlsConfig *tls.Config) {\n}\n\nfunc (i *ConfigureImpl) ConfigureServer(s *http.Server, scheme, addr string) {\n\tif i.flags.Example1 != \"something\" {\n\t\tlog.Println(\"example1 argument is not something\")\n\t}\n}\n\nfunc (i *ConfigureImpl) SetupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}\n\nfunc (i *ConfigureImpl) SetupGlobalMiddleware(handler http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tlog.Printf(\"Recieved request on path: %v\", req.URL.String())\n\t\thandler.ServeHTTP(w, req)\n\t})\n}\n\nfunc (i *ConfigureImpl) CustomConfigure(api *operations.AToDoListApplicationAPI) {\n\tapi.Logger = log.Printf\n\tapi.ServerShutdown = func() {\n\t\tlog.Printf(\"Running ServerShutdown function\")\n\t}\n}\n\nfunc (i *ConfigureImpl) ConfigureFlags(api *operations.AToDoListApplicationAPI) ", "output": "{\n\tapi.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{\n\t\t{\n\t\t\tShortDescription: \"Example Flags\",\n\t\t\tLongDescription: \"\",\n\t\t\tOptions: &i.flags,\n\t\t},\n\t}\n}"} {"input": "package unix\n\nimport \"unsafe\"\n\n\n\nvar fcntl64Syscall uintptr = SYS_FCNTL\n\n\n\n\nfunc FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error ", "output": "{\n\t_, _, errno := Syscall(fcntl64Syscall, fd, uintptr(cmd), uintptr(unsafe.Pointer(lk)))\n\tif errno == 0 {\n\t\treturn nil\n\t}\n\treturn errno\n}"} {"input": "package log\n\nimport \"gopkg.in/inconshreveable/log15.v2\"\n\nvar (\n\tLogger log15.Logger\n)\n\nfunc init() {\n\tLogger = log15.New()\n\tLogger.SetHandler(log15.DiscardHandler())\n}\n\n\n\nfunc Interactive() {\n\tLogger.SetHandler(log15.MultiHandler(\n\t\tlog15.LvlFilterHandler(\n\t\t\tlog15.LvlError,\n\t\t\tlog15.StderrHandler)))\n}\n\n\nfunc Debug(msg string, ctx ...interface{}) { Logger.Debug(msg, ctx...) }\nfunc Info(msg string, ctx ...interface{}) { Logger.Info(msg, ctx...) }\nfunc Warn(msg string, ctx ...interface{}) { Logger.Warn(msg, ctx...) }\n\nfunc Crit(msg string, ctx ...interface{}) { Logger.Crit(msg, ctx...) }\n\nfunc Error(msg string, ctx ...interface{}) ", "output": "{ Logger.Error(msg, ctx...) }"} {"input": "package apb\n\nimport (\n\t\"testing\"\n\n\tft \"github.com/openshift/ansible-service-broker/pkg/fusortest\"\n)\n\n\n\nfunc TestCreateExtraVarsNilParameters(t *testing.T) {\n\tcontext := Context{Platform: \"kubernetes\", Namespace: \"testing-project\"}\n\tparameters := Parameters(nil)\n\n\tt.Log(\"calling createExtraVars\")\n\tvalue, err := createExtraVars(&context, ¶meters)\n\tif err != nil {\n\t\tt.Log(\"we have an error\")\n\t\tt.Fatal(err)\n\t}\n\n\tt.Log(value)\n\texpected := \"{\\\"namespace\\\":\\\"testing-project\\\"}\"\n\tft.AssertEqual(t, value, expected, \"invalid value on nil parameters\")\n}\n\nfunc TestCreateExtraVarsNilContextRef(t *testing.T) {\n\tparameters := &Parameters{\"key\": \"param\"}\n\n\tt.Log(\"calling createExtraVars\")\n\tvalue, err := createExtraVars(nil, parameters)\n\tif err != nil {\n\t\tt.Log(\"we have an error\")\n\t\tt.Fatal(err)\n\t}\n\n\tt.Log(value)\n\texpected := \"{\\\"key\\\":\\\"param\\\"}\"\n\tft.AssertEqual(t, value, expected, \"invalid value on empty context\")\n}\n\nfunc TestCreateExtraVars(t *testing.T) {\n\tcontext := &Context{Platform: \"kubernetes\", Namespace: \"testing-project\"}\n\tparameters := &Parameters{\"key\": \"param\"}\n\tvalue, err := createExtraVars(context, parameters)\n\tif err != nil {\n\t\tt.Log(\"we have an error\")\n\t\tt.Fatal(err)\n\t}\n\n\texpected := \"{\\\"key\\\":\\\"param\\\",\\\"namespace\\\":\\\"testing-project\\\"}\"\n\tft.AssertEqual(t, value, expected, \"extravars do not match\")\n}\n\nfunc TestCreateExtraVarsNilParametersRef(t *testing.T) ", "output": "{\n\tcontext := &Context{Platform: \"kubernetes\", Namespace: \"testing-project\"}\n\n\tt.Log(\"calling createExtraVars\")\n\tvalue, err := createExtraVars(context, nil)\n\tif err != nil {\n\t\tt.Log(\"we have an error\")\n\t\tt.Fatal(err)\n\t}\n\n\tt.Log(value)\n\texpected := \"{\\\"namespace\\\":\\\"testing-project\\\"}\"\n\tft.AssertEqual(t, value, expected, \"invalid value on nil parameters ref\")\n}"} {"input": "package main\n\nimport (\n\t\"io\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/gorilla/websocket\"\n)\n\ntype Client struct {\n\thub *Hub\n\tws *websocket.Conn\n\totherSide *Client\n\tchannelID uuid.UUID\n\tremoteType string\n\tparams map[string][]string\n\twmu sync.Mutex\n\trmu sync.Mutex\n}\n\nfunc (c *Client) WriteMessage(msgType int, message []byte) (err error) {\n\tc.wmu.Lock()\n\terr = c.ws.WriteMessage(msgType, message)\n\tc.wmu.Unlock()\n\treturn\n}\n\nfunc (c *Client) NextWriter(msgType int) (w io.WriteCloser, err error) {\n\tc.wmu.Lock()\n\tw, err = c.ws.NextWriter(msgType)\n\tc.wmu.Unlock()\n\treturn\n}\n\nfunc (c *Client) ReadMessage() (msgType int, message []byte, err error) {\n\tc.rmu.Lock()\n\tmsgType, message, err = c.ws.ReadMessage()\n\tc.rmu.Unlock()\n\treturn\n}\n\nfunc (c *Client) NextReader() (msgType int, r io.Reader, err error) {\n\tc.rmu.Lock()\n\tmsgType, r, err = c.ws.NextReader()\n\tc.rmu.Unlock()\n\treturn\n}\n\n\n\nfunc (c *Client) SetReadDeadline(t time.Time) (err error) {\n\tc.rmu.Lock()\n\terr = c.ws.SetReadDeadline(t)\n\tc.rmu.Unlock()\n\treturn\n}\n\nfunc (c *Client) SetWriteDeadline(t time.Time) (err error) ", "output": "{\n\tc.wmu.Lock()\n\terr = c.ws.SetWriteDeadline(t)\n\tc.wmu.Unlock()\n\treturn\n}"} {"input": "package main\n\n\n\n\n\n\n\nimport \"C\"\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"runtime\"\n\t\"runtime/pprof\"\n\t\"unsafe\"\n)\n\nfunc init() {\n\tregister(\"CgoRaceprof\", CgoRaceprof)\n}\n\n\n\nfunc CgoRaceprof() ", "output": "{\n\truntime.SetCgoTraceback(0, unsafe.Pointer(C.raceprofTraceback), nil, nil)\n\n\tvar buf bytes.Buffer\n\tpprof.StartCPUProfile(&buf)\n\n\tC.runRaceprofThread()\n\tfmt.Println(\"OK\")\n}"} {"input": "package route\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/dgrijalva/jwt-go\"\n\t\"github.com/iron-io/functions/examples/blog/database\"\n\t\"github.com/iron-io/functions/examples/blog/models\"\n\t\"golang.org/x/crypto/bcrypt\"\n)\n\nvar jwtSignKey = []byte(\"mysecretblog\")\n\ntype Response map[string]interface{}\n\nfunc SendResponse(resp Response) {\n\tdata, _ := json.Marshal(resp)\n\tfmt.Println(string(data))\n}\n\nfunc SendError(err interface{}) {\n\tSendResponse(Response{\n\t\t\"error\": err,\n\t})\n}\n\nfunc HandleToken(db *database.Database) {\n\tvar login *models.User\n\n\tif err := json.NewDecoder(os.Stdin).Decode(&login); err != nil {\n\t\tfmt.Printf(\"Couldn't decode login JSON: %v\\n\", err)\n\t\treturn\n\t}\n\n\tuser, err := db.GetUser(login.Username)\n\tif err != nil {\n\t\tSendError(\"Couldn't create a token\")\n\t\treturn\n\t}\n\n\tif err := bcrypt.CompareHashAndPassword(user.Password, []byte(login.NewPassword)); err != nil {\n\t\tSendError(\"Couldn't create a token\")\n\t\treturn\n\t}\n\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{\n\t\t\"user\": login.Username,\n\t\t\"exp\": time.Now().Add(1 * time.Hour),\n\t})\n\n\ttokenString, err := token.SignedString(jwtSignKey)\n\tif err != nil {\n\t\tSendError(\"Couldn't create a token\")\n\t\treturn\n\t}\n\n\tSendResponse(Response{\"token\": tokenString})\n}\n\n\n\nfunc Authentication() (map[string]interface{}, bool) ", "output": "{\n\tauthorization := os.Getenv(\"HEADER_AUTHORIZATION\")\n\n\tp := strings.Split(authorization, \" \")\n\tif len(p) <= 1 {\n\t\treturn nil, false\n\t}\n\n\ttoken, err := jwt.Parse(p[1], func(token *jwt.Token) (interface{}, error) {\n\t\tif _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {\n\t\t\treturn nil, fmt.Errorf(\"Unexpected signing method: %v\", token.Header[\"alg\"])\n\t\t}\n\t\treturn jwtSignKey, nil\n\t})\n\n\tif err != nil {\n\t\treturn nil, false\n\t}\n\n\tif claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {\n\t\treturn claims, true\n\t}\n\n\treturn nil, false\n}"} {"input": "package ast\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/gobuffalo/plush/token\"\n)\n\ntype InfixExpression struct {\n\tToken token.Token\n\tLeft Expression\n\tOperator string\n\tRight Expression\n}\n\nfunc (oe *InfixExpression) expressionNode() {\n}\n\nfunc (oe *InfixExpression) TokenLiteral() string {\n\treturn oe.Token.Literal\n}\n\n\n\nfunc (oe *InfixExpression) String() string ", "output": "{\n\tvar out bytes.Buffer\n\n\tout.WriteString(\"(\")\n\tif oe.Left != nil {\n\t\tout.WriteString(oe.Left.String())\n\t}\n\tout.WriteString(\" \" + oe.Operator + \" \")\n\tout.WriteString(oe.Right.String())\n\tout.WriteString(\")\")\n\n\treturn out.String()\n}"} {"input": "package classfile\n\nimport (\n\t\"github.com/zxh0/jvm.go/jvmgo/util/bigendian\"\n)\n\ntype ClassReader struct {\n\tdata []byte\n}\n\nfunc newClassReader(data []byte) *ClassReader {\n\treturn &ClassReader{data}\n}\n\nfunc (self *ClassReader) readUint8() uint8 {\n\tval := self.data[0]\n\tself.data = self.data[1:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint16() uint16 {\n\tval := bigendian.Uint16(self.data)\n\tself.data = self.data[2:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint32() uint32 {\n\tval := bigendian.Int32(self.data)\n\tself.data = self.data[4:]\n\treturn uint32(val)\n}\nfunc (self *ClassReader) readInt32() int32 {\n\tval := bigendian.Int32(self.data)\n\tself.data = self.data[4:]\n\treturn val\n}\n\nfunc (self *ClassReader) readInt64() int64 {\n\tval := bigendian.Int64(self.data)\n\tself.data = self.data[8:]\n\treturn val\n}\n\nfunc (self *ClassReader) readFloat32() float32 {\n\tval := bigendian.Float32(self.data)\n\tself.data = self.data[4:]\n\treturn val\n}\n\nfunc (self *ClassReader) readFloat64() float64 {\n\tval := bigendian.Float64(self.data)\n\tself.data = self.data[8:]\n\treturn val\n}\n\n\n\n\nfunc (self *ClassReader) readString() string {\n\tlength := uint32(self.readUint16())\n\tbytes := self.readBytes(length)\n\treturn string(bytes)\n}\n\nfunc (self *ClassReader) readBytes(length uint32) []byte ", "output": "{\n\tbytes := self.data[:length]\n\tself.data = self.data[length:]\n\treturn bytes\n}"} {"input": "package pmgo\n\nimport mgo \"gopkg.in/mgo.v2\"\n\ntype IterManager interface {\n\tAll(result interface{}) error\n\tClose() error\n\tDone() bool\n\tErr() error\n\tFor(result interface{}, f func() error) (err error)\n\tNext(result interface{}) bool\n\tTimeout() bool\n}\n\ntype Iter struct {\n\titer *mgo.Iter\n}\n\n\n\nfunc (i *Iter) All(result interface{}) error {\n\treturn i.iter.All(result)\n}\n\nfunc (i *Iter) Close() error {\n\treturn i.iter.Close()\n}\n\nfunc (i *Iter) Done() bool {\n\treturn i.iter.Done()\n}\n\nfunc (i *Iter) Err() error {\n\treturn i.iter.Err()\n}\n\nfunc (i *Iter) For(result interface{}, f func() error) (err error) {\n\treturn i.iter.For(result, f)\n}\n\nfunc (i *Iter) Next(result interface{}) bool {\n\treturn i.iter.Next(result)\n}\n\nfunc (i *Iter) Timeout() bool {\n\treturn i.iter.Timeout()\n}\n\nfunc NewIter(iter *mgo.Iter) IterManager ", "output": "{\n\treturn &Iter{iter}\n}"} {"input": "package memory\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/square/quotaservice/buckets\"\n\t\"github.com/square/quotaservice/config\"\n)\n\nvar factory = NewBucketFactory()\n\n\n\nfunc setUp() {\n\tfactory.Init(config.NewDefaultServiceConfig())\n}\n\nfunc TestTokenAcquisition(t *testing.T) {\n\tbucket := factory.NewBucket(\"memory\", \"memory\", config.NewDefaultBucketConfig(\"\"), false)\n\tbuckets.TestTokenAcquisition(t, bucket)\n}\n\nfunc TestGC(t *testing.T) {\n\tbuckets.TestGC(t, factory, \"memory\")\n}\n\nfunc TestMain(m *testing.M) ", "output": "{\n\tsetUp()\n\tr := m.Run()\n\tos.Exit(r)\n}"} {"input": "package commands\n\nimport (\n\t\"github.com/limetext/lime/backend\"\n)\n\ntype (\n\tUndoCommand struct {\n\t\tbackend.BypassUndoCommand\n\t\thard bool\n\t}\n\tRedoCommand struct {\n\t\tbackend.BypassUndoCommand\n\t\thard bool\n\t}\n)\n\n\n\nfunc (c *RedoCommand) Run(v *backend.View, e *backend.Edit) error {\n\tv.UndoStack().Redo(c.hard)\n\treturn nil\n}\n\nfunc init() {\n\tregister([]cmd{\n\t\t{\"undo\", &UndoCommand{hard: true}},\n\t\t{\"redo\", &RedoCommand{hard: true}},\n\t\t{\"soft_undo\", &UndoCommand{}},\n\t\t{\"soft_redo\", &RedoCommand{}},\n\t})\n}\n\nfunc (c *UndoCommand) Run(v *backend.View, e *backend.Edit) error ", "output": "{\n\tv.UndoStack().Undo(c.hard)\n\treturn nil\n}"} {"input": "package circular\n\nimport (\n\t\"errors\"\n)\n\n\ntype Buffer struct {\n\tsize int \n\tn int \n\tdata []byte \n\twrite, read int \n}\n\n\nfunc NewBuffer(size int) *Buffer {\n\n\treturn &Buffer{\n\t\tsize: size,\n\t\tdata: make([]byte, size),\n\t}\n}\n\n\nfunc (b *Buffer) ReadByte() (byte, error) {\n\tif b.n == 0 {\n\t\treturn 0, errors.New(\"no bytes read\")\n\t}\n\td := b.data[b.read]\n\tb.read = (b.read + 1) % b.size\n\tb.n--\n\treturn d, nil\n}\n\n\n\n\n\nfunc (b *Buffer) Overwrite(c byte) {\n\tif b.read == b.write && b.n > 0 {\n\t\tb.read = (b.read + 1) % b.size\n\t\tb.n--\n\t}\n\tb.data[b.write] = c\n\tb.write = (b.write + 1) % b.size\n\tb.n++\n}\n\n\nfunc (b *Buffer) Reset() {\n\t*b = Buffer{\n\t\tsize: b.size,\n\t\tdata: make([]byte, b.size),\n\t}\n}\n\nfunc (b *Buffer) WriteByte(c byte) error ", "output": "{\n\tif b.write == b.read && b.n > 0 {\n\t\treturn errors.New(\"buffer is full\")\n\t}\n\tb.Overwrite(c)\n\treturn nil\n}"} {"input": "package cli_test\n\nimport (\n\t\"flag\"\n\t\"testing\"\n\n\t\"github.com/zeroed/escli/Godeps/_workspace/src/github.com/codegangsta/cli\"\n)\n\nfunc TestCommandDoNotIgnoreFlags(t *testing.T) {\n\tapp := cli.NewApp()\n\tset := flag.NewFlagSet(\"test\", 0)\n\ttest := []string{\"blah\", \"blah\", \"-break\"}\n\tset.Parse(test)\n\n\tc := cli.NewContext(app, set, nil)\n\n\tcommand := cli.Command{\n\t\tName: \"test-cmd\",\n\t\tAliases: []string{\"tc\"},\n\t\tUsage: \"this is for testing\",\n\t\tDescription: \"testing\",\n\t\tAction: func(_ *cli.Context) {},\n\t}\n\terr := command.Run(c)\n\n\texpect(t, err.Error(), \"flag provided but not defined: -break\")\n}\n\n\n\nfunc TestCommandIgnoreFlags(t *testing.T) ", "output": "{\n\tapp := cli.NewApp()\n\tset := flag.NewFlagSet(\"test\", 0)\n\ttest := []string{\"blah\", \"blah\"}\n\tset.Parse(test)\n\n\tc := cli.NewContext(app, set, nil)\n\n\tcommand := cli.Command{\n\t\tName: \"test-cmd\",\n\t\tAliases: []string{\"tc\"},\n\t\tUsage: \"this is for testing\",\n\t\tDescription: \"testing\",\n\t\tAction: func(_ *cli.Context) {},\n\t\tSkipFlagParsing: true,\n\t}\n\terr := command.Run(c)\n\n\texpect(t, err, nil)\n}"} {"input": "package fakes\n\nimport (\n\tboshas \"github.com/cloudfoundry/bosh-agent/agent/applier/applyspec\"\n\t\"github.com/cloudfoundry/bosh-agent/agent/applier/models\"\n)\n\ntype FakeApplier struct {\n\tPrepared bool\n\tPrepareDesiredApplySpec boshas.ApplySpec\n\tPrepareError error\n\n\tApplied bool\n\tApplyCurrentApplySpec boshas.ApplySpec\n\tApplyDesiredApplySpec boshas.ApplySpec\n\tApplyError error\n\n\tConfigured bool\n\tConfiguredDesiredApplySpec boshas.ApplySpec\n\tConfiguredJobs []models.Job\n\tConfiguredError error\n}\n\nfunc NewFakeApplier() *FakeApplier {\n\treturn &FakeApplier{}\n}\n\nfunc (s *FakeApplier) Prepare(desiredApplySpec boshas.ApplySpec) error {\n\ts.Prepared = true\n\ts.PrepareDesiredApplySpec = desiredApplySpec\n\treturn s.PrepareError\n}\n\nfunc (s *FakeApplier) ConfigureJobs(desiredApplySpec boshas.ApplySpec) error {\n\ts.Configured = true\n\ts.ConfiguredDesiredApplySpec = desiredApplySpec\n\treturn s.ConfiguredError\n}\n\n\n\nfunc (s *FakeApplier) Apply(currentApplySpec, desiredApplySpec boshas.ApplySpec) error ", "output": "{\n\ts.Applied = true\n\ts.ApplyCurrentApplySpec = currentApplySpec\n\ts.ApplyDesiredApplySpec = desiredApplySpec\n\treturn s.ApplyError\n}"} {"input": "package weave\n\nimport (\n\t\"strings\"\n)\n\n\n\ntype Advice struct {\n\tbefore string\n\tafter string\n\taround string\n\n\tadviceTypeId int\n}\n\n\nfunc adviceType() map[int]string {\n\treturn map[int]string{\n\t\t1: \"before\",\n\t\t2: \"after\",\n\t\t3: \"around\",\n\t}\n}\n\n\n\n\nfunc adviceKind(l string) int ", "output": "{\n\tstuff := strings.Split(l, \": \")\n\tostuff := strings.Split(stuff[1], \" \")\n\n\tswitch ostuff[0] {\n\tcase \"before\":\n\t\treturn 1\n\tcase \"after\":\n\t\treturn 2\n\tcase \"around\":\n\t\treturn 3\n\t}\n\n\treturn -1\n}"} {"input": "package migration\n\nimport (\n\t\"github.com/jmoiron/sqlx\"\n)\n\ntype revision_db76e79e987 struct {\n}\n\nfunc (r *revision_db76e79e987) Version() string { return \"db76e79e987\" }\n\n\n\nfunc (r *revision_db76e79e987) Down(tx *sqlx.Tx) error {\n\tstmts := []string{\n\t\t`ALTER TABLE _user DROP COLUMN last_login_at;`,\n\t\t`ALTER TABLE _user DROP COLUMN last_seen_at;`,\n\t}\n\tfor _, stmt := range stmts {\n\t\tif _, err := tx.Exec(stmt); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (r *revision_db76e79e987) Up(tx *sqlx.Tx) error ", "output": "{\n\tstmts := []string{\n\t\t`ALTER TABLE _user ADD COLUMN last_login_at timestamp without time zone;`,\n\t\t`ALTER TABLE _user ADD COLUMN last_seen_at timestamp without time zone;`,\n\t}\n\tfor _, stmt := range stmts {\n\t\tif _, err := tx.Exec(stmt); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package sliceset\n\nimport (\n\t\"sort\"\n\n\t\"github.com/xtgo/set\"\n)\n\ntype Set []int\n\nfunc (s Set) Len() int { return len(s) }\nfunc (s Set) Less(i, j int) bool { return s[i] < s[j] }\nfunc (s Set) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (s Set) Copy() Set { return append(Set(nil), s...) }\n\nfunc (s Set) Union(t Set) Set { return s.Do(set.Union, t) }\nfunc (s Set) Inter(t Set) Set { return s.Do(set.Inter, t) }\nfunc (s Set) Diff(t Set) Set { return s.Do(set.Diff, t) }\n\nfunc (s Set) IsSub(t Set) bool { return s.DoBool(set.IsSub, t) }\nfunc (s Set) IsSuper(t Set) bool { return s.DoBool(set.IsSuper, t) }\nfunc (s Set) IsInter(t Set) bool { return s.DoBool(set.IsInter, t) }\nfunc (s Set) IsEqual(t Set) bool { return s.DoBool(set.IsEqual, t) }\n\nfunc (s Set) Uniq() Set {\n\tn := set.Uniq(s)\n\treturn s[:n]\n}\n\nfunc (s Set) Do(op set.Op, t Set) Set {\n\tdata := append(s, t...)\n\tn := op(data, len(s))\n\treturn data[:n]\n}\n\ntype BoolOp func(sort.Interface, int) bool\n\nfunc (s Set) DoBool(op BoolOp, t Set) bool {\n\tdata := append(s, t...)\n\treturn op(data, len(s))\n}\n\nfunc (s Set) SymDiff(t Set) Set ", "output": "{ return s.Do(set.SymDiff, t) }"} {"input": "package ignition\n\nimport (\n\t\"github.com/coreos/ignition/config/types\"\n\t\"github.com/hashicorp/terraform/helper/schema\"\n)\n\nfunc resourceGroup() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceGroupCreate,\n\t\tDelete: resourceGroupDelete,\n\t\tExists: resourceGroupExists,\n\t\tRead: resourceGroupRead,\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"name\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"gid\": &schema.Schema{\n\t\t\t\tType: schema.TypeInt,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"password_hash\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceGroupCreate(d *schema.ResourceData, meta interface{}) error {\n\tid, err := buildGroup(d, meta.(*cache))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.SetId(id)\n\treturn nil\n}\n\nfunc resourceGroupDelete(d *schema.ResourceData, meta interface{}) error {\n\td.SetId(\"\")\n\treturn nil\n}\n\n\n\nfunc resourceGroupRead(d *schema.ResourceData, meta interface{}) error {\n\treturn nil\n}\n\nfunc buildGroup(d *schema.ResourceData, c *cache) (string, error) {\n\treturn c.addGroup(&types.Group{\n\t\tName: d.Get(\"name\").(string),\n\t\tPasswordHash: d.Get(\"password_hash\").(string),\n\t\tGid: getUInt(d, \"gid\"),\n\t}), nil\n}\n\nfunc resourceGroupExists(d *schema.ResourceData, meta interface{}) (bool, error) ", "output": "{\n\tid, err := buildGroup(d, meta.(*cache))\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn id == d.Id(), nil\n}"} {"input": "package vision_test\n\nimport (\n\t\"context\"\n\n\tvision \"cloud.google.com/go/vision/apiv1\"\n\tvisionpb \"google.golang.org/genproto/googleapis/cloud/vision/v1\"\n)\n\nfunc ExampleNewImageAnnotatorClient() {\n\tctx := context.Background()\n\tc, err := vision.NewImageAnnotatorClient(ctx)\n\tif err != nil {\n\t}\n\t_ = c\n}\n\nfunc ExampleImageAnnotatorClient_BatchAnnotateImages() {\n\tctx := context.Background()\n\tc, err := vision.NewImageAnnotatorClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &visionpb.BatchAnnotateImagesRequest{\n\t}\n\tresp, err := c.BatchAnnotateImages(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\nfunc ExampleImageAnnotatorClient_BatchAnnotateFiles() {\n\tctx := context.Background()\n\tc, err := vision.NewImageAnnotatorClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &visionpb.BatchAnnotateFilesRequest{\n\t}\n\tresp, err := c.BatchAnnotateFiles(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\nfunc ExampleImageAnnotatorClient_AsyncBatchAnnotateImages() {\n\tctx := context.Background()\n\tc, err := vision.NewImageAnnotatorClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &visionpb.AsyncBatchAnnotateImagesRequest{\n\t}\n\top, err := c.AsyncBatchAnnotateImages(ctx, req)\n\tif err != nil {\n\t}\n\n\tresp, err := op.Wait(ctx)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\n\n\nfunc ExampleImageAnnotatorClient_AsyncBatchAnnotateFiles() ", "output": "{\n\tctx := context.Background()\n\tc, err := vision.NewImageAnnotatorClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &visionpb.AsyncBatchAnnotateFilesRequest{\n\t}\n\top, err := c.AsyncBatchAnnotateFiles(ctx, req)\n\tif err != nil {\n\t}\n\n\tresp, err := op.Wait(ctx)\n\tif err != nil {\n\t}\n\t_ = resp\n}"} {"input": "package v1\n\nimport (\n\t\"k8s.io/kubernetes/pkg/runtime\"\n)\n\nfunc addDefaultingFuncs(scheme *runtime.Scheme) {\n\tscheme.AddDefaultingFuncs(\n\t\tSetDefaults_Job,\n\t)\n}\n\n\n\nfunc SetDefaults_Job(obj *Job) ", "output": "{\n\tif obj.Spec.Completions == nil && obj.Spec.Parallelism == nil {\n\t\tobj.Spec.Completions = new(int32)\n\t\t*obj.Spec.Completions = 1\n\t\tobj.Spec.Parallelism = new(int32)\n\t\t*obj.Spec.Parallelism = 1\n\t}\n\tif obj.Spec.Parallelism == nil {\n\t\tobj.Spec.Parallelism = new(int32)\n\t\t*obj.Spec.Parallelism = 1\n\t}\n}"} {"input": "package iso20022\n\n\ntype TotalFeesAndTaxes40 struct {\n\n\tTotalOverheadApplied *ActiveCurrencyAndAmount `xml:\"TtlOvrhdApld,omitempty\"`\n\n\tTotalFees *ActiveCurrencyAndAmount `xml:\"TtlFees,omitempty\"`\n\n\tTotalTaxes *ActiveCurrencyAndAmount `xml:\"TtlTaxs,omitempty\"`\n\n\tCommercialAgreementReference *Max35Text `xml:\"ComrclAgrmtRef,omitempty\"`\n\n\tIndividualFee []*Fee2 `xml:\"IndvFee,omitempty\"`\n\n\tIndividualTax []*Tax31 `xml:\"IndvTax,omitempty\"`\n}\n\nfunc (t *TotalFeesAndTaxes40) SetTotalOverheadApplied(value, currency string) {\n\tt.TotalOverheadApplied = NewActiveCurrencyAndAmount(value, currency)\n}\n\nfunc (t *TotalFeesAndTaxes40) SetTotalFees(value, currency string) {\n\tt.TotalFees = NewActiveCurrencyAndAmount(value, currency)\n}\n\nfunc (t *TotalFeesAndTaxes40) SetTotalTaxes(value, currency string) {\n\tt.TotalTaxes = NewActiveCurrencyAndAmount(value, currency)\n}\n\nfunc (t *TotalFeesAndTaxes40) SetCommercialAgreementReference(value string) {\n\tt.CommercialAgreementReference = (*Max35Text)(&value)\n}\n\nfunc (t *TotalFeesAndTaxes40) AddIndividualFee() *Fee2 {\n\tnewValue := new(Fee2)\n\tt.IndividualFee = append(t.IndividualFee, newValue)\n\treturn newValue\n}\n\n\n\nfunc (t *TotalFeesAndTaxes40) AddIndividualTax() *Tax31 ", "output": "{\n\tnewValue := new(Tax31)\n\tt.IndividualTax = append(t.IndividualTax, newValue)\n\treturn newValue\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n)\n\nvar (\n\tVersion string\n\tBuildDate string\n)\n\n\n\nfunc main() {\n\tfmt.Println(\"Hello\")\n}\n\nfunc init() ", "output": "{\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"Version: %s\\n\", Version)\n\t\tfmt.Fprintf(os.Stderr, \"Build Date: %s\\n\", BuildDate)\n\t\tfmt.Fprintf(os.Stderr, \"Usage of %s:\\n\", os.Args[0])\n\t\tflag.PrintDefaults()\n\t}\n\tflag.Parse()\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"context\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/strfmt\"\n\t\"github.com/go-openapi/swag\"\n\t\"github.com/go-openapi/validate\"\n)\n\n\n\n\n\n\ntype Endpoint struct {\n\n\tIPV4 strfmt.IPv4 `json:\"ipv4,omitempty\"`\n\n\tIPV6 strfmt.IPv6 `json:\"ipv6,omitempty\"`\n\n\tPort int64 `json:\"port,omitempty\"`\n\n\tServiceName string `json:\"serviceName,omitempty\"`\n}\n\n\n\n\nfunc (m *Endpoint) validateIPV4(formats strfmt.Registry) error {\n\tif swag.IsZero(m.IPV4) { \n\t\treturn nil\n\t}\n\n\tif err := validate.FormatOf(\"ipv4\", \"body\", \"ipv4\", m.IPV4.String(), formats); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (m *Endpoint) validateIPV6(formats strfmt.Registry) error {\n\tif swag.IsZero(m.IPV6) { \n\t\treturn nil\n\t}\n\n\tif err := validate.FormatOf(\"ipv6\", \"body\", \"ipv6\", m.IPV6.String(), formats); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc (m *Endpoint) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}\n\n\nfunc (m *Endpoint) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\nfunc (m *Endpoint) UnmarshalBinary(b []byte) error {\n\tvar res Endpoint\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *Endpoint) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tif err := m.validateIPV4(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIPV6(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package gpio\n\n\ntype Mode byte\n\nconst (\n\tIn Mode = 0 \n\tOut Mode = out \n\tAlt Mode = alt \n\tAltIn Mode = altIn \n\tAna Mode = ana \n)\n\n\ntype Driver byte\n\nconst (\n\tPushPull Driver = 0\n\tOpenDrain Driver = openDrain\n)\n\n\n\n\n\ntype Speed int8\n\nconst (\n\tVeryLow Speed = veryLow \n\tLow Speed = low \n\tMedium Speed = 0 \n\tHigh Speed = high \n\tVeryHigh Speed = veryHigh \n)\n\n\ntype Pull byte\n\nconst (\n\tNoPull Pull = 0 \n\tPullUp Pull = pullUp \n\tPullDown Pull = pullDown \n)\n\n\ntype Config struct {\n\tMode Mode \n\tDriver Driver \n\tSpeed Speed \n\tPull Pull \n}\n\n\nfunc (p *Port) SetupPin(index int, cfg *Config) {\n\tsetup(p, index, cfg)\n}\n\n\nfunc (p *Port) Setup(pins Pins, cfg *Config) {\n\tfor n := 0; n < 16; n++ {\n\t\tif pins&(1< message:string = Bool;\", \"ctor auth.sendInvites#771c1d97 phone_numbers:Vector message:string = Bool\"},\n\t\t{\"invokeWithLayer#da9b0d0d {X:Type} layer:int query:!X = X;\", \"ctor invokeWithLayer#da9b0d0d {X:Type} layer:int query:!X = X\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tactual, _, err := ParseLine(tt.input, ParseState{false})\n\t\tvar actualStr string\n\t\tif actual != nil {\n\t\t\tactualStr = actual.String()\n\t\t} else {\n\t\t\tactualStr = \"\"\n\t\t}\n\n\t\tif err != nil {\n\t\t\tt.Errorf(\"ParseLine(%q) failed: %v\", tt.input, err)\n\t\t} else if actualStr != tt.expected {\n\t\t\tt.Errorf(\"ParseLine(%q) == %q, expected %q\", tt.input, actualStr, tt.expected)\n\t\t} else {\n\t\t\tt.Logf(\"ParseLine(%q) == %q\", tt.input, actualStr)\n\t\t}\n\t}\n}\n\n\n\nfunc TestParseDef(t *testing.T) ", "output": "{\n\ttests := []string{knownschemas.MTProtoSchema, knownschemas.TelegramSchema}\n\n\tfor _, str := range tests {\n\t\tdefs, err := Parse(str)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Parse failed: %v\", err)\n\t\t}\n\t\tif len(defs) == 0 {\n\t\t\tt.Error(\"Parse returned zero defs\")\n\t\t}\n\t}\n}"} {"input": "package iso20022\n\n\ntype CardPaymentEnvironment37 struct {\n\n\tAcquirer *Acquirer4 `xml:\"Acqrr\"`\n\n\tMerchantIdentification *GenericIdentification53 `xml:\"MrchntId,omitempty\"`\n\n\tPOIIdentification *GenericIdentification53 `xml:\"POIId,omitempty\"`\n\n\tPOIComponent []*PointOfInteractionComponent5 `xml:\"POICmpnt,omitempty\"`\n}\n\nfunc (c *CardPaymentEnvironment37) AddAcquirer() *Acquirer4 {\n\tc.Acquirer = new(Acquirer4)\n\treturn c.Acquirer\n}\n\n\n\nfunc (c *CardPaymentEnvironment37) AddPOIIdentification() *GenericIdentification53 {\n\tc.POIIdentification = new(GenericIdentification53)\n\treturn c.POIIdentification\n}\n\nfunc (c *CardPaymentEnvironment37) AddPOIComponent() *PointOfInteractionComponent5 {\n\tnewValue := new(PointOfInteractionComponent5)\n\tc.POIComponent = append(c.POIComponent, newValue)\n\treturn newValue\n}\n\nfunc (c *CardPaymentEnvironment37) AddMerchantIdentification() *GenericIdentification53 ", "output": "{\n\tc.MerchantIdentification = new(GenericIdentification53)\n\treturn c.MerchantIdentification\n}"} {"input": "package connect\n\nimport \"io\"\nimport \"github.com/LilyPad/GoLilyPad/packet\"\n\ntype RequestAuthenticate struct {\n\tUsername string\n\tPassword string\n}\n\nfunc NewRequestAuthenticate(username string, password string) (this *RequestAuthenticate) {\n\tthis = new(RequestAuthenticate)\n\tthis.Username = username\n\tthis.Password = password\n\treturn\n}\n\n\n\ntype requestAuthenticateCodec struct {\n\n}\n\nfunc (this *requestAuthenticateCodec) Decode(reader io.Reader) (request Request, err error) {\n\trequestAuthenticate := new(RequestAuthenticate)\n\trequestAuthenticate.Username, err = packet.ReadString(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\trequestAuthenticate.Password, err = packet.ReadString(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\trequest = requestAuthenticate\n\treturn\n}\n\nfunc (this *requestAuthenticateCodec) Encode(writer io.Writer, request Request) (err error) {\n\trequestAuthenticate := request.(*RequestAuthenticate)\n\terr = packet.WriteString(writer, requestAuthenticate.Username)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = packet.WriteString(writer, requestAuthenticate.Password)\n\treturn\n}\n\ntype ResultAuthenticate struct {\n\n}\n\nfunc NewResultAuthenticate() (this *ResultAuthenticate) {\n\tthis = new(ResultAuthenticate)\n\treturn\n}\n\nfunc (this *ResultAuthenticate) Id() int {\n\treturn REQUEST_AUTHENTICATE\n}\n\ntype resultAuthenticateCodec struct {\n\n}\n\nfunc (this *resultAuthenticateCodec) Decode(reader io.Reader) (result Result, err error) {\n\tresult = new(ResultAuthenticate)\n\treturn\n}\n\nfunc (this *resultAuthenticateCodec) Encode(writer io.Writer, result Result) (err error) {\n\treturn\n}\n\nfunc (this *RequestAuthenticate) Id() int ", "output": "{\n\treturn REQUEST_AUTHENTICATE\n}"} {"input": "package retry\n\nimport (\n\t\"time\"\n)\n\ntype strategyFunc func(now time.Time) Timer\n\n\n\n\n\n\n\nfunc LimitCount(n int, strategy Strategy) Strategy {\n\treturn strategyFunc(func(now time.Time) Timer {\n\t\treturn &countLimitTimer{\n\t\t\ttimer: strategy.NewTimer(now),\n\t\t\tremain: n,\n\t\t}\n\t})\n}\n\ntype countLimitTimer struct {\n\ttimer Timer\n\tremain int\n}\n\nfunc (t *countLimitTimer) NextSleep(now time.Time) (time.Duration, bool) {\n\tif t.remain--; t.remain <= 0 {\n\t\treturn 0, false\n\t}\n\treturn t.timer.NextSleep(now)\n}\n\n\n\nfunc LimitTime(limit time.Duration, strategy Strategy) Strategy {\n\treturn strategyFunc(func(now time.Time) Timer {\n\t\treturn &timeLimitTimer{\n\t\t\ttimer: strategy.NewTimer(now),\n\t\t\tend: now.Add(limit),\n\t\t}\n\t})\n}\n\ntype timeLimitTimer struct {\n\ttimer Timer\n\tend time.Time\n}\n\nfunc (t *timeLimitTimer) NextSleep(now time.Time) (time.Duration, bool) {\n\tsleep, ok := t.timer.NextSleep(now)\n\tif ok && now.Add(sleep).After(t.end) {\n\t\treturn 0, false\n\t}\n\treturn sleep, ok\n}\n\nfunc (f strategyFunc) NewTimer(now time.Time) Timer ", "output": "{\n\treturn f(now)\n}"} {"input": "package v1_test\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime\"\n\n\tkapi \"github.com/GoogleCloudPlatform/kubernetes/pkg/api\"\n\tdeployapi \"github.com/openshift/origin/pkg/deploy/api\"\n\tcurrent \"github.com/openshift/origin/pkg/deploy/api/v1\"\n)\n\n\n\nfunc TestDefaults_rollingParams(t *testing.T) {\n\tc := ¤t.DeploymentConfig{}\n\to := roundTrip(t, runtime.Object(c))\n\tconfig := o.(*current.DeploymentConfig)\n\tstrat := config.Spec.Strategy\n\tif e, a := current.DeploymentStrategyTypeRolling, strat.Type; e != a {\n\t\tt.Errorf(\"expected strategy type %s, got %s\", e, a)\n\t}\n\tif e, a := deployapi.DefaultRollingUpdatePeriodSeconds, *strat.RollingParams.UpdatePeriodSeconds; e != a {\n\t\tt.Errorf(\"expected UpdatePeriodSeconds %d, got %d\", e, a)\n\t}\n\tif e, a := deployapi.DefaultRollingIntervalSeconds, *strat.RollingParams.IntervalSeconds; e != a {\n\t\tt.Errorf(\"expected IntervalSeconds %d, got %d\", e, a)\n\t}\n\tif e, a := deployapi.DefaultRollingTimeoutSeconds, *strat.RollingParams.TimeoutSeconds; e != a {\n\t\tt.Errorf(\"expected UpdatePeriodSeconds %d, got %d\", e, a)\n\t}\n}\n\nfunc roundTrip(t *testing.T, obj runtime.Object) runtime.Object ", "output": "{\n\tdata, err := kapi.Codec.Encode(obj)\n\tif err != nil {\n\t\tt.Errorf(\"%v\\n %#v\", err, obj)\n\t\treturn nil\n\t}\n\tobj2, err := kapi.Codec.Decode(data)\n\tif err != nil {\n\t\tt.Errorf(\"%v\\nData: %s\\nSource: %#v\", err, string(data), obj)\n\t\treturn nil\n\t}\n\tobj3 := reflect.New(reflect.TypeOf(obj).Elem()).Interface().(runtime.Object)\n\terr = kapi.Scheme.Convert(obj2, obj3)\n\tif err != nil {\n\t\tt.Errorf(\"%v\\nSource: %#v\", err, obj2)\n\t\treturn nil\n\t}\n\treturn obj3\n}"} {"input": "package gatherer\n\nimport (\n\t\"magic\"\n\n\t\"github.com/PuerkitoBio/goquery\"\n)\n\ntype single struct{}\n\n\n\nfunc (s single) Parse(doc *goquery.Document) (*magic.Card, error) {\n\tcol := \"#ctl00_ctl00_ctl00_MainContent_SubContent_SubContent_cardComponent0\"\n\treturn NewCard(col, doc).Parse()\n}\n\nfunc NewSingle() single ", "output": "{\n\treturn single{}\n}"} {"input": "package probe_test\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/minio/minio/pkg/probe\"\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc Test(t *testing.T) { TestingT(t) }\n\ntype MySuite struct{}\n\nvar _ = Suite(&MySuite{})\n\nfunc testDummy0() *probe.Error {\n\t_, e := os.Stat(\"this-file-cannot-exit\")\n\treturn probe.NewError(e)\n}\n\n\n\nfunc testDummy2() *probe.Error {\n\treturn testDummy1().Trace(\"DummyTag2\")\n}\n\nfunc (s *MySuite) TestProbe(c *C) {\n\tes := testDummy2().Trace(\"TopOfStack\")\n\tc.Assert(es, Not(Equals), nil)\n\n\tnewES := es.Trace()\n\tc.Assert(newES, Not(Equals), nil)\n}\n\nfunc (s *MySuite) TestWrappedError(c *C) {\n\t_, e := os.Stat(\"this-file-cannot-exit\")\n\tes := probe.NewError(e) \n\te = probe.WrapError(es) \n\t_, ok := probe.UnwrapError(e)\n\tc.Assert(ok, Equals, true)\n}\n\nfunc testDummy1() *probe.Error ", "output": "{\n\treturn testDummy0().Trace(\"DummyTag1\")\n}"} {"input": "package queue\n\n\n\n\ntype LazyQueue struct {\n\tqChan chan interface{}\n\tDequeueMethod DequeueMethod\n}\n\n\n\n\ntype DequeueMethod func(interface{})\n\n\n\n\nfunc NewLazyQueue(qsize int, dequeueMethod DequeueMethod, grcount int) *LazyQueue {\n\tqInstance := &LazyQueue{}\n\tqInstance.qChan = make(chan interface{}, qsize)\n\tqInstance.DequeueMethod = dequeueMethod\n\tif grcount <= 0 {\n\t\tgrcount = 1\n\t}\n\tfor i := 0; i < grcount; i++ {\n\t\tgo qInstance.startDequeue()\n\t}\n\n\treturn qInstance\n}\n\n\n\n\n\nfunc (lq *LazyQueue) startDequeue() {\n\tfor {\n\t\tselect {\n\t\tcase bm := <-lq.qChan:\n\t\t\tlq.DequeueMethod(bm)\n\t\t}\n\t}\n}\n\nfunc (lq *LazyQueue) Enqueue(qinfo interface{}) ", "output": "{\n\tlq.qChan <- qinfo\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"time\"\n)\n\n\n\n\nfunc LogDir(CreateDir string) {\n\n \n if _, err := os.Stat(CreateDir); os.IsNotExist(err) {\n fmt.Printf(\"No such file or directory: %s\", CreateDir)\n os.Mkdir(CreateDir, 0777)\n } else {\n fmt.Printf(\"Its There: %s\", CreateDir)\n }\n}\n\nfunc LogFile(CreateFile string) {\n \n if _, err := os.Stat(CreateFile + \".log\"); os.IsNotExist(err) {\n fmt.Printf(\"Log File \" + CreateFile + \".log Doesn't Exist.\\n\")\n os.Create(CreateFile + \".log\")\n fmt.Printf(\"Created the log file\\n\")\n } else {\n fmt.Printf(\"Log File Exists.\\n\")\n }\n}\n\nfunc ChannelLogger(LogDir string, UserNick string, message string) ", "output": "{\n STime := time.Now().Format(time.ANSIC)\n logLoc := fmt.Sprintf(\"%d-%s-%d\", time.Now().Day(), time.Now().Month(), time.Now().Year())\n\n f, err := os.OpenFile(LogDir + logLoc + \".log\", os.O_CREATE|os.O_RDWR|os.O_APPEND|os.O_SYNC, 0666)\n if err != nil {\n fmt.Println(f, err)\n }\n\n n, err := io.WriteString(f, STime + \" > \" + UserNick + message + \"\\n\")\n if err != nil {\n fmt.Println(n, err)\n }\n f.Close()\n}"} {"input": "package pricing\n\nimport (\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/client\"\n\t\"github.com/aws/aws-sdk-go/aws/client/metadata\"\n\t\"github.com/aws/aws-sdk-go/aws/request\"\n\t\"github.com/aws/aws-sdk-go/aws/signer/v4\"\n\t\"github.com/aws/aws-sdk-go/private/protocol/jsonrpc\"\n)\n\n\n\n\n\n\n\ntype Pricing struct {\n\t*client.Client\n}\n\n\nvar initClient func(*client.Client)\n\n\nvar initRequest func(*request.Request)\n\n\nconst (\n\tServiceName = \"api.pricing\" \n\tEndpointsID = ServiceName \n\tServiceID = \"Pricing\" \n)\n\n\n\n\n\n\n\n\n\n\n\nfunc New(p client.ConfigProvider, cfgs ...*aws.Config) *Pricing {\n\tc := p.ClientConfig(EndpointsID, cfgs...)\n\tif c.SigningNameDerived || len(c.SigningName) == 0 {\n\t\tc.SigningName = \"pricing\"\n\t}\n\treturn newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName)\n}\n\n\n\n\n\n\nfunc (c *Pricing) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\tif initRequest != nil {\n\t\tinitRequest(req)\n\t}\n\n\treturn req\n}\n\nfunc newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *Pricing ", "output": "{\n\tsvc := &Pricing{\n\t\tClient: client.New(\n\t\t\tcfg,\n\t\t\tmetadata.ClientInfo{\n\t\t\t\tServiceName: ServiceName,\n\t\t\t\tServiceID: ServiceID,\n\t\t\t\tSigningName: signingName,\n\t\t\t\tSigningRegion: signingRegion,\n\t\t\t\tEndpoint: endpoint,\n\t\t\t\tAPIVersion: \"2017-10-15\",\n\t\t\t\tJSONVersion: \"1.1\",\n\t\t\t\tTargetPrefix: \"AWSPriceListService\",\n\t\t\t},\n\t\t\thandlers,\n\t\t),\n\t}\n\n\tsvc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)\n\tsvc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler)\n\tsvc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler)\n\tsvc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler)\n\tsvc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler)\n\n\tif initClient != nil {\n\t\tinitClient(svc.Client)\n\t}\n\n\treturn svc\n}"} {"input": "package format\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\tblocks \"gx/ipfs/QmRcHuYzAyswytBuMF78rj3LTChYszomRFXNg4685ZN1WM/go-block-format\"\n)\n\n\ntype DecodeBlockFunc func(block blocks.Block) (Node, error)\n\ntype BlockDecoder interface {\n\tRegister(codec uint64, decoder DecodeBlockFunc)\n\tDecode(blocks.Block) (Node, error)\n}\ntype safeBlockDecoder struct {\n\tlock sync.RWMutex\n\tdecoders map[uint64]DecodeBlockFunc\n}\n\n\n\n\n\n\nfunc (d *safeBlockDecoder) Decode(block blocks.Block) (Node, error) {\n\tif node, ok := block.(Node); ok {\n\t\treturn node, nil\n\t}\n\n\tty := block.Cid().Type()\n\n\td.lock.RLock()\n\tdecoder, ok := d.decoders[ty]\n\td.lock.RUnlock()\n\n\tif ok {\n\t\treturn decoder(block)\n\t} else {\n\t\treturn nil, fmt.Errorf(\"unrecognized object type: %d\", ty)\n\t}\n}\n\nvar DefaultBlockDecoder BlockDecoder = &safeBlockDecoder{decoders: make(map[uint64]DecodeBlockFunc)}\n\n\nfunc Decode(block blocks.Block) (Node, error) {\n\treturn DefaultBlockDecoder.Decode(block)\n}\n\n\nfunc Register(codec uint64, decoder DecodeBlockFunc) {\n\tDefaultBlockDecoder.Register(codec, decoder)\n}\n\nfunc (d *safeBlockDecoder) Register(codec uint64, decoder DecodeBlockFunc) ", "output": "{\n\td.lock.Lock()\n\tdefer d.lock.Unlock()\n\td.decoders[codec] = decoder\n}"} {"input": "package cloudstorage\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n)\n\ntype MockStorage struct {\n\tPutRequest *http.Request\n\tGetURL *url.URL\n\tOriginallySigned bool\n\tListObjectsResponse *ListObjectsResponse\n}\n\nvar _ Storage = &MockStorage{}\n\nfunc (s *MockStorage) PresignPutObject(name string, accessType AccessType, header http.Header) (*http.Request, error) {\n\treturn s.PutRequest, nil\n}\n\nfunc (s *MockStorage) PresignGetObject(name string) (*url.URL, error) {\n\treturn s.GetURL, nil\n}\n\nfunc (s *MockStorage) PresignHeadObject(name string) (*url.URL, error) {\n\treturn s.GetURL, nil\n}\n\nfunc (s *MockStorage) RewriteGetURL(u *url.URL, name string) (*url.URL, bool, error) {\n\treturn s.GetURL, s.OriginallySigned, nil\n}\n\nfunc (s *MockStorage) ListObjects(r *ListObjectsRequest) (*ListObjectsResponse, error) {\n\treturn s.ListObjectsResponse, nil\n}\n\nfunc (s *MockStorage) DeleteObject(name string) error {\n\treturn nil\n}\n\nfunc (s *MockStorage) AccessType(header http.Header) AccessType {\n\treturn AccessTypeDefault\n}\n\n\n\nfunc (s *MockStorage) ProprietaryToStandard(header http.Header) http.Header {\n\treturn header\n}\n\nfunc (s *MockStorage) StandardToProprietary(header http.Header) http.Header ", "output": "{\n\treturn header\n}"} {"input": "package parser\n\nimport (\n\t\"github.com/dop251/goja/ast\"\n)\n\ntype _scope struct {\n\touter *_scope\n\tallowIn bool\n\tinIteration bool\n\tinSwitch bool\n\tinFunction bool\n\tdeclarationList []ast.Declaration\n\n\tlabels []string\n}\n\nfunc (self *_parser) openScope() {\n\tself.scope = &_scope{\n\t\touter: self.scope,\n\t\tallowIn: true,\n\t}\n}\n\nfunc (self *_parser) closeScope() {\n\tself.scope = self.scope.outer\n}\n\nfunc (self *_scope) declare(declaration ast.Declaration) {\n\tself.declarationList = append(self.declarationList, declaration)\n}\n\n\n\nfunc (self *_scope) hasLabel(name string) bool ", "output": "{\n\tfor _, label := range self.labels {\n\t\tif label == name {\n\t\t\treturn true\n\t\t}\n\t}\n\tif self.outer != nil && !self.inFunction {\n\t\treturn self.outer.hasLabel(name)\n\t}\n\treturn false\n}"} {"input": "package main\n\nimport \"sync\"\n\ntype mLocker struct {\n\tm map[string]*sync.Mutex\n\tmut sync.Mutex\n}\n\nfunc multiLocker() *mLocker {\n\treturn &mLocker{m: make(map[string]*sync.Mutex)}\n}\n\nfunc (l *mLocker) Lock(name string) {\n\tl.mut.Lock()\n\tmutex, ok := l.m[name]\n\tif !ok {\n\t\tmutex = new(sync.Mutex)\n\t\tl.m[name] = mutex\n\t}\n\tl.mut.Unlock()\n\tmutex.Lock()\n}\n\n\n\nfunc (l *mLocker) Unlock(name string) ", "output": "{\n\tl.mut.Lock()\n\tmutex := l.m[name]\n\tl.mut.Unlock()\n\tmutex.Unlock()\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/gofxh/blog/app\"\n\t\"github.com/gofxh/blog/app/log\"\n)\n\nconst (\n\tSETTING_FORMAT_TEXT int8 = 16 \n\tSETTING_FORMAT_JSON int8 = 26 \n)\n\nvar Settings map[string]*Setting = make(map[string]*Setting)\n\n\ntype Setting struct {\n\tName string `xorm:\"unique(setting-name)\"`\n\tValue string\n\tFormat int8 `xorm:\"not null\"`\n\tUserId int64 `xorm:\"unique(setting-name)\"`\n}\n\n\nfunc (s *Setting) GetString() string {\n\treturn s.Value\n}\n\n\nfunc (s *Setting) GetJson(value interface{}) error {\n\treturn json.Unmarshal([]byte(s.Value), value)\n}\n\n\n\n\n\nfunc SaveSettings(ss []*Setting) error {\n\tsess := app.Db.NewSession()\n\tdefer sess.Close()\n\tif err := sess.Begin(); err != nil {\n\t\tlog.Error(\"Db|SaveSettings|%s\", err.Error())\n\t\treturn err\n\t}\n\tfor _, s := range ss {\n\t\tsess.Insert(s)\n\t}\n\tif err := sess.Commit(); err != nil {\n\t\tlog.Error(\"Db|SaveSettings|%s\", err.Error())\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\nfunc ReadSettingsToGlobal() error {\n\tsettings := make([]*Setting, 0)\n\tif err := app.Db.Find(&settings); err != nil {\n\t\tlog.Error(\"Db|ReadSettingsToGlobal|%s\", err.Error())\n\t\treturn err\n\t}\n\tfor _, s := range settings {\n\t\tSettings[s.Name] = s\n\t}\n\treturn nil\n}\n\nfunc NewDefaultSetting(uid int64) []*Setting ", "output": "{\n\tm := make([]*Setting, 0)\n\tm = append(m, &Setting{\"theme\", \"default\", SETTING_FORMAT_TEXT, uid})\n\treturn m\n}"} {"input": "package geth\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\n\ntype Strings struct{ strs []string }\n\n\n\n\n\nfunc (s *Strings) Get(index int) (str string, _ error) {\n\tif index < 0 || index >= len(s.strs) {\n\t\treturn \"\", errors.New(\"index out of bounds\")\n\t}\n\treturn s.strs[index], nil\n}\n\n\nfunc (s *Strings) Set(index int, str string) error {\n\tif index < 0 || index >= len(s.strs) {\n\t\treturn errors.New(\"index out of bounds\")\n\t}\n\ts.strs[index] = str\n\treturn nil\n}\n\n\nfunc (s *Strings) String() string {\n\treturn fmt.Sprintf(\"%v\", s.strs)\n}\n\nfunc (s *Strings) Size() int ", "output": "{\n\treturn len(s.strs)\n}"} {"input": "package AuditTime\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t_ \"github.com/reactivego/rx\"\n)\n\nfunc Example_auditTime() {\n\tconst ms = time.Millisecond\n\n\tInterval(1 * ms).AuditTime(10 * ms).Take(5).Println()\n}\n\n\n\nfunc Example_auditTimeBursts() ", "output": "{\n\tconst ms = time.Millisecond\n\n\tburst20ms := func(i int) ObservableInt {\n\t\treturn IntervalInt(5 * ms).Take(4).MapInt(func(j int) int {\n\t\t\treturn i*100 + j\n\t\t})\n\t}\n\n\tfmt.Println(\"-1-\")\n\n\tIntervalInt(25 * ms).Take(4).MergeMapInt(burst20ms).AuditTime(21 * ms).Println()\n\n\tfmt.Println(\"-2-\")\n\n\tIntervalInt(50 * ms).Take(4).MergeMapInt(burst20ms).AuditTime(14 * ms).Println()\n}"} {"input": "package iris2\n\nimport (\n\t\"fmt\"\n)\n\ntype Mux struct {\n\trunning bool\n\tsources []<-chan interface{}\n\tselector chan Word\n\tdestination chan interface{}\n\terr chan error\n\n\tControl <-chan Word\n\tSelect chan<- Word\n\tDestination <-chan interface{}\n\tError <-chan error\n}\n\n\nfunc (this *Mux) AddSource(src <-chan interface{}) {\n\tthis.sources = append(this.sources, src)\n}\nfunc (this *Mux) body() {\n\tfor this.running {\n\t\tselect {\n\t\tcase index, more := <-this.selector:\n\t\t\tif more {\n\t\t\t\tif index >= Word(len(this.sources)) {\n\t\t\t\t\tthis.err <- fmt.Errorf(\"Selected non existent source: %d\", index)\n\t\t\t\t} else if index < 0 {\n\t\t\t\t\tthis.err <- fmt.Errorf(\"Select source %d is less than zero!\", index)\n\t\t\t\t} else {\n\t\t\t\t\tthis.destination <- <-this.sources[index]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (this *Mux) queryControl() {\n\t<-this.Control\n\tif err := this.shutdown(); err != nil {\n\t\tthis.err <- err\n\t}\n}\n\nfunc (this *Mux) shutdown() error {\n\tif !this.running {\n\t\treturn fmt.Errorf(\"Attempted to shutdown a multiplexer which isn't running\")\n\t} else {\n\t\tthis.running = false\n\t\tclose(this.selector)\n\t\treturn nil\n\t}\n}\n\nfunc (this *Mux) Startup() error {\n\tif this.running {\n\t\treturn fmt.Errorf(\"Given multiplexer is already running!\")\n\t} else {\n\t\tthis.running = true\n\t\tgo this.body()\n\t\tgo this.queryControl()\n\t\treturn nil\n\t}\n}\n\nfunc NewMux(control chan<- Word) *Mux ", "output": "{\n\tvar mux Mux\n\tmux.err = make(chan error)\n\tmux.destination = make(chan interface{})\n\tmux.selector = make(chan Word)\n\tmux.Error = mux.err\n\tmux.Destination = mux.destination\n\tmux.Control = control\n\tmux.Select = mux.selector\n\treturn &mux\n}"} {"input": "package echo\n\ntype (\n\tGroup struct {\n\t\techo Echo\n\t}\n)\n\nfunc (g *Group) Use(m ...Middleware) {\n\tfor _, h := range m {\n\t\tg.echo.middleware = append(g.echo.middleware, wrapMiddleware(h))\n\t}\n}\n\nfunc (g *Group) Connect(path string, h Handler) {\n\tg.echo.Connect(path, h)\n}\n\nfunc (g *Group) Delete(path string, h Handler) {\n\tg.echo.Delete(path, h)\n}\n\nfunc (g *Group) Get(path string, h Handler) {\n\tg.echo.Get(path, h)\n}\n\nfunc (g *Group) Head(path string, h Handler) {\n\tg.echo.Head(path, h)\n}\n\n\n\nfunc (g *Group) Patch(path string, h Handler) {\n\tg.echo.Patch(path, h)\n}\n\nfunc (g *Group) Post(path string, h Handler) {\n\tg.echo.Post(path, h)\n}\n\nfunc (g *Group) Put(path string, h Handler) {\n\tg.echo.Put(path, h)\n}\n\nfunc (g *Group) Trace(path string, h Handler) {\n\tg.echo.Trace(path, h)\n}\n\nfunc (g *Group) WebSocket(path string, h HandlerFunc) {\n\tg.echo.WebSocket(path, h)\n}\n\nfunc (g *Group) Static(path, root string) {\n\tg.echo.Static(path, root)\n}\n\nfunc (g *Group) ServeDir(path, root string) {\n\tg.echo.ServeDir(path, root)\n}\n\nfunc (g *Group) ServeFile(path, file string) {\n\tg.echo.ServeFile(path, file)\n}\n\nfunc (g *Group) Group(prefix string, m ...Middleware) *Group {\n\treturn g.echo.Group(prefix, m...)\n}\n\nfunc (g *Group) Options(path string, h Handler) ", "output": "{\n\tg.echo.Options(path, h)\n}"} {"input": "package insulin\n\nimport (\n\t\"math\"\n\n\t\"github.com/tidepool-org/platform/data\"\n\t\"github.com/tidepool-org/platform/structure\"\n)\n\nconst (\n\tConcentrationUnitsUnitsPerML = \"Units/mL\"\n\tConcentrationValueUnitsPerMLMaximum = 10000.0\n\tConcentrationValueUnitsPerMLMinimum = 0.0\n)\n\n\n\ntype Concentration struct {\n\tUnits *string `json:\"units,omitempty\" bson:\"units,omitempty\"`\n\tValue *float64 `json:\"value,omitempty\" bson:\"value,omitempty\"`\n}\n\nfunc ParseConcentration(parser structure.ObjectParser) *Concentration {\n\tif !parser.Exists() {\n\t\treturn nil\n\t}\n\tdatum := NewConcentration()\n\tparser.Parse(datum)\n\treturn datum\n}\n\nfunc NewConcentration() *Concentration {\n\treturn &Concentration{}\n}\n\nfunc (c *Concentration) Parse(parser structure.ObjectParser) {\n\tc.Units = parser.String(\"units\")\n\tc.Value = parser.Float64(\"value\")\n}\n\nfunc (c *Concentration) Validate(validator structure.Validator) {\n\tvalidator.String(\"units\", c.Units).Exists().OneOf(ConcentrationUnits()...)\n\tvalidator.Float64(\"value\", c.Value).Exists().InRange(ConcentrationValueRangeForUnits(c.Units))\n}\n\nfunc (c *Concentration) Normalize(normalizer data.Normalizer) {}\n\nfunc ConcentrationValueRangeForUnits(units *string) (float64, float64) {\n\tif units != nil {\n\t\tswitch *units {\n\t\tcase ConcentrationUnitsUnitsPerML:\n\t\t\treturn ConcentrationValueUnitsPerMLMinimum, ConcentrationValueUnitsPerMLMaximum\n\t\t}\n\t}\n\treturn -math.MaxFloat64, math.MaxFloat64\n}\n\nfunc ConcentrationUnits() []string ", "output": "{\n\treturn []string{\n\t\tConcentrationUnitsUnitsPerML,\n\t}\n}"} {"input": "package main\n\n\n\n\n\ntype Scope struct {\n\tparent *Scope \n\tentities map[string]*Decl\n}\n\nfunc NewScope(outer *Scope) *Scope {\n\ts := new(Scope)\n\ts.parent = outer\n\ts.entities = make(map[string]*Decl)\n\treturn s\n}\n\n\nfunc AdvanceScope(s *Scope) (*Scope, *Scope) {\n\tif len(s.entities) == 0 {\n\t\treturn s, s.parent\n\t}\n\treturn NewScope(s), s\n}\n\n\nfunc (s *Scope) addNamedDecl(d *Decl) *Decl {\n\treturn s.addDecl(d.Name, d)\n}\n\nfunc (s *Scope) addDecl(name string, d *Decl) *Decl {\n\tdecl, ok := s.entities[name]\n\tif !ok {\n\t\ts.entities[name] = d\n\t\treturn d\n\t}\n\treturn decl\n}\n\nfunc (s *Scope) replaceDecl(name string, d *Decl) {\n\ts.entities[name] = d\n}\n\n\n\nfunc (s *Scope) lookup(name string) *Decl {\n\tdecl, ok := s.entities[name]\n\tif !ok {\n\t\tif s.parent != nil {\n\t\t\treturn s.parent.lookup(name)\n\t\t} else {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn decl\n}\n\nfunc (s *Scope) mergeDecl(d *Decl) ", "output": "{\n\tdecl, ok := s.entities[d.Name]\n\tif !ok {\n\t\ts.entities[d.Name] = d\n\t} else {\n\t\tdecl := decl.DeepCopy()\n\t\tdecl.ExpandOrReplace(d)\n\t\ts.entities[d.Name] = decl\n\t}\n}"} {"input": "package client\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc _TestEncoding(t *testing.T) ", "output": "{\n\tdecrypted := &DecryptedPassword{\n\t\tKey: \"hello\",\n\t\tValue: \"world\",\n\t}\n\tencrypted := decrypted.SimpleEncrypt()\n\tt.Log(encrypted)\n\n\tdebyte := encrypted.SimpleDecrypt()\n\tt.Log(debyte)\n}"} {"input": "package classfile\n\nimport \"encoding/binary\"\n\ntype ClassReader struct {\n\tdata []byte \n}\n\nfunc (self *ClassReader) readUint8() uint8 {\n\tval := self.data[0]\n\tself.data = self.data[1:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint16() uint16 {\n\tval := binary.BigEndian.Uint16(self.data)\n\tself.data = self.data[2:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint32() uint32 {\n\tval := binary.BigEndian.Uint32(self.data)\n\tself.data = self.data[4:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint64() uint64 {\n\tval := binary.BigEndian.Uint64(self.data)\n\tself.data = self.data[8:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint16s() []uint16 {\n\tn := self.readUint16()\n\ts := make([]uint16, n)\n\tfor i := range s {\n\t\ts[i] = self.readUint16()\n\t}\n\treturn s\n}\n\n\n\nfunc (self *ClassReader) readBytes(n uint32) []byte ", "output": "{\n\tbytes := self.data[:n]\n\tself.data = self.data[n:]\n\treturn bytes\n}"} {"input": "package clang\n\n\n\nimport \"C\"\nimport (\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype IdxCXXClassDeclInfo struct {\n\tc C.CXIdxCXXClassDeclInfo\n}\n\n\n\nfunc (icxxcdi IdxCXXClassDeclInfo) Bases() []*IdxBaseClassInfo {\n\tvar s []*IdxBaseClassInfo\n\tgos_s := (*reflect.SliceHeader)(unsafe.Pointer(&s))\n\tgos_s.Cap = int(icxxcdi.c.numBases)\n\tgos_s.Len = int(icxxcdi.c.numBases)\n\tgos_s.Data = uintptr(unsafe.Pointer(icxxcdi.c.bases))\n\n\treturn s\n}\n\nfunc (icxxcdi IdxCXXClassDeclInfo) NumBases() uint32 {\n\treturn uint32(icxxcdi.c.numBases)\n}\n\nfunc (icxxcdi IdxCXXClassDeclInfo) DeclInfo() *IdxDeclInfo ", "output": "{\n\to := icxxcdi.c.declInfo\n\n\tvar gop_o *IdxDeclInfo\n\tif o != nil {\n\t\tgop_o = &IdxDeclInfo{o}\n\t}\n\n\treturn gop_o\n}"} {"input": "package proxy\n\nimport (\n\t\"net/http\"\n\t\"strings\"\n)\n\ntype createExecInterceptor struct{ proxy *Proxy }\n\nfunc (i *createExecInterceptor) InterceptRequest(r *http.Request) error {\n\toptions := jsonObject{}\n\tif err := unmarshalRequestBody(r, &options); err != nil {\n\t\treturn err\n\t}\n\n\tcontainer, err := inspectContainerInPath(i.proxy.client, r.URL.Path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, hasWeaveWait := container.Volumes[\"/w\"]; !hasWeaveWait {\n\t\treturn nil\n\t}\n\n\tcidrs, err := i.proxy.weaveCIDRs(container.HostConfig.NetworkMode, container.Config.Env)\n\tif err != nil {\n\t\tLog.Infof(\"Leaving container %s alone because %s\", container.ID, err)\n\t\treturn nil\n\t}\n\n\tcmd, err := options.StringArray(\"Cmd\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tLog.Infof(\"Exec in container %s with WEAVE_CIDR \\\"%s\\\"\", container.ID, strings.Join(cidrs, \" \"))\n\toptions[\"Cmd\"] = append(weaveWaitEntrypoint, cmd...)\n\n\treturn marshalRequestBody(r, options)\n}\n\n\n\nfunc (i *createExecInterceptor) InterceptResponse(r *http.Response) error ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nvar x, y, i = 0, 0, 1\n\nvar a [10] int\n\n\n\nvar b, c = 3, 4\n\nfunc g() bool {\n\treturn true\n}\n\nfunc h() bool {\n\treturn false\n}\n\nfunc main() {\n\ta[i] = x\n\n\tx = +x\n\tx = 23 + 3 * a[i]\n\tx = x <= f()\n\tx = ^b >> c\n\tx = g() || h()\n\tx = x == y+1 && c > 0\n}\n\nfunc f() int ", "output": "{\n\treturn 100\n}"} {"input": "package logger\n\nimport (\n\t\"io\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\nvar _ Logger = Logrus{}\nvar _ FieldLogger = Logrus{}\nvar _ Outable = Logrus{}\n\n\ntype Logrus struct {\n\tlogrus.FieldLogger\n}\n\n\n\nfunc (l Logrus) SetOutput(w io.Writer) {\n\tif lg, ok := l.FieldLogger.(Outable); ok {\n\t\tlg.SetOutput(w)\n\t}\n}\n\n\nfunc (l Logrus) WithField(s string, i interface{}) FieldLogger {\n\treturn Logrus{l.FieldLogger.WithField(s, i)}\n}\n\n\n\n\nfunc (l Logrus) WithFields(m map[string]interface{}) FieldLogger ", "output": "{\n\treturn Logrus{l.FieldLogger.WithFields(m)}\n}"} {"input": "package utils\n\nimport (\n\t\"bytes\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\tirc \"gopkg.in/irc.v3\"\n)\n\n\n\ntype TestClientServer struct {\n\tclient *bytes.Buffer\n\tserver *bytes.Buffer\n}\n\n\nfunc NewTestClientServer() *TestClientServer {\n\treturn &TestClientServer{\n\t\tclient: &bytes.Buffer{},\n\t\tserver: &bytes.Buffer{},\n\t}\n}\n\n\nfunc (cs *TestClientServer) Read(p []byte) (int, error) {\n\treturn cs.server.Read(p)\n}\n\n\nfunc (cs *TestClientServer) Write(p []byte) (int, error) {\n\treturn cs.client.Write(p)\n}\n\n\n\nfunc (cs *TestClientServer) SendServerLines(lines []string) {\n\tw := irc.NewWriter(cs.server)\n\n\tfor _, line := range lines {\n\t\tw.WriteMessage(irc.MustParseMessage(line))\n\t}\n}\n\n\n\n\nfunc (cs *TestClientServer) CheckLines(t *testing.T, expected []string) bool {\n\tok := true\n\n\tlines := strings.Split(cs.client.String(), \"\\r\\n\")\n\n\tvar line, clientLine string\n\tfor len(expected) > 0 && len(lines) > 0 {\n\t\tline, expected = expected[0], expected[1:]\n\t\tclientLine, lines = lines[0], lines[1:]\n\n\t\tok = ok && assert.Equal(t, line, clientLine)\n\t}\n\n\tok = ok && assert.Equal(t, 0, len(expected), \"Not enough lines: %s\", strings.Join(expected, \", \"))\n\tok = ok && assert.Equal(t, 0, len(lines), \"Extra non-empty lines: %s\", strings.Join(lines, \", \"))\n\n\treturn ok\n}\n\n\n\n\nfunc (cs *TestClientServer) Reset() ", "output": "{\n\tcs.client.Reset()\n\tcs.server.Reset()\n}"} {"input": "package metrics\n\n\n\n\nimport (\n\t\"errors\"\n\t\"net/url\"\n\tgolangswaggerpaths \"path\"\n)\n\n\ntype GetMetricsURL struct {\n\t_basePath string\n}\n\n\n\n\nfunc (o *GetMetricsURL) WithBasePath(bp string) *GetMetricsURL {\n\to.SetBasePath(bp)\n\treturn o\n}\n\n\n\n\nfunc (o *GetMetricsURL) SetBasePath(bp string) {\n\to._basePath = bp\n}\n\n\nfunc (o *GetMetricsURL) Build() (*url.URL, error) {\n\tvar result url.URL\n\n\tvar _path = \"/metrics/\"\n\n\t_basePath := o._basePath\n\tif _basePath == \"\" {\n\t\t_basePath = \"/v1\"\n\t}\n\tresult.Path = golangswaggerpaths.Join(_basePath, _path)\n\n\treturn &result, nil\n}\n\n\nfunc (o *GetMetricsURL) Must(u *url.URL, err error) *url.URL {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif u == nil {\n\t\tpanic(\"url can't be nil\")\n\t}\n\treturn u\n}\n\n\nfunc (o *GetMetricsURL) String() string {\n\treturn o.Must(o.Build()).String()\n}\n\n\n\n\n\nfunc (o *GetMetricsURL) StringFull(scheme, host string) string {\n\treturn o.Must(o.BuildFull(scheme, host)).String()\n}\n\nfunc (o *GetMetricsURL) BuildFull(scheme, host string) (*url.URL, error) ", "output": "{\n\tif scheme == \"\" {\n\t\treturn nil, errors.New(\"scheme is required for a full url on GetMetricsURL\")\n\t}\n\tif host == \"\" {\n\t\treturn nil, errors.New(\"host is required for a full url on GetMetricsURL\")\n\t}\n\n\tbase, err := o.Build()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbase.Scheme = scheme\n\tbase.Host = host\n\treturn base, nil\n}"} {"input": "package route\n\nimport (\n\t\"io\"\n\t\"net/http\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nvar ()\n\n\ntype Route struct {\n\tPath string\n\tSystem int\n\tS0 NullRoute\n\tS1 StringRoute\n\tS2 ControllerRoute\n\tS3 FilesystemRoute\n\tS4 FunctionRoute\n}\n\n\nfunc NewRoute(path string, system int) Route {\n\treturn Route{path, system, NullRoute{}, StringRoute{}, ControllerRoute{}, FilesystemRoute{}, FunctionRoute{}}\n}\n\n\n\n\n\nfunc ValidStringRoute(str string) bool {\n\trouteStringRegexp := `^\\/([a-zA-Z0-9](\\/)*)*\\s(null|str .*|fs .*)$`\n\tr, _ := regexp.Compile(routeStringRegexp)\n\tif r.MatchString(str) {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (r *Route) Read(w http.ResponseWriter, req *http.Request) ", "output": "{\n\tresult := \"\"\n\tswitch r.System {\n\tcase 0:\n\t\tresult = \"\"\n\tcase 1:\n\t\tresult = r.S1.String\n\tcase 2:\n\tcase 3:\n\t\tresult = r.S3.FileContent\n\tcase 4:\n\t\tresult = r.S4.Function()\n\t}\n\tio.Copy(w, strings.NewReader(result))\n}"} {"input": "package memfs\n\nimport (\n\t\"io\"\n\t\"testing\"\n\n\t\"gopkg.in/src-d/go-billy.v4\"\n\t\"gopkg.in/src-d/go-billy.v4/test\"\n\n\t. \"gopkg.in/check.v1\"\n)\n\n\n\ntype MemorySuite struct {\n\ttest.FilesystemSuite\n\tpath string\n}\n\nvar _ = Suite(&MemorySuite{})\n\nfunc (s *MemorySuite) SetUpTest(c *C) {\n\ts.FilesystemSuite = test.NewFilesystemSuite(New())\n}\n\nfunc (s *MemorySuite) TestCapabilities(c *C) {\n\t_, ok := s.FS.(billy.Capable)\n\tc.Assert(ok, Equals, true)\n\n\tcaps := billy.Capabilities(s.FS)\n\tc.Assert(caps, Equals, billy.DefaultCapabilities&^billy.LockCapability)\n}\n\nfunc (s *MemorySuite) TestNegativeOffsets(c *C) {\n\tf, err := s.FS.Create(\"negative\")\n\tc.Assert(err, IsNil)\n\n\tbuf := make([]byte, 100)\n\t_, err = f.ReadAt(buf, -100)\n\tc.Assert(err, ErrorMatches, \"readat negative: negative offset\")\n\n\t_, err = f.Seek(-100, io.SeekCurrent)\n\tc.Assert(err, IsNil)\n\t_, err = f.Write(buf)\n\tc.Assert(err, ErrorMatches, \"writeat negative: negative offset\")\n}\n\nfunc Test(t *testing.T) ", "output": "{ TestingT(t) }"} {"input": "package server\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\n\n\nfunc TestHandleHealth(t *testing.T) ", "output": "{\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\thttpServer, server := newTestServer(ctx, t, nil)\n\tdefer httpServer.Close()\n\n\trr := httptest.NewRecorder()\n\tserver.handleHealth(rr, httptest.NewRequest(\"GET\", \"/healthz\", nil))\n\tif rr.Code != http.StatusOK {\n\t\tt.Errorf(\"expected 200 got %d\", rr.Code)\n\t}\n\n}"} {"input": "package notmain\n\nimport (\n\t\"testing\"\n\n\t\"github.com/letsencrypt/boulder/test\"\n)\n\nfunc TestLineValidAccepts(t *testing.T) {\n\terr := lineValid(\"2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 boulder-wfe[1595]: kKG6cwA Caught SIGTERM\")\n\ttest.AssertNotError(t, err, \"errored on valid checksum\")\n}\n\n\n\nfunc TestLineValidRejectsNotAChecksum(t *testing.T) {\n\terr := lineValid(\"2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 boulder-wfe[1595]: xxxx Caught SIGTERM\")\n\ttest.AssertError(t, err, \"didn't error on invalid checksum\")\n\ttest.AssertErrorIs(t, err, errInvalidChecksum)\n}\n\nfunc TestLineValidNonOurobouros(t *testing.T) {\n\terr := lineValid(\"2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 boulder-wfe[1595]: xxxxxxx Caught SIGTERM\")\n\ttest.AssertError(t, err, \"didn't error on invalid checksum\")\n\n\tselfOutput := \"2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 log-validator[1337]: xxxxxxx \" + err.Error()\n\terr2 := lineValid(selfOutput)\n\ttest.AssertNotError(t, err2, \"expected no error when feeding lineValid's error output into itself\")\n}\n\nfunc TestLineValidRejects(t *testing.T) ", "output": "{\n\terr := lineValid(\"2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 boulder-wfe[1595]: xxxxxxx Caught SIGTERM\")\n\ttest.AssertError(t, err, \"didn't error on invalid checksum\")\n}"} {"input": "package etl\n\nimport \"strings\"\n\n\n\nfunc Transform(input in) out ", "output": "{\n\tresult := make(out)\n\tfor score, letters := range input {\n\t\tfor _, letter := range letters {\n\t\t\tresult[strings.ToLower(letter)] = score\n\t\t}\n\t}\n\treturn result\n}"} {"input": "package engine\n\nimport (\n\t\"time\"\n\n\t\"github.com/aws/amazon-ecs-agent/agent/api\"\n)\n\n\n\ntype impossibleTransitionError struct {\n\tstate api.ContainerStatus\n}\n\nfunc (err *impossibleTransitionError) Error() string {\n\treturn \"Cannot transition to \" + err.state.String()\n}\n\n\ntype DockerTimeoutError struct {\n\tduration time.Duration\n\ttransition string\n}\n\nfunc (err *DockerTimeoutError) Error() string {\n\treturn \"Could not transition to \" + err.transition + \"; timed out after waiting \" + err.duration.String()\n}\nfunc (err *DockerTimeoutError) ErrorName() string { return \"DockerTimeoutError\" }\n\ntype ContainerVanishedError struct{}\n\nfunc (err ContainerVanishedError) Error() string { return \"No container matching saved ID found\" }\nfunc (err ContainerVanishedError) ErrorName() string { return \"ContainerVanishedError\" }\n\ntype CannotXContainerError struct {\n\ttransition string\n\tmsg string\n}\n\nfunc (err CannotXContainerError) Error() string { return err.msg }\nfunc (err CannotXContainerError) ErrorName() string {\n\treturn \"Cannot\" + err.transition + \"ContainerError\"\n}\n\ntype OutOfMemoryError struct{}\n\nfunc (err OutOfMemoryError) Error() string { return \"Container killed due to memory usage\" }\nfunc (err OutOfMemoryError) ErrorName() string { return \"OutOfMemoryError\" }\n\n\ntype DockerStateError struct {\n\tdockerError string\n\tname string\n}\n\nfunc NewDockerStateError(err string) DockerStateError {\n\treturn DockerStateError{\n\t\tdockerError: err,\n\t\tname: \"DockerStateError\",\n\t}\n}\n\nfunc (err DockerStateError) Error() string {\n\treturn err.dockerError\n}\nfunc (err DockerStateError) ErrorName() string {\n\treturn err.name\n}\n\nfunc (err *impossibleTransitionError) ErrorName() string ", "output": "{ return \"ImpossibleStateTransitionError\" }"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/wrouesnel/tailio\"\n\t\"os\"\n)\n\nfunc args2config() (tailio.Config, int64) {\n\tconfig := tailio.Config{Follow: true}\n\tn := int64(0)\n\tmaxlinesize := int(0)\n\tflag.Int64Var(&n, \"n\", 0, \"tail from the last Nth location\")\n\tflag.IntVar(&maxlinesize, \"max\", 0, \"max line size\")\n\tflag.BoolVar(&config.Follow, \"f\", false, \"wait for additional data to be appended to the file\")\n\tflag.BoolVar(&config.ReOpen, \"F\", false, \"follow, and track file rename/rotation\")\n\tflag.BoolVar(&config.Poll, \"p\", false, \"use polling, instead of inotify\")\n\tflag.Parse()\n\tif config.ReOpen {\n\t\tconfig.Follow = true\n\t}\n\tconfig.MaxLineSize = maxlinesize\n\treturn config, n\n}\n\nfunc main() {\n\tconfig, n := args2config()\n\tif flag.NFlag() < 1 {\n\t\tfmt.Println(\"need one or more files as arguments\")\n\t\tos.Exit(1)\n\t}\n\n\tif n != 0 {\n\t\tconfig.Location = &tailio.SeekInfo{-n, os.SEEK_END}\n\t}\n\n\tdone := make(chan bool)\n\tfor _, filename := range flag.Args() {\n\t\tgo tailFile(filename, config, done)\n\t}\n\n\tfor _, _ = range flag.Args() {\n\t\t<-done\n\t}\n}\n\n\n\nfunc tailFile(filename string, config tailio.Config, done chan bool) ", "output": "{\n\tdefer func() { done <- true }()\n\tt, err := tailio.TailFile(filename, config)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tfor line := range t.Lines {\n\t\tfmt.Println(line.Text)\n\t}\n\terr = t.Wait()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"regexp\"\n\n\t\"github.com/gin-gonic/gin\"\n\t\"net/http\"\n)\n\n\nfunc EmailHandler(c *gin.Context) {\n\temail := c.Query(\"email\")\n\tif (ValidateEmail(email)) {\n\t\tc.JSON(http.StatusOK, gin.H{\"email\": email, \"valid\": true, \"message\": \"Email is Validated\"})\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"email\": email, \"valid\": false, \"message\": \"Email address is Invalid\"})\n}\n\n\n\n\nfunc ValidateEmail(email string) bool ", "output": "{\n\tRe := regexp.MustCompile(`^[a-z0-9._%+\\-]+@[a-z0-9.\\-]+\\.[a-z]{2,3}$`)\n\treturn Re.MatchString(email)\n}"} {"input": "package assembler\n\nimport (\n\t\"log\"\n\t\"golang.org/x/sys/cpu\"\n)\n\nvar useAVX2, useAVX, useSSE4 bool\n\nfunc init() {\n\n\tuseSSE4 = cpu.X86.HasSSE41\n\tuseAVX = cpu.X86.HasAVX\n\tuseAVX2 = cpu.X86.HasAVX2\n\n\tInit(true)\n\tlog.Printf(\"SSE4: %v\", useSSE4)\n\tlog.Printf(\"AVX: %v\", useAVX)\n\tlog.Printf(\"AVX2: %v\", useAVX2)\n\n}\n\nvar logging bool = true\n\nvar Isamax func(x []float32) int\nvar Ismax func(x []float32) int\n\n\n\nfunc Init(optimize bool) ", "output": "{\n\tif optimize {\n\t\tIsamax = isamax_asm\n\t\tIsmax = ismax_asm\n\t} else {\n\t\tIsamax = isamax\n\t\tIsmax = ismax\n\t}\n}"} {"input": "package opts\n\n\ntype CreateOption func(*CreateConfig)\n\n\n\ntype CreateConfig struct {\n\tOptions map[string]string\n\tLabels map[string]string\n\tReference string\n}\n\n\n\nfunc WithCreateLabels(labels map[string]string) CreateOption {\n\treturn func(cfg *CreateConfig) {\n\t\tcfg.Labels = labels\n\t}\n}\n\n\n\nfunc WithCreateOptions(opts map[string]string) CreateOption {\n\treturn func(cfg *CreateConfig) {\n\t\tcfg.Options = opts\n\t}\n}\n\n\n\n\nfunc WithCreateReference(ref string) CreateOption {\n\treturn func(cfg *CreateConfig) {\n\t\tcfg.Reference = ref\n\t}\n}\n\n\n\ntype GetConfig struct {\n\tDriver string\n\tReference string\n\tResolveStatus bool\n}\n\n\ntype GetOption func(*GetConfig)\n\n\n\n\n\nfunc WithGetDriver(name string) GetOption {\n\treturn func(o *GetConfig) {\n\t\to.Driver = name\n\t}\n}\n\n\n\n\n\n\n\nfunc WithGetResolveStatus(cfg *GetConfig) {\n\tcfg.ResolveStatus = true\n}\n\n\ntype RemoveConfig struct {\n\tPurgeOnError bool\n}\n\n\ntype RemoveOption func(*RemoveConfig)\n\n\n\n\nfunc WithPurgeOnError(b bool) RemoveOption {\n\treturn func(o *RemoveConfig) {\n\t\to.PurgeOnError = b\n\t}\n}\n\nfunc WithGetReference(ref string) GetOption ", "output": "{\n\treturn func(o *GetConfig) {\n\t\to.Reference = ref\n\t}\n}"} {"input": "package testhelpers\n\nimport \"github.com/go-kit/kit/metrics\"\n\n\ntype CollectingCounter struct {\n\tCounterValue float64\n\tLastLabelValues []string\n}\n\n\nfunc (c *CollectingCounter) With(labelValues ...string) metrics.Counter {\n\tc.LastLabelValues = labelValues\n\treturn c\n}\n\n\nfunc (c *CollectingCounter) Add(delta float64) {\n\tc.CounterValue += delta\n}\n\n\ntype CollectingGauge struct {\n\tGaugeValue float64\n\tLastLabelValues []string\n}\n\n\nfunc (g *CollectingGauge) With(labelValues ...string) metrics.Gauge {\n\tg.LastLabelValues = labelValues\n\treturn g\n}\n\n\nfunc (g *CollectingGauge) Set(value float64) {\n\tg.GaugeValue = value\n}\n\n\nfunc (g *CollectingGauge) Add(delta float64) {\n\tg.GaugeValue = delta\n}\n\n\ntype CollectingHealthCheckMetrics struct {\n\tGauge *CollectingGauge\n}\n\n\nfunc (m *CollectingHealthCheckMetrics) BackendServerUpGauge() metrics.Gauge {\n\treturn m.Gauge\n}\n\n\n\n\nfunc NewCollectingHealthCheckMetrics() *CollectingHealthCheckMetrics ", "output": "{\n\treturn &CollectingHealthCheckMetrics{&CollectingGauge{}}\n}"} {"input": "package nntptest\n\nimport \"bytes\"\n\n\n\ntype ResponseRecorder struct {\n\tCode int\n\tBody *bytes.Buffer\n\twroteHeader bool\n}\n\n\nfunc NewRecorder() *ResponseRecorder {\n\treturn &ResponseRecorder{\n\t\tBody: new(bytes.Buffer),\n\t\tCode: 403,\n\t}\n}\n\n\n\n\n\nfunc (rw *ResponseRecorder) WriteHeader(code int) {\n\tif !rw.wroteHeader {\n\t\trw.Code = code\n\t}\n\trw.wroteHeader = true\n}\n\nfunc (rw *ResponseRecorder) Write(buf []byte) (int, error) ", "output": "{\n\tif !rw.wroteHeader {\n\t\trw.WriteHeader(403)\n\t\treturn 0, nil\n\t}\n\tif rw.Body != nil {\n\t\trw.Body.Write(buf)\n\t}\n\treturn len(buf), nil\n}"} {"input": "package cfg_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/walle/cfg\"\n)\n\nvar myConfig = &MyConfig{\n\tAnswer: 42,\n\tPi: 3.14,\n\tIsActive: true,\n\tQuotes: \"Alea iacta est\\nEt tu, Brute?\",\n\tunexported: \"foo\",\n\tNotUsed: \"bar\",\n}\n\nvar myConfigWithEmpty = &MyConfig{\n\tAnswer: 42,\n\tIsActive: false,\n}\n\nconst myConfigEncoded = `Answer = 42\nPi = 3.14\nis_active = true\nquotes = Alea iacta est\\nEt tu, Brute?\n`\n\nconst myConfigEncodedWithEmpty = `Answer = 42\nPi = 0\nis_active = false\nquotes = \n`\n\nfunc Test_Marshal(t *testing.T) {\n\tdata, err := cfg.Marshal(myConfig)\n\tif err != nil {\n\t\tt.Errorf(\"Error encoding data: %s\\n\", err)\n\t}\n\n\tif string(data) != myConfigEncoded {\n\t\tt.Errorf(\"Expected %q got %q\\n\", myConfigEncoded, string(data))\n\t}\n}\n\nfunc Test_MarshalWithEmpty(t *testing.T) {\n\tdata, err := cfg.Marshal(myConfigWithEmpty)\n\tif err != nil {\n\t\tt.Errorf(\"Error encoding data: %s\\n\", err)\n\t}\n\n\tif string(data) != myConfigEncodedWithEmpty {\n\t\tt.Errorf(\"Expected %q got %q\\n\", myConfigEncodedWithEmpty, string(data))\n\t}\n}\n\nfunc Test_MarshalNotStruct(t *testing.T) {\n\ti := 0\n\t_, err := cfg.Marshal(i)\n\tif err == nil {\n\t\tt.Errorf(\"Did not get error when trying to marshal int\\n\")\n\t}\n}\n\n\n\nfunc Test_MarshalToConfig(t *testing.T) ", "output": "{\n\tconfig, err := cfg.MarshalToConfig(myConfig)\n\tif err != nil {\n\t\tt.Errorf(\"Error encoding data: %s\\n\", err)\n\t}\n\n\tanswer, _ := config.GetInt(\"Answer\")\n\tif answer != 42 {\n\t\tt.Errorf(\"Expected %v, got %v\\n\", 42, answer)\n\t}\n\n\tpi, _ := config.GetFloat(\"Pi\")\n\tif pi != 3.14 {\n\t\tt.Errorf(\"Expected %v, got %v\\n\", 3.14, pi)\n\t}\n\n\tisActive, _ := config.GetBool(\"is_active\")\n\tif isActive != true {\n\t\tt.Errorf(\"Expected %v, got %v\\n\", true, isActive)\n\t}\n\n\tquotes, _ := config.GetString(\"quotes\")\n\tq := \"Alea iacta est\\nEt tu, Brute?\"\n\tif quotes != q {\n\t\tt.Errorf(\"Expected %q, got %q\\n\", q, quotes)\n\t}\n}"} {"input": "package configparser\n\nimport (\n\t\"github.com/bigkevmcd/go-configparser/chainmap\"\n\n\t\"strings\"\n)\n\nfunc (p *ConfigParser) getInterpolated(section, option string, c *chainmap.ChainMap) (string, error) {\n\tval, err := p.Get(section, option)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn p.interpolate(val, c), nil\n}\n\n\n\n\n\nfunc (p *ConfigParser) GetInterpolated(section, option string) (string, error) {\n\to, err := p.Items(section)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tc := chainmap.New(chainmap.Dict(p.Defaults()), chainmap.Dict(o))\n\treturn p.getInterpolated(section, option, c)\n}\n\n\n\n\n\n\n\nfunc (p *ConfigParser) GetInterpolatedWithVars(section, option string, v Dict) (string, error) {\n\to, err := p.Items(section)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tc := chainmap.New(chainmap.Dict(p.Defaults()), chainmap.Dict(o), chainmap.Dict(v))\n\treturn p.getInterpolated(section, option, c)\n\n}\n\n\n\n\n\n\n\nfunc (p *ConfigParser) ItemsWithDefaultsInterpolated(section string) (Dict, error) {\n\ts, err := p.ItemsWithDefaults(section)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor k, v := range s {\n\t\tv, err = p.GetInterpolated(section, k)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ts[k] = v\n\t}\n\treturn s, nil\n}\n\nfunc (p *ConfigParser) interpolate(value string, options *chainmap.ChainMap) string ", "output": "{\n\n\tfor i := 0; i < maxInterpolationDepth; i++ {\n\t\tif strings.Contains(value, \"%(\") {\n\t\t\tvalue = interpolater.ReplaceAllStringFunc(value, func(m string) string {\n\t\t\t\tmatch := interpolater.FindAllStringSubmatch(m, 1)[0][1]\n\t\t\t\treplacement := options.Get(match)\n\t\t\t\treturn replacement\n\t\t\t})\n\t\t}\n\t}\n\treturn value\n}"} {"input": "package engine\n\nimport (\n\tvtrpcpb \"vitess.io/vitess/go/vt/proto/vtrpc\"\n\t\"vitess.io/vitess/go/vt/vterrors\"\n\n\t\"vitess.io/vitess/go/sqltypes\"\n\t\"vitess.io/vitess/go/vt/proto/query\"\n)\n\nvar _ Primitive = (*UpdateTarget)(nil)\n\n\ntype UpdateTarget struct {\n\tTarget string\n\n\tnoInputs\n\n\tnoTxNeeded\n}\n\nfunc (updTarget *UpdateTarget) description() PrimitiveDescription {\n\treturn PrimitiveDescription{\n\t\tOperatorType: \"UpdateTarget\",\n\t\tOther: map[string]interface{}{\"target\": updTarget.Target},\n\t}\n}\n\n\nfunc (updTarget *UpdateTarget) RouteType() string {\n\treturn \"UpdateTarget\"\n}\n\n\nfunc (updTarget *UpdateTarget) GetKeyspaceName() string {\n\treturn updTarget.Target\n}\n\n\nfunc (updTarget *UpdateTarget) GetTableName() string {\n\treturn \"\"\n}\n\n\nfunc (updTarget *UpdateTarget) TryExecute(vcursor VCursor, bindVars map[string]*query.BindVariable, wantfields bool) (*sqltypes.Result, error) {\n\terr := vcursor.Session().SetTarget(updTarget.Target)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &sqltypes.Result{}, nil\n}\n\n\nfunc (updTarget *UpdateTarget) TryStreamExecute(vcursor VCursor, bindVars map[string]*query.BindVariable, wantfields bool, callback func(*sqltypes.Result) error) error {\n\tresult, err := updTarget.TryExecute(vcursor, bindVars, wantfields)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn callback(result)\n}\n\n\n\n\nfunc (updTarget *UpdateTarget) GetFields(vcursor VCursor, bindVars map[string]*query.BindVariable) (*sqltypes.Result, error) ", "output": "{\n\treturn nil, vterrors.Errorf(vtrpcpb.Code_INTERNAL, \"[BUG] GetFields not reachable for use statement\")\n}"} {"input": "package timeutil\n\nimport (\n\t\"time\"\n\t\"unsafe\"\n\n\t\"github.com/leekchan/timeutil\"\n\t\"github.com/pkg/errors\"\n)\n\n\n\n\n\n\n\nimport \"C\"\n\n\n\n\n\nfunc Strptime(layout, value string) (time.Time, error) {\n\tcLayout := C.CString(layout)\n\tdefer C.free(unsafe.Pointer(cLayout))\n\tcValue := C.CString(value)\n\tdefer C.free(unsafe.Pointer(cValue))\n\n\tvar cTime C.struct_tm\n\tif _, err := C.strptime(cValue, cLayout, &cTime); err != nil {\n\t\treturn time.Time{}, errors.Wrapf(err, \"could not parse %s as %s\", value, layout)\n\t}\n\treturn time.Date(\n\t\tint(cTime.tm_year)+1900,\n\t\ttime.Month(cTime.tm_mon+1),\n\t\tint(cTime.tm_mday),\n\t\tint(cTime.tm_hour),\n\t\tint(cTime.tm_min),\n\t\tint(cTime.tm_sec),\n\t\t0,\n\t\ttime.FixedZone(\"\", int(cTime.tm_gmtoff)),\n\t), nil\n}\n\nfunc Strftime(t time.Time, layout string) (string, error) ", "output": "{\n\treturn timeutil.Strftime(&t, layout), nil\n}"} {"input": "package http\n\nimport (\n\t\"go-common/app/admin/main/activity/model\"\n\tbm \"go-common/library/net/http/blademaster\"\n)\n\nfunc listInfosAll(c *bm.Context) {\n\targ := new(model.ListSub)\n\tif err := c.Bind(arg); err != nil {\n\t\treturn\n\t}\n\tc.JSON(actSrv.SubjectList(c, arg))\n}\n\nfunc videoList(c *bm.Context) {\n\tc.JSON(actSrv.VideoList(c))\n}\n\nfunc addActSubject(c *bm.Context) {\n\targ := new(model.AddList)\n\tif err := c.Bind(arg); err != nil {\n\t\treturn\n\t}\n\tc.JSON(actSrv.AddActSubject(c, arg))\n}\n\n\n\nfunc subPro(c *bm.Context) {\n\ttype subStr struct {\n\t\tSid int64 `form:\"sid\" validate:\"min=1\"`\n\t}\n\targ := new(subStr)\n\tif err := c.Bind(arg); err != nil {\n\t\treturn\n\t}\n\tc.JSON(actSrv.SubProtocol(c, arg.Sid))\n}\n\nfunc timeConf(c *bm.Context) {\n\ttype subStr struct {\n\t\tSid int64 `form:\"sid\" validate:\"required\"`\n\t}\n\targ := new(subStr)\n\tif err := c.Bind(arg); err != nil {\n\t\treturn\n\t}\n\tc.JSON(actSrv.TimeConf(c, arg.Sid))\n}\n\nfunc article(c *bm.Context) {\n\ttype subStr struct {\n\t\tAids []int64 `form:\"aids,split\" validate:\"min=1,required\"`\n\t}\n\targ := new(subStr)\n\tif err := c.Bind(arg); err != nil {\n\t\treturn\n\t}\n\tc.JSON(actSrv.GetArticleMetas(c, arg.Aids))\n}\n\nfunc updateInfoAll(c *bm.Context) ", "output": "{\n\ttype upStr struct {\n\t\tmodel.AddList\n\t\tSid int64 `form:\"sid\" validate:\"min=1\"`\n\t}\n\targ := new(upStr)\n\tif err := c.Bind(arg); err != nil {\n\t\treturn\n\t}\n\tc.JSON(actSrv.UpActSubject(c, &arg.AddList, arg.Sid))\n}"} {"input": "package timekeeper\n\nimport \"time\"\n\n\n\n\n\ntype TimeKeeper interface {\n\tAfter(d time.Duration) <-chan time.Time\n\tSleep(d time.Duration)\n\tNow() time.Time\n}\n\n\ntype realTime struct{}\n\nvar rt realTime\n\n\nfunc (t *realTime) After(d time.Duration) <-chan time.Time {\n\treturn time.After(d)\n}\n\n\n\n\n\nfunc RealTime() TimeKeeper {\n\treturn &rt\n}\n\n\nfunc (t *realTime) Now() time.Time {\n\treturn time.Now()\n}\n\nfunc (t *realTime) Sleep(d time.Duration) ", "output": "{\n\ttime.Sleep(d)\n}"} {"input": "package fuse\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"golang.org/x/net/context\"\n)\n\n\ntype MountConfig struct {\n\tOpContext context.Context\n\n\tFSName string\n\n\tReadOnly bool\n\n\tErrorLogger *log.Logger\n\n\tDebugLogger *log.Logger\n\n\tDisableWritebackCaching bool\n\n\tEnableVnodeCaching bool\n\n\tOptions map[string]string\n}\n\n\n\nfunc (c *MountConfig) toMap() (opts map[string]string) {\n\tisDarwin := runtime.GOOS == \"darwin\"\n\topts = make(map[string]string)\n\n\topts[\"default_permissions\"] = \"\"\n\n\tfsname := c.FSName\n\tif runtime.GOOS == \"linux\" && fsname == \"\" {\n\t\tfsname = \"some_fuse_file_system\"\n\t}\n\n\tif fsname != \"\" {\n\t\topts[\"fsname\"] = fsname\n\t}\n\n\tif c.ReadOnly {\n\t\topts[\"ro\"] = \"\"\n\t}\n\n\tif isDarwin && !c.EnableVnodeCaching {\n\t\topts[\"novncache\"] = \"\"\n\t}\n\n\tif isDarwin {\n\t\topts[\"noappledouble\"] = \"\"\n\t}\n\n\tfor k, v := range c.Options {\n\t\topts[k] = v\n\t}\n\n\treturn\n}\n\n\n\n\nfunc (c *MountConfig) toOptionsString() string {\n\tvar components []string\n\tfor k, v := range c.toMap() {\n\t\tk = escapeOptionsKey(k)\n\n\t\tcomponent := k\n\t\tif v != \"\" {\n\t\t\tcomponent = fmt.Sprintf(\"%s=%s\", k, v)\n\t\t}\n\n\t\tcomponents = append(components, component)\n\t}\n\n\treturn strings.Join(components, \",\")\n}\n\nfunc escapeOptionsKey(s string) (res string) ", "output": "{\n\tres = s\n\tres = strings.Replace(res, `\\`, `\\\\`, -1)\n\tres = strings.Replace(res, `,`, `\\,`, -1)\n\treturn\n}"} {"input": "package jobs\n\nimport (\n\t\"github.com/simplemvc/gocorelib/cron\"\n\t\"github.com/simplemvc/gocorelib/revel\"\n\t\"strings\"\n\t\"time\"\n)\n\n\n\n\n\n\ntype Func func()\n\nfunc (r Func) Run() { r() }\n\nfunc Schedule(spec string, job cron.Job) {\n\tif strings.HasPrefix(spec, \"cron.\") {\n\t\tconfSpec, found := revel.Config.String(spec)\n\t\tif !found {\n\t\t\tpanic(\"Cron spec not found: \" + spec)\n\t\t}\n\t\tspec = confSpec\n\t}\n\tMainCron.Schedule(cron.Parse(spec), New(job))\n}\n\n\n\n\nfunc Every(duration time.Duration, job cron.Job) {\n\tMainCron.Schedule(cron.Every(duration), New(job))\n}\n\n\nfunc Now(job cron.Job) {\n\tgo New(job).Run()\n}\n\n\n\n\nfunc In(duration time.Duration, job cron.Job) ", "output": "{\n\tgo func() {\n\t\ttime.Sleep(duration)\n\t\tNew(job).Run()\n\t}()\n}"} {"input": "package net\n\nimport (\n\t\"net/url\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\ntype Endpoint interface {\n\tHostName() string\n\tPort() int\n}\n\ntype defaultEndpoint struct {\n\thostname string\n\tport int\n}\n\n\nfunc (e defaultEndpoint) Port() int {\n\treturn e.port\n}\n\nfunc NewEndpoint(hostname string, port int) Endpoint {\n\treturn defaultEndpoint{hostname, port}\n}\n\nfunc FromUrl(u url.URL) Endpoint {\n\tparts := strings.Split(u.Host, \":\")\n\tif len(parts) != 2 {\n\t\treturn nil\n\t}\n\tport, _ := strconv.Atoi(parts[1])\n\treturn NewEndpoint(parts[0], port)\n}\n\nfunc (e defaultEndpoint) HostName() string ", "output": "{\n\treturn e.hostname\n}"} {"input": "package srpc\n\nimport (\n\t\"crypto/tls\"\n\n\t\"github.com/Symantec/Dominator/lib/connpool\"\n)\n\nfunc newClientResource(network, address string) *ClientResource {\n\tclientResource := &ClientResource{\n\t\tnetwork: network,\n\t\taddress: address,\n\t}\n\tclientResource.privateClientResource.clientResource = clientResource\n\trp := connpool.GetResourcePool()\n\tclientResource.resource = rp.Create(&clientResource.privateClientResource)\n\treturn clientResource\n}\n\n\n\nfunc (client *Client) put() {\n\tclient.resource.resource.Put()\n\tif client.resource.inUse {\n\t\tclientMetricsMutex.Lock()\n\t\tnumInUseClientConnections--\n\t\tclientMetricsMutex.Unlock()\n\t\tclient.resource.inUse = false\n\t}\n}\n\nfunc (pcr *privateClientResource) Allocate() error {\n\tcr := pcr.clientResource\n\tclient, err := dialHTTP(cr.network, cr.address, pcr.tlsConfig, pcr.dialer)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcr.client = client\n\tclient.resource = cr\n\treturn nil\n}\n\nfunc (pcr *privateClientResource) Release() error {\n\tcr := pcr.clientResource\n\terr := cr.client.conn.Close()\n\tcr.client = nil\n\treturn err\n}\n\nfunc (cr *ClientResource) getHTTP(tlsConfig *tls.Config,\n\tcancelChannel <-chan struct{}, dialer connpool.Dialer) (*Client, error) ", "output": "{\n\tcr.privateClientResource.tlsConfig = tlsConfig\n\tcr.privateClientResource.dialer = dialer\n\tif err := cr.resource.Get(cancelChannel); err != nil {\n\t\treturn nil, err\n\t}\n\tcr.inUse = true\n\tclientMetricsMutex.Lock()\n\tnumInUseClientConnections++\n\tclientMetricsMutex.Unlock()\n\treturn cr.client, nil\n}"} {"input": "package monkit\n\nimport \"syscall\"\n\n\n\nfunc isErrnoError(err error) bool ", "output": "{\n\t_, ok := err.(syscall.Errno)\n\treturn ok\n}"} {"input": "package iso20022\n\n\ntype SettlementStatus10Choice struct {\n\n\tPending *PendingStatus15Choice `xml:\"Pdg\"`\n\n\tFailing *FailingStatus3Choice `xml:\"Flng\"`\n\n\tProprietary *ProprietaryStatusAndReason1 `xml:\"Prtry\"`\n}\n\n\n\nfunc (s *SettlementStatus10Choice) AddFailing() *FailingStatus3Choice {\n\ts.Failing = new(FailingStatus3Choice)\n\treturn s.Failing\n}\n\nfunc (s *SettlementStatus10Choice) AddProprietary() *ProprietaryStatusAndReason1 {\n\ts.Proprietary = new(ProprietaryStatusAndReason1)\n\treturn s.Proprietary\n}\n\nfunc (s *SettlementStatus10Choice) AddPending() *PendingStatus15Choice ", "output": "{\n\ts.Pending = new(PendingStatus15Choice)\n\treturn s.Pending\n}"} {"input": "package goFrontEnd\n\nimport (\n \"fmt\"\n \"net/http\"\n \"math/rand\"\n \"strconv\"\n)\n\nfunc init() {\n http.HandleFunc(\"/\", handler)\n http.HandleFunc(\"/abc\", handler2)\n}\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n wHeader := w.Header()\n wHeader.Set(\"Content-Type\",\"application/json\")\n fmt.Fprint(w, \"{\\\"a\\\":\\\"beetle\\\",\\\"b\\\":\\\"juice\\\"}\")\n}\n\n\n\nfunc handler2(w http.ResponseWriter, r *http.Request) ", "output": "{\n wHeader := w.Header()\n x := rand.Intn(18)\n y := rand.Intn(18)\n xx := strconv.Itoa(x)\n yy := strconv.Itoa(y)\n wHeader.Set(\"Content-Type\",\"application/json\")\n fmt.Fprint(w, \"{\\\"x\\\":\\\"\" + xx + \"\\\",\\\"y\\\":\\\"\" + yy + \"\\\"}\")\n \n}"} {"input": "package api\n\nimport (\n\t\"io\"\n)\n\n\n\ntype Snapshot struct {\n\tc *Client\n}\n\n\n\n\n\n\n\n\nfunc (s *Snapshot) Save(q *QueryOptions) (io.ReadCloser, *QueryMeta, error) {\n\tr := s.c.newRequest(\"GET\", \"/v1/snapshot\")\n\tr.setQueryOptions(q)\n\n\trtt, resp, err := requireOK(s.c.doRequest(r))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tqm := &QueryMeta{}\n\tparseQueryMeta(resp, qm)\n\tqm.RequestTime = rtt\n\treturn resp.Body, qm, nil\n}\n\n\nfunc (s *Snapshot) Restore(q *WriteOptions, in io.Reader) error {\n\tr := s.c.newRequest(\"PUT\", \"/v1/snapshot\")\n\tr.body = in\n\tr.header.Set(\"Content-Type\", \"application/octet-stream\")\n\tr.setWriteOptions(q)\n\t_, _, err := requireOK(s.c.doRequest(r))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (c *Client) Snapshot() *Snapshot ", "output": "{\n\treturn &Snapshot{c}\n}"} {"input": "package command_runner\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/starkandwayne/cf-cli/cf/command_factory\"\n\t\"github.com/starkandwayne/cf-cli/cf/requirements\"\n\t\"github.com/codegangsta/cli\"\n\t\"os\"\n)\n\ntype Runner interface {\n\tRunCmdByName(cmdName string, c *cli.Context) (err error)\n}\n\ntype ConcreteRunner struct {\n\tcmdFactory command_factory.Factory\n\trequirementsFactory requirements.Factory\n}\n\nfunc NewRunner(cmdFactory command_factory.Factory, requirementsFactory requirements.Factory) (runner ConcreteRunner) {\n\trunner.cmdFactory = cmdFactory\n\trunner.requirementsFactory = requirementsFactory\n\treturn\n}\n\n\n\nfunc (runner ConcreteRunner) RunCmdByName(cmdName string, c *cli.Context) (err error) ", "output": "{\n\tcmd, err := runner.cmdFactory.GetByCmdName(cmdName)\n\tif err != nil {\n\t\tfmt.Printf(\"Error finding command %s\\n\", cmdName)\n\t\tos.Exit(1)\n\t\treturn\n\t}\n\n\trequirements, err := cmd.GetRequirements(runner.requirementsFactory, c)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor _, requirement := range requirements {\n\t\tsuccess := requirement.Execute()\n\t\tif !success {\n\t\t\terr = errors.New(\"Error in requirement\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tcmd.Run(c)\n\treturn\n}"} {"input": "package ps\n\n\n\ntype Process interface {\n\tPid() int\n\n\tPPid() int\n\n\tCPids() []int\n\n\tExecutable() string\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc FindProcessByPid(pid int) (Process, error) {\n\treturn findProcessByPid(pid)\n}\n\n\n\n\n\nfunc FindProcessByExecutable(name string) ([]Process, error) {\n\treturn findProcessByExecutable(name)\n}\n\nfunc Processes() ([]Process, error) ", "output": "{\n\treturn processes()\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"time\"\n)\n\n\nfunc ChannelLogger(LogDir string, UserNick string, message string) {\n STime := time.Now().Format(time.ANSIC)\n logLoc := fmt.Sprintf(\"%d-%s-%d\", time.Now().Day(), time.Now().Month(), time.Now().Year())\n\n f, err := os.OpenFile(LogDir + logLoc + \".log\", os.O_CREATE|os.O_RDWR|os.O_APPEND|os.O_SYNC, 0666)\n if err != nil {\n fmt.Println(f, err)\n }\n\n n, err := io.WriteString(f, STime + \" > \" + UserNick + message + \"\\n\")\n if err != nil {\n fmt.Println(n, err)\n }\n f.Close()\n}\n\n\n\nfunc LogFile(CreateFile string) {\n \n if _, err := os.Stat(CreateFile + \".log\"); os.IsNotExist(err) {\n fmt.Printf(\"Log File \" + CreateFile + \".log Doesn't Exist.\\n\")\n os.Create(CreateFile + \".log\")\n fmt.Printf(\"Created the log file\\n\")\n } else {\n fmt.Printf(\"Log File Exists.\\n\")\n }\n}\n\nfunc LogDir(CreateDir string) ", "output": "{\n\n \n if _, err := os.Stat(CreateDir); os.IsNotExist(err) {\n fmt.Printf(\"No such file or directory: %s\", CreateDir)\n os.Mkdir(CreateDir, 0777)\n } else {\n fmt.Printf(\"Its There: %s\", CreateDir)\n }\n}"} {"input": "package controllers\n\nimport (\n\t\"../models\"\n\t\"../repository\"\n\t\"html/template\"\n\t\"net/http\"\n)\n\ntype ArchivedListController struct{}\n\nconst ArchivedListUrl = \"/archivedList\"\n\n\n\nfunc (c ArchivedListController) ArchivedListHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\n\tfuncMap := template.FuncMap{\n\t\t\"safehtml\": func(text string) template.HTML { return template.HTML(text) },\n\t}\n\ttemplate := template.Must(template.New(\"\").Delims(\"[[\", \"]]\").Funcs(funcMap).ParseFiles(\"../views/layout.html\", \"../views/body.html\"))\n\n\ttodoRepository := repository.NewTodoRepository()\n\tarchivedList := todoRepository.FindArchiveList()\n\ttodoList := make([]map[string]interface{}, 0)\n\tfor _, todo := range archivedList {\n\t\ttodoList = append(todoList, todo.ToJsonObj())\n\t}\n\tpage := models.Page{\n\t\tTitle: \"Todo Sample(Go+Typescript)\",\n\t\tSubTitle: \"Archive\",\n\t\tColor: \"purple\",\n\t\tTodoList: todoList}\n\terr := template.ExecuteTemplate(w, \"base\", page)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc main() {\n\tx := make(chan struct {\n\t\tthreadId uint64\n\t\tvalue int\n\t})\n\ttracer.RegisterChan(x, cap(x))\n\n\tfoo(<-x)\n}\n\nfunc foo(x int) ", "output": "{\n\tfmt.Println(x)\n}"} {"input": "package depsync\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\n\t\"github.com/go-kit/kit/endpoint\"\n)\n\nfunc (s *DEPSyncService) SyncNow(_ context.Context) error {\n\ts.syncer.SyncNow()\n\treturn nil\n}\n\ntype syncNowResponse struct{}\ntype syncNowRequest struct{}\n\nfunc MakeSyncNowEndpoint(s Service) endpoint.Endpoint {\n\treturn func(ctx context.Context, _ interface{}) (interface{}, error) {\n\t\ts.SyncNow(ctx)\n\t\treturn syncNowResponse{}, nil\n\t}\n}\n\nfunc decodeEmptyRequest(ctx context.Context, r *http.Request) (interface{}, error) {\n\treturn nil, nil\n}\n\nfunc encodeEmptyResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {\n\treturn nil\n}\n\n\n\nfunc (e Endpoints) SyncNow(ctx context.Context) error {\n\t_, err := e.SyncNowEndpoint(ctx, nil)\n\treturn err\n}\n\nfunc decodeEmptyResponse(ctx context.Context, r *http.Response) (interface{}, error) ", "output": "{\n\treturn nil, nil\n}"} {"input": "package term \n\nimport \"io\"\n\ntype Db []Term\n\nfunc NewDb(args []Term) Db {\n\treturn Db(args)\n}\n\nfunc (s Db) Format(w io.Writer, style Style) {\n\tisRoot := style.IsRoot\n\tstyle.IsRoot = false \n\n\tprevName := \"#\" \n\tfor _, t := range s {\n\t\tif isRoot {\n\t\t\tname := Name(t)\n\t\t\tif prevName != \"#\" && prevName != name {\n\t\t\t\tio.WriteString(w, \"\\n\")\n\t\t\t}\n\t\t\tprevName = name\n\t\t}\n\n\t\tstyle.WriteIndent(w)\n\t\tt.Format(w, style)\n\t}\n}\n\n\ntype Query struct {\n\tdb Db\n\tname string\n\tarity int\n}\n\n\n\n\nfunc (db Db) NewQuery(t Term) *Query {\n\treturn &Query{\n\t\tdb: db,\n\t\tname: Name(t),\n\t\tarity: Arity(t),\n\t}\n}\n\n\n\nfunc (q *Query) Run() *Cursor {\n\treturn &Cursor{\n\t\tq: q,\n\t\ti: 0,\n\t}\n}\n\n\ntype Cursor struct {\n\tq *Query\n\ti int\n}\n\n\n\nfunc (c *Cursor) Next() (Term, bool) ", "output": "{\n\tfor ; c.i < len(c.q.db); c.i++ {\n\t\tcandidate := c.q.db[c.i]\n\t\tif Arity(candidate) == c.q.arity && Name(candidate) == c.q.name {\n\t\t\tc.i++\n\t\t\treturn candidate, c.i < len(c.q.db)\n\t\t}\n\t}\n\treturn nil, false\n}"} {"input": "package v3_4_experimental\n\nimport (\n\t\"github.com/coreos/ignition/v2/config/merge\"\n\t\"github.com/coreos/ignition/v2/config/shared/errors\"\n\t\"github.com/coreos/ignition/v2/config/util\"\n\tprev \"github.com/coreos/ignition/v2/config/v3_3\"\n\t\"github.com/coreos/ignition/v2/config/v3_4_experimental/translate\"\n\t\"github.com/coreos/ignition/v2/config/v3_4_experimental/types\"\n\t\"github.com/coreos/ignition/v2/config/validate\"\n\n\t\"github.com/coreos/go-semver/semver\"\n\t\"github.com/coreos/vcontext/report\"\n)\n\nfunc Merge(parent, child types.Config) types.Config {\n\tres, _ := merge.MergeStructTranscribe(parent, child)\n\treturn res.(types.Config)\n}\n\n\n\nfunc Parse(rawConfig []byte) (types.Config, report.Report, error) {\n\tif len(rawConfig) == 0 {\n\t\treturn types.Config{}, report.Report{}, errors.ErrEmpty\n\t}\n\n\tvar config types.Config\n\tif rpt, err := util.HandleParseErrors(rawConfig, &config); err != nil {\n\t\treturn types.Config{}, rpt, err\n\t}\n\n\tversion, err := semver.NewVersion(config.Ignition.Version)\n\n\tif err != nil || *version != types.MaxVersion {\n\t\treturn types.Config{}, report.Report{}, errors.ErrUnknownVersion\n\t}\n\n\trpt := validate.ValidateWithContext(config, rawConfig)\n\tif rpt.IsFatal() {\n\t\treturn types.Config{}, rpt, errors.ErrInvalid\n\t}\n\n\treturn config, rpt, nil\n}\n\n\n\n\n\n\nfunc ParseCompatibleVersion(raw []byte) (types.Config, report.Report, error) ", "output": "{\n\tversion, rpt, err := util.GetConfigVersion(raw)\n\tif err != nil {\n\t\treturn types.Config{}, rpt, err\n\t}\n\n\tif version == types.MaxVersion {\n\t\treturn Parse(raw)\n\t}\n\tprevCfg, r, err := prev.ParseCompatibleVersion(raw)\n\tif err != nil {\n\t\treturn types.Config{}, r, err\n\t}\n\treturn translate.Translate(prevCfg), r, nil\n}"} {"input": "package cron\n\nimport (\n\t\"fmt\"\n\t\"github.com/Cepave/agent/g\"\n\t\"github.com/Cepave/common/model\"\n\t\"log\"\n\t\"time\"\n)\n\nfunc ReportAgentStatus() {\n\tif g.Config().Heartbeat.Enabled && g.Config().Heartbeat.Addr != \"\" {\n\t\tgo reportAgentStatus(time.Duration(g.Config().Heartbeat.Interval) * time.Second)\n\t}\n}\n\n\n\nfunc reportAgentStatus(interval time.Duration) ", "output": "{\n\tfor {\n\t\thostname, err := g.Hostname()\n\t\tif err != nil {\n\t\t\thostname = fmt.Sprintf(\"error:%s\", err.Error())\n\t\t}\n\n\t\treq := model.AgentReportRequest{\n\t\t\tHostname: hostname,\n\t\t\tIP: g.IP(),\n\t\t\tAgentVersion: g.VERSION,\n\t\t\tPluginVersion: g.GetCurrPluginVersion(),\n\t\t}\n\n\t\tvar resp model.SimpleRpcResponse\n\t\terr = g.HbsClient.Call(\"Agent.ReportStatus\", req, &resp)\n\t\tif err != nil || resp.Code != 0 {\n\t\t\tlog.Println(\"call Agent.ReportStatus fail:\", err, \"Request:\", req, \"Response:\", resp)\n\t\t}\n\n\t\ttime.Sleep(interval)\n\t}\n}"} {"input": "package stats_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/montanaflynn/stats\"\n)\n\nfunc ExampleSigmoid() {\n\ts, _ := stats.Sigmoid([]float64{3.0, 1.0, 2.1})\n\tfmt.Println(s)\n}\n\nfunc TestSigmoidEmptyInput(t *testing.T) {\n\t_, err := stats.Sigmoid([]float64{})\n\tif err != stats.EmptyInputErr {\n\t\tt.Errorf(\"Should have returned empty input error\")\n\t}\n}\n\n\n\nfunc TestSigmoid(t *testing.T) ", "output": "{\n\tsm, err := stats.Sigmoid([]float64{-0.54761371, 17.04850603, 4.86054302})\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\ta := 0.3664182235138545\n\tif sm[0] != a {\n\t\tt.Errorf(\"%v != %v\", sm[0], a)\n\t}\n\n\ta = 0.9999999605608187\n\tif sm[1] != a {\n\t\tt.Errorf(\"%v != %v\", sm[1], a)\n\t}\n\n\ta = 0.9923132671908277\n\tif sm[2] != a {\n\t\tt.Errorf(\"%v != %v\", sm[2], a)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n)\n\nconst (\n\tsemanticAlphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-\"\n\n\tsemanticBuildAlphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-.\"\n)\n\n\n\nconst (\n\tAppName string = \"dcrdata\"\n\tAppMajor uint = 6\n\tAppMinor uint = 1\n\tAppPatch uint = 0\n)\n\n\nvar (\n\tappPreRelease = \"pre\"\n\n\tappBuild = \"dev\"\n)\n\n\n\nfunc Version() string {\n\tversion := fmt.Sprintf(\"%d.%d.%d\", AppMajor, AppMinor, AppPatch)\n\n\tpreRelease := normalizePreRelString(appPreRelease)\n\tif preRelease != \"\" {\n\t\tversion = fmt.Sprintf(\"%s-%s\", version, preRelease)\n\t}\n\n\tbuild := normalizeBuildString(appBuild)\n\tif build != \"\" {\n\t\tversion = fmt.Sprintf(\"%s+%s\", version, build)\n\t}\n\n\treturn version\n}\n\n\n\n\n\n\n\n\n\nfunc normalizePreRelString(str string) string {\n\treturn normalizeSemString(str, semanticAlphabet)\n}\n\n\n\n\n\nfunc normalizeBuildString(str string) string {\n\treturn normalizeSemString(str, semanticBuildAlphabet)\n}\n\nfunc normalizeSemString(str, alphabet string) string ", "output": "{\n\tvar result bytes.Buffer\n\tfor _, r := range str {\n\t\tif strings.ContainsRune(alphabet, r) {\n\t\t\tresult.WriteRune(r)\n\t\t}\n\t}\n\treturn result.String()\n}"} {"input": "package dml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/dml\"\n)\n\n\n\nfunc TestCT_Scale2DMarshalUnmarshal(t *testing.T) {\n\tv := dml.NewCT_Scale2D()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := dml.NewCT_Scale2D()\n\txml.Unmarshal(buf, v2)\n}\n\nfunc TestCT_Scale2DConstructor(t *testing.T) ", "output": "{\n\tv := dml.NewCT_Scale2D()\n\tif v == nil {\n\t\tt.Errorf(\"dml.NewCT_Scale2D must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed dml.CT_Scale2D should validate: %s\", err)\n\t}\n}"} {"input": "package processors\n\nimport (\n\t\"context\"\n\n\t\"github.com/cloudevents/sdk-go/v2/event\"\n)\n\n\n\n\n\ntype Interface interface {\n\tProcess(ctx context.Context, e *event.Event) error\n\tNext() Interface\n}\n\n\ntype ChainableProcessor interface {\n\tInterface\n\n\tWithNext(ChainableProcessor) ChainableProcessor\n}\n\n\n\n\ntype BaseProcessor struct {\n\tn ChainableProcessor\n}\n\n\n\n\nfunc (p *BaseProcessor) Next() Interface {\n\tif p.n == nil {\n\t\treturn noop\n\t}\n\treturn p.n\n}\n\n\nfunc (p *BaseProcessor) WithNext(n ChainableProcessor) ChainableProcessor {\n\tp.n = n\n\treturn p.n\n}\n\n\nfunc ChainProcessors(first ChainableProcessor, rest ...ChainableProcessor) Interface {\n\tnext := first\n\tfor _, p := range rest {\n\t\tnext = next.WithNext(p)\n\t}\n\treturn first\n}\n\nvar noop = &noOpProcessor{}\n\ntype noOpProcessor struct{}\n\nfunc (p noOpProcessor) Process(_ context.Context, _ *event.Event) error {\n\treturn nil\n}\n\n\n\n\n\nfunc (p noOpProcessor) Next() Interface ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nimport \"github.com/gopherjs/gopherjs/js\"\n\nfunc uint8ArrayToBytes(buf uintptr) []byte {\n\tarray := js.InternalObject(buf)\n\tslice := make([]byte, array.Length())\n\tjs.InternalObject(slice).Set(\"$array\", array)\n\treturn slice\n}\n\n\n\nfunc uint8ArrayToString(buf uintptr) string ", "output": "{\n\tarray := js.InternalObject(buf)\n\tslice := make([]byte, array.Length())\n\tjs.InternalObject(slice).Set(\"$array\", array)\n\treturn string(slice)\n}"} {"input": "package readline\n\n\nimport \"C\"\n\nimport (\n\t\"unsafe\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype CompletionEntryFunction func(text string, state int) string\n\nvar completionEntryFunction CompletionEntryFunction\n\n\n\nfunc SetCompletionEntryFunction(f CompletionEntryFunction) {\n\tif f == nil {\n\t\tif completionEntryFunction != nil {\n\t\t\tC.rl_attempted_completion_function = nil\n\t\t}\n\t} else if completionEntryFunction == nil {\n\t\tC.register_attempted_completion_function()\n\t}\n\tcompletionEntryFunction = f\n}\n\n\n\n\n\nfunc SetAttemptedCompletionOver(b bool) {\n\tif b {\n\t\tC.rl_attempted_completion_over = 1\n\t} else {\n\t\tC.rl_attempted_completion_over = 0\n\t}\n}\n\n\n\nfunc SetCompleterWordBreakChars(s string) {\n\tcs := C.CString(s)\n\tC.free(unsafe.Pointer(C.rl_completer_word_break_characters))\n\tC.rl_completer_word_break_characters = cs\n}\n\n\n\n\nfunc CompleterWordBreakChars() string {\n\treturn C.GoString(C.rl_completer_word_break_characters)\n}\n\nfunc goCompletionEntryFunction(text *C.char, state C.int) *C.char ", "output": "{\n\tmatch := completionEntryFunction(C.GoString(text), int(state))\n\tif match == \"\" {\n\t\treturn nil\n\t}\n\treturn C.CString(match) \n}"} {"input": "package integration\n\nimport (\n\t\"context\"\n\t\"testing\"\n)\n\n\n\nfunc TestUserSettings_List(t *testing.T) ", "output": "{\n\tresult, _, err := client.UserSettings.List(context.Background())\n\n\tif err != nil {\n\t\tt.Errorf(\"Could not get webhooks list: %v\", err)\n\t}\n\n\tif result.Success != true {\n\t\tt.Error(\"Got invalid result\")\n\t}\n}"} {"input": "package query\n\nimport (\n\t\"encoding/json\"\n\t\"reflect\"\n)\n\nfunc toJson(v interface{}) ([]byte, error) {\n\treturn json.Marshal(v)\n}\n\nfunc wrapper(name string, v interface{}) map[string]interface{} {\n\tquery := map[string]interface{}{\n\t\tname: v,\n\t}\n\treturn query\n}\n\n\n\nfunc convertable(value reflect.Value) bool {\n\tswitch value.Kind() {\n\tcase reflect.Slice:\n\t\treturn value.Len() > 0\n\tcase reflect.Ptr:\n\t\treturn !value.IsNil()\n\t}\n\treturn true\n}\n\nfunc convertStruct(x interface{}) interface{} {\n\tquery := make(map[string]interface{})\n\n\tt := reflect.ValueOf(x).Type()\n\tv := reflect.ValueOf(x)\n\n\tfor i := 0; i < t.NumField(); i++ {\n\t\tfield := t.Field(i)\n\t\tvalue := v.FieldByName(field.Name)\n\t\ttag := field.Tag.Get(\"json\")\n\t\tif tag == \"-\" {\n\t\t\tcontinue\n\t\t}\n\t\tif convertable(value) {\n\t\t\tquery[tag] = convert(value)\n\t\t}\n\t}\n\n\treturn query\n\n}\n\nfunc convert(value reflect.Value) interface{} ", "output": "{\n\tswitch value.Kind() {\n\tcase reflect.Slice:\n\t\tvar res []interface{}\n\t\tfor i := 0; i < value.Len(); i++ {\n\t\t\tres = append(res, convert(value.Index(i)))\n\t\t}\n\t\treturn res\n\tcase reflect.Ptr:\n\t\tif !value.IsNil() {\n\t\t\treturn convert(value.Elem())\n\t\t}\n\tcase reflect.String:\n\t\treturn value.String()\n\tcase reflect.Float64:\n\t\treturn value.Float()\n\tcase reflect.Int:\n\t\treturn value.Int()\n\tcase reflect.Bool:\n\t\treturn value.Bool()\n\t}\n\treturn value.Interface()\n}"} {"input": "package donna\n\n\n\n\nfunc (gen *MoveGen) pawnCaptures(color int) *MoveGen {\n\tenemy := gen.p.outposts[color^1]\n\n\tfor pawns := gen.p.outposts[pawn(color)]; pawns.any(); pawns = pawns.pop() {\n\t\tsquare := pawns.first()\n\n\t\tif rank(color, square) != A7H7 {\n\t\t\tgen.movePawn(square, gen.p.targets(square) & enemy)\n\t\t} else {\n\t\t\tfor bm := gen.p.targets(square); bm.any(); bm = bm.pop() {\n\t\t\t\ttarget := bm.first()\n\t\t\t\tmQ, _, _, _ := NewPromotion(gen.p, square, target)\n\t\t\t\tgen.add(mQ)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn gen\n}\n\n\nfunc (gen *MoveGen) pieceCaptures(color int) *MoveGen {\n\tenemy := gen.p.outposts[color^1]\n\n\tfor bm := gen.p.outposts[color] ^ gen.p.outposts[pawn(color)] ^ gen.p.outposts[king(color)]; bm.any(); bm = bm.pop() {\n\t\tsquare := bm.first()\n\t\tgen.movePiece(square, gen.p.targets(square) & enemy)\n\t}\n\tif gen.p.outposts[king(color)].any() {\n\t\tsquare := gen.p.king[color]\n\t\tgen.moveKing(square, gen.p.targets(square) & enemy)\n\t}\n\n\treturn gen\n}\n\nfunc (gen *MoveGen) generateCaptures() *MoveGen ", "output": "{\n\tcolor := gen.p.color\n\treturn gen.pawnCaptures(color).pieceCaptures(color)\n}"} {"input": "package main\n\nimport (\n \"math\"\n \"time\"\n)\n\n\n\n\n\nfunc timeToUnix(value string) int64 {\n local, _ := time.LoadLocation(\"Local\")\n toTime, _ := time.ParseInLocation(timeLayout, value, local)\n return toTime.Unix()\n}\n\nfunc getTime(packet []byte, entryList *[]string, pointer *int, err *bool) ", "output": "{\n var timeLen int\n if len(packet) - *pointer >= 8 && !*err {\n timeLen = 8\n }\n if timeLen > 0 {\n timeByteString := string(packet[*pointer: *pointer + timeLen])\n var cInt float64\n for x := range timeByteString {\n cInt += float64(timeByteString[x]) * math.Pow(256, float64(timeLen -\n 1 - x))\n }\n timestamp := time.Unix(int64(cInt), 0).Format(timeLayout)\n *entryList = append(*entryList, timestamp)\n } else {\n *err = true\n }\n *pointer += 8\n}"} {"input": "package session\n\nimport (\n\tgomock \"github.com/golang/mock/gomock\"\n\tanonymous \"github.com/skygeario/skygear-server/pkg/auth/dependency/identity/anonymous\"\n\treflect \"reflect\"\n)\n\n\ntype MockAnonymousIdentityProvider struct {\n\tctrl *gomock.Controller\n\trecorder *MockAnonymousIdentityProviderMockRecorder\n}\n\n\ntype MockAnonymousIdentityProviderMockRecorder struct {\n\tmock *MockAnonymousIdentityProvider\n}\n\n\nfunc NewMockAnonymousIdentityProvider(ctrl *gomock.Controller) *MockAnonymousIdentityProvider {\n\tmock := &MockAnonymousIdentityProvider{ctrl: ctrl}\n\tmock.recorder = &MockAnonymousIdentityProviderMockRecorder{mock}\n\treturn mock\n}\n\n\nfunc (m *MockAnonymousIdentityProvider) EXPECT() *MockAnonymousIdentityProviderMockRecorder {\n\treturn m.recorder\n}\n\n\nfunc (m *MockAnonymousIdentityProvider) List(userID string) ([]*anonymous.Identity, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", userID)\n\tret0, _ := ret[0].([]*anonymous.Identity)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}\n\n\n\n\nfunc (mr *MockAnonymousIdentityProviderMockRecorder) List(userID interface{}) *gomock.Call ", "output": "{\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"List\", reflect.TypeOf((*MockAnonymousIdentityProvider)(nil).List), userID)\n}"} {"input": "package helpers\n\nimport (\n \"fmt\"\n\n \"kekocity/data/entities\"\n \"kekocity/data/models\"\n \"kekocity/interfaces\"\n)\n\nvar AuthHelper *authHelper\n\ntype authHelper struct{}\n\n\n\nfunc (a *authHelper) playerEntityToModel(_entity *entities.Player) (*models.Player, error) {\n u := models.NewPlayer(_entity)\n\n return u, nil\n}\n\nfunc (a *authHelper) AuthenticateUsingCredentials(_token string) (interfaces.IPlayer, error) {\n var players *entities.Player\n var query string = fmt.Sprintf(\"SELECT * FROM user WHERE token = '%v' LIMIT 1\", _token)\n db.Query(query).Rows(&players)\n\n if players == nil {\n\t\treturn nil, fmt.Errorf(\"Player '%s' not found\", _token)\n\t}\n\n\tplayerModel, err := a.playerEntityToModel(players)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn playerModel, nil\n}\n\nfunc init() ", "output": "{\n\tAuthHelper = &authHelper{}\n}"} {"input": "package guest\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"io\"\n\t\"os\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/vim25/soap\"\n)\n\ntype upload struct {\n\t*GuestFlag\n\t*FileAttrFlag\n\n\toverwrite bool\n}\n\nfunc init() {\n\tcli.Register(\"guest.upload\", &upload{})\n}\n\nfunc (cmd *upload) Register(ctx context.Context, f *flag.FlagSet) {\n\tcmd.GuestFlag, ctx = newGuestFlag(ctx)\n\tcmd.GuestFlag.Register(ctx, f)\n\tcmd.FileAttrFlag, ctx = newFileAttrFlag(ctx)\n\tcmd.FileAttrFlag.Register(ctx, f)\n\n\tf.BoolVar(&cmd.overwrite, \"f\", false, \"If set, the guest destination file is clobbered\")\n}\n\nfunc (cmd *upload) Usage() string {\n\treturn \"SOURCE DEST\"\n}\n\nfunc (cmd *upload) Description() string {\n\treturn `Copy SOURCE from the local system to DEST in the guest VM.\n\nIf SOURCE name is \"-\", read source from stdin.\n\nExamples:\n govc guest.upload -l user:pass -vm=my-vm ~/.ssh/id_rsa.pub /home/$USER/.ssh/authorized_keys\n cowsay \"have a great day\" | govc guest.upload -l user:pass -vm=my-vm - /etc/motd`\n}\n\nfunc (cmd *upload) Process(ctx context.Context) error {\n\tif err := cmd.GuestFlag.Process(ctx); err != nil {\n\t\treturn err\n\t}\n\tif err := cmd.FileAttrFlag.Process(ctx); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\nfunc (cmd *upload) Run(ctx context.Context, f *flag.FlagSet) error ", "output": "{\n\tif f.NArg() != 2 {\n\t\treturn flag.ErrHelp\n\t}\n\n\tc, err := cmd.Toolbox()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrc := f.Arg(0)\n\tdst := f.Arg(1)\n\n\tp := soap.DefaultUpload\n\n\tvar r io.Reader = os.Stdin\n\n\tif src != \"-\" {\n\t\tf, err := os.Open(src)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\n\t\tr = f\n\n\t\tif cmd.OutputFlag.TTY {\n\t\t\tlogger := cmd.ProgressLogger(\"Uploading... \")\n\t\t\tp.Progress = logger\n\t\t\tdefer logger.Wait()\n\t\t}\n\t}\n\n\treturn c.Upload(ctx, r, dst, p, cmd.Attr(), cmd.overwrite)\n}"} {"input": "package lib\n\n\nimport \"C\"\n\nfunc CheckIsSupported(check int) bool {\n\treturn C.lzma_check_is_supported(C.lzma_check(check)) != 0\n}\n\nfunc CheckSize(check int) int {\n\treturn int(C.lzma_check_size(C.lzma_check(check)))\n}\n\nfunc CRC32(buf []byte, crc uint32) uint32 {\n\tptr, size := CSlicePtrLen(buf)\n\treturn uint32(C.lzma_crc32(ptr, size, C.uint32_t(crc)))\n}\n\n\n\nfunc (z *Stream) GetCheck() int {\n\treturn int(C.lzma_get_check(z.C()))\n}\n\nfunc CRC64(buf []byte, crc uint64) uint64 ", "output": "{\n\tptr, size := CSlicePtrLen(buf)\n\treturn uint64(C.lzma_crc64(ptr, size, C.uint64_t(crc)))\n}"} {"input": "package sliceset\n\nimport (\n\t\"sort\"\n\n\t\"github.com/xtgo/set\"\n)\n\ntype Set []int\n\nfunc (s Set) Len() int { return len(s) }\nfunc (s Set) Less(i, j int) bool { return s[i] < s[j] }\nfunc (s Set) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (s Set) Copy() Set { return append(Set(nil), s...) }\n\nfunc (s Set) Union(t Set) Set { return s.Do(set.Union, t) }\nfunc (s Set) Inter(t Set) Set { return s.Do(set.Inter, t) }\nfunc (s Set) Diff(t Set) Set { return s.Do(set.Diff, t) }\nfunc (s Set) SymDiff(t Set) Set { return s.Do(set.SymDiff, t) }\nfunc (s Set) IsSub(t Set) bool { return s.DoBool(set.IsSub, t) }\nfunc (s Set) IsSuper(t Set) bool { return s.DoBool(set.IsSuper, t) }\nfunc (s Set) IsInter(t Set) bool { return s.DoBool(set.IsInter, t) }\n\n\nfunc (s Set) Uniq() Set {\n\tn := set.Uniq(s)\n\treturn s[:n]\n}\n\nfunc (s Set) Do(op set.Op, t Set) Set {\n\tdata := append(s, t...)\n\tn := op(data, len(s))\n\treturn data[:n]\n}\n\ntype BoolOp func(sort.Interface, int) bool\n\nfunc (s Set) DoBool(op BoolOp, t Set) bool {\n\tdata := append(s, t...)\n\treturn op(data, len(s))\n}\n\nfunc (s Set) IsEqual(t Set) bool ", "output": "{ return s.DoBool(set.IsEqual, t) }"} {"input": "package unix\n\nimport \"syscall\"\n\nfunc setTimespec(sec, nsec int64) Timespec {\n\treturn Timespec{Sec: int32(sec), Nsec: int32(nsec)}\n}\n\nfunc setTimeval(sec, usec int64) Timeval {\n\treturn Timeval{Sec: int32(sec), Usec: int32(usec)}\n}\n\nfunc SetKevent(k *Kevent_t, fd, mode, flags int) {\n\tk.Ident = uint32(fd)\n\tk.Filter = int16(mode)\n\tk.Flags = uint16(flags)\n}\n\nfunc (iov *Iovec) SetLen(length int) {\n\tiov.Len = uint32(length)\n}\n\nfunc (msghdr *Msghdr) SetControllen(length int) {\n\tmsghdr.Controllen = uint32(length)\n}\n\n\n\nfunc (cmsg *Cmsghdr) SetLen(length int) {\n\tcmsg.Len = uint32(length)\n}\n\nfunc Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)\n\nfunc (msghdr *Msghdr) SetIovlen(length int) ", "output": "{\n\tmsghdr.Iovlen = int32(length)\n}"} {"input": "package labassistant\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc good_func(i int) int {\n\treturn i\n}\n\nfunc panic_func(i int) int {\n\tpanic(\"panic\")\n}\n\nfunc bad_func(i int) int {\n\treturn i + 1\n}\n\nfunc TestObservationRunIsOK(t *testing.T) {\n\ta := assert.New(t)\n\tout := make_ob().run(good_func, 1)\n\ta.Equal([]interface{}{1}, out)\n\n\tout = make_ob().run(good_func, 0)\n\ta.NotEqual([]interface{}{1}, out)\n\n\ta.Panics(func() {\n\t\tmake_ob().run(good_func)\n\t})\n\n\ta.Panics(func() {\n\t\tmake_ob().run(good_func, 1, 1)\n\t})\n\n\ta.Panics(func() {\n\t\tmake_ob().run(good_func, \"string\")\n\t})\n}\n\nfunc TestObservationRunSetsValues(t *testing.T) {\n\ta := assert.New(t)\n\tgood := make_ob()\n\tgood.run(good_func, 1)\n\ta.Equal(\"github.com/lmas/labassistant.good_func\", good.Name)\n\ta.Empty(good.Panic)\n\ta.Equal([]interface{}{1}, good.Outputs)\n\ta.NotEmpty(good.Start)\n\ta.NotZero(good.Duration)\n\n\tbad := make_ob()\n\tbad.can_panic = true\n\ta.NotPanics(func() {\n\t\tbad.run(panic_func, 1)\n\t})\n\ta.Equal(\"panic\", bad.Panic)\n\ta.Empty(bad.Outputs)\n\ta.NotEmpty(bad.Start)\n\ta.Zero(bad.Duration)\n}\n\nfunc make_ob() *Observation ", "output": "{\n\treturn &Observation{}\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n)\n\n\ntype Address struct {\n\tStreet, City string\n}\n\ntype Person struct {\n\tFirstName, LastName string\n}\n\ntype T1 string\ntype T2 string\ntype T3 string\n\nvar logger *log.Logger\n\nfunc main() {\n\tmyAddress := Address{\n\t\tStreet: \"Trimveien 6\",\n\t\tCity: \"Oslo\",\n\t}\n\tlog.Println(myAddress)\n\n\tme := Person{\n\t\tFirstName: \"Christian\",\n\t\tLastName: \"Bergum Bergersen\",\n\t}\n\tlog.Println(me)\n\n\tvar foo T1\n\tfoo = \"foo\"\n\tlog.Println(foo)\n\n\tvar bar T3\n\tbar = \"bar\"\n\tlog.Println(bar)\n}\n\n\nfunc (address Address) String() string {\n\treturn fmt.Sprintf(\"%s\", address)\n}\n\n\nfunc (person Person) String() string {\n\treturn fmt.Sprintf(\"%s %s\", person.FirstName, person.LastName)\n}\n\n\nfunc (t1 T1) String() string {\n\treturn fmt.Sprint(t1)\n}\n\n\nfunc (t2 T2) String() string {\n\tlog.Print(\"Calling String() for : %v\", t2)\n\treturn fmt.Sprintln(t2)\n}\n\n\n\n\nfunc (bar T3) String() string ", "output": "{\n\tvar buf bytes.Buffer\n\tlogger = log.New(&buf, \"logger: \", log.Lshortfile)\n\tlogger.Printf(\"Calling String() for %+v\", bar)\n\treturn fmt.Sprintf(\"Bar\")\n}"} {"input": "package daemon\n\nimport (\n\t\"path/filepath\"\n\n\t\"github.com/pkg/errors\"\n\n\t\"github.com/mutagen-io/mutagen/pkg/filesystem\"\n)\n\nconst (\n\tlockName = \"daemon.lock\"\n\tendpointName = \"daemon.sock\"\n)\n\n\n\nfunc subpath(name string) (string, error) {\n\tdaemonRoot, err := filesystem.Mutagen(true, filesystem.MutagenDaemonDirectoryName)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to compute daemon directory\")\n\t}\n\n\treturn filepath.Join(daemonRoot, name), nil\n}\n\n\n\n\n\n\n\nfunc EndpointPath() (string, error) {\n\treturn subpath(endpointName)\n}\n\nfunc lockPath() (string, error) ", "output": "{\n\treturn subpath(lockName)\n}"} {"input": "package api\n\n\ntype UserInfo interface {\n\tGetName() string\n\tGetUID() string\n\tGetScope() string\n\tGetExtra() map[string]string\n}\n\n\n\ntype UserIdentityInfo interface {\n\tGetUserName() string\n\tGetProviderName() string\n\tGetExtra() map[string]string\n}\n\n\ntype UserIdentityMapper interface {\n\tUserFor(identityInfo UserIdentityInfo) (UserInfo, error)\n}\n\ntype Client interface {\n\tGetId() string\n\tGetSecret() string\n\tGetRedirectUri() string\n\tGetUserData() interface{}\n}\n\ntype Grant struct {\n\tClient Client\n\tScope string\n\tExpiration int64\n\tRedirectURI string\n}\n\ntype DefaultUserInfo struct {\n\tName string\n\tUID string\n\tScope string\n\tExtra map[string]string\n}\n\nfunc (i *DefaultUserInfo) GetName() string {\n\treturn i.Name\n}\n\nfunc (i *DefaultUserInfo) GetUID() string {\n\treturn i.UID\n}\n\nfunc (i *DefaultUserInfo) GetScope() string {\n\treturn i.Scope\n}\n\n\n\ntype DefaultUserIdentityInfo struct {\n\tUserName string\n\tProviderName string\n\tExtra map[string]string\n}\n\n\nfunc NewDefaultUserIdentityInfo(username string) DefaultUserIdentityInfo {\n\treturn DefaultUserIdentityInfo{\n\t\tUserName: username,\n\t\tExtra: make(map[string]string),\n\t}\n}\n\nfunc (i *DefaultUserIdentityInfo) GetUserName() string {\n\treturn i.UserName\n}\n\nfunc (i *DefaultUserIdentityInfo) GetProviderName() string {\n\treturn i.ProviderName\n}\n\nfunc (i *DefaultUserIdentityInfo) GetExtra() map[string]string {\n\treturn i.Extra\n}\n\nfunc (i *DefaultUserInfo) GetExtra() map[string]string ", "output": "{\n\treturn i.Extra\n}"} {"input": "package crypto\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha512\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n)\n\n\nfunc HS512Byte(in, secret []byte) []byte {\n\th := hmac.New(sha512.New, secret)\n\th.Write(in)\n\treturn h.Sum(nil)\n}\n\n\n\n\n\nfunc HS512Hex(in, secret string) string {\n\tkey := []byte(secret)\n\th := hmac.New(sha512.New, key)\n\th.Write([]byte(in))\n\treturn hex.EncodeToString(h.Sum(nil))\n}\n\n\nfunc CompareHS512Hex(in, secret, hs512Hex string) bool {\n\tif HS512Hex(in, secret) == hs512Hex {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc HS512Base64(in, secret string) string ", "output": "{\n\tkey := []byte(secret)\n\th := hmac.New(sha512.New, key)\n\th.Write([]byte(in))\n\treturn base64.StdEncoding.EncodeToString(h.Sum(nil))\n}"} {"input": "package integration\n\nimport (\n\t\"os\"\n\t\"runtime\"\n\t\"testing\"\n\n\t\"github.com/opencontainers/runc/libcontainer\"\n\t_ \"github.com/opencontainers/runc/libcontainer/nsenter\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\n\n\n\n\nvar testRoots []string\n\nfunc TestMain(m *testing.M) {\n\tlogrus.SetOutput(os.Stderr)\n\tlogrus.SetLevel(logrus.InfoLevel)\n\n\tdefer func() {\n\t\tfor _, root := range testRoots {\n\t\t\tos.RemoveAll(root)\n\t\t}\n\t}()\n\n\tret := m.Run()\n\tos.Exit(ret)\n}\n\nfunc init() ", "output": "{\n\tif len(os.Args) < 2 || os.Args[1] != \"init\" {\n\t\treturn\n\t}\n\truntime.GOMAXPROCS(1)\n\truntime.LockOSThread()\n\tfactory, err := libcontainer.New(\"\")\n\tif err != nil {\n\t\tlogrus.Fatalf(\"unable to initialize for container: %s\", err)\n\t}\n\tif err := factory.StartInitialization(); err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n}"} {"input": "package text\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\nvar text = \"The quick brown fox jumps over the lazy dog.\"\n\nfunc TestWrap(t *testing.T) {\n\texp := [][]string{\n\t\t{\"The\", \"quick\", \"brown\", \"fox\"},\n\t\t{\"jumps\", \"over\", \"the\", \"lazy\", \"dog.\"},\n\t}\n\twords := bytes.Split([]byte(text), sp)\n\tgot := WrapWords(words, 1, 24, defaultPenalty)\n\tif len(exp) != len(got) {\n\t\tt.Fail()\n\t}\n\tfor i := range exp {\n\t\tif len(exp[i]) != len(got[i]) {\n\t\t\tt.Fail()\n\t\t}\n\t\tfor j := range exp[i] {\n\t\t\tif exp[i][j] != string(got[i][j]) {\n\t\t\t\tt.Fatal(i, exp[i][j], got[i][j])\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestWrapNarrow(t *testing.T) {\n\texp := \"The\\nquick\\nbrown\\nfox\\njumps\\nover\\nthe\\nlazy\\ndog.\"\n\tif Wrap(text, 5) != exp {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestWrapOneLine(t *testing.T) {\n\texp := \"The quick brown fox jumps over the lazy dog.\"\n\tif Wrap(text, 500) != exp {\n\t\tt.Fail()\n\t}\n}\n\n\n\nfunc TestWrapBug1(t *testing.T) ", "output": "{\n\tcases := []struct {\n\t\tlimit int\n\t\ttext string\n\t\twant string\n\t}{\n\t\t{4, \"aaaaa\", \"aaaaa\"},\n\t\t{4, \"a aaaaa\", \"a\\naaaaa\"},\n\t}\n\n\tfor _, test := range cases {\n\t\tgot := Wrap(test.text, test.limit)\n\t\tif got != test.want {\n\t\t\tt.Errorf(\"Wrap(%q, %d) = %q want %q\", test.text, test.limit, got, test.want)\n\t\t}\n\t}\n}"} {"input": "package ipam\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\t\"github.com/go-openapi/runtime/middleware\"\n\t\"github.com/go-openapi/validate\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewPostIPAMParams() PostIPAMParams {\n\tvar ()\n\treturn PostIPAMParams{}\n}\n\n\n\n\n\ntype PostIPAMParams struct {\n\n\tHTTPRequest *http.Request\n\n\tFamily *string\n}\n\n\n\n\n\nfunc (o *PostIPAMParams) bindFamily(rawData []string, hasKey bool, formats strfmt.Registry) error {\n\tvar raw string\n\tif len(rawData) > 0 {\n\t\traw = rawData[len(rawData)-1]\n\t}\n\tif raw == \"\" { \n\t\treturn nil\n\t}\n\n\to.Family = &raw\n\n\tif err := o.validateFamily(formats); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (o *PostIPAMParams) validateFamily(formats strfmt.Registry) error {\n\n\tif err := validate.Enum(\"family\", \"query\", *o.Family, []interface{}{\"ipv4\", \"ipv6\"}); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (o *PostIPAMParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error ", "output": "{\n\tvar res []error\n\to.HTTPRequest = r\n\n\tqs := runtime.Values(r.URL.Query())\n\n\tqFamily, qhkFamily, _ := qs.GetOK(\"family\")\n\tif err := o.bindFamily(qFamily, qhkFamily, route.Formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package unversioned\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/api/testapi\"\n\t\"k8s.io/kubernetes/pkg/runtime\"\n)\n\ntype HTTPClientFunc func(*http.Request) (*http.Response, error)\n\nfunc (f HTTPClientFunc) Do(req *http.Request) (*http.Response, error) {\n\treturn f(req)\n}\n\n\ntype FakeRESTClient struct {\n\tClient HTTPClient\n\tCodec runtime.Codec\n\tReq *http.Request\n\tResp *http.Response\n\tErr error\n}\n\nfunc (c *FakeRESTClient) Get() *Request {\n\treturn NewRequest(c, \"GET\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Put() *Request {\n\treturn NewRequest(c, \"PUT\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\n\n\nfunc (c *FakeRESTClient) Post() *Request {\n\treturn NewRequest(c, \"POST\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Delete() *Request {\n\treturn NewRequest(c, \"DELETE\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}\n\nfunc (c *FakeRESTClient) Do(req *http.Request) (*http.Response, error) {\n\tc.Req = req\n\tif c.Client != HTTPClient(nil) {\n\t\treturn c.Client.Do(req)\n\t}\n\treturn c.Resp, c.Err\n}\n\nfunc (c *FakeRESTClient) Patch(_ api.PatchType) *Request ", "output": "{\n\treturn NewRequest(c, \"PATCH\", &url.URL{Host: \"localhost\"}, testapi.Default.Version(), c.Codec)\n}"} {"input": "package iso20022\n\n\ntype TotalFeesAndTaxes40 struct {\n\n\tTotalOverheadApplied *ActiveCurrencyAndAmount `xml:\"TtlOvrhdApld,omitempty\"`\n\n\tTotalFees *ActiveCurrencyAndAmount `xml:\"TtlFees,omitempty\"`\n\n\tTotalTaxes *ActiveCurrencyAndAmount `xml:\"TtlTaxs,omitempty\"`\n\n\tCommercialAgreementReference *Max35Text `xml:\"ComrclAgrmtRef,omitempty\"`\n\n\tIndividualFee []*Fee2 `xml:\"IndvFee,omitempty\"`\n\n\tIndividualTax []*Tax31 `xml:\"IndvTax,omitempty\"`\n}\n\nfunc (t *TotalFeesAndTaxes40) SetTotalOverheadApplied(value, currency string) {\n\tt.TotalOverheadApplied = NewActiveCurrencyAndAmount(value, currency)\n}\n\nfunc (t *TotalFeesAndTaxes40) SetTotalFees(value, currency string) {\n\tt.TotalFees = NewActiveCurrencyAndAmount(value, currency)\n}\n\n\n\nfunc (t *TotalFeesAndTaxes40) SetCommercialAgreementReference(value string) {\n\tt.CommercialAgreementReference = (*Max35Text)(&value)\n}\n\nfunc (t *TotalFeesAndTaxes40) AddIndividualFee() *Fee2 {\n\tnewValue := new(Fee2)\n\tt.IndividualFee = append(t.IndividualFee, newValue)\n\treturn newValue\n}\n\nfunc (t *TotalFeesAndTaxes40) AddIndividualTax() *Tax31 {\n\tnewValue := new(Tax31)\n\tt.IndividualTax = append(t.IndividualTax, newValue)\n\treturn newValue\n}\n\nfunc (t *TotalFeesAndTaxes40) SetTotalTaxes(value, currency string) ", "output": "{\n\tt.TotalTaxes = NewActiveCurrencyAndAmount(value, currency)\n}"} {"input": "package httpserver\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\nfunc TestNewResponseRecorder(t *testing.T) {\n\tw := httptest.NewRecorder()\n\trecordRequest := NewResponseRecorder(w)\n\tif !(recordRequest.ResponseWriter == w) {\n\t\tt.Fatalf(\"Expected Response writer in the Recording to be same as the one sent\\n\")\n\t}\n\tif recordRequest.status != http.StatusOK {\n\t\tt.Fatalf(\"Expected recorded status to be http.StatusOK (%d) , but found %d\\n \", http.StatusOK, recordRequest.status)\n\t}\n}\nfunc TestWriteHeader(t *testing.T) {\n\tw := httptest.NewRecorder()\n\trecordRequest := NewResponseRecorder(w)\n\trecordRequest.WriteHeader(401)\n\tif w.Code != 401 || recordRequest.status != 401 {\n\t\tt.Fatalf(\"Expected Response status to be set to 401, but found %d\\n\", recordRequest.status)\n\t}\n}\n\n\n\nfunc TestWrite(t *testing.T) ", "output": "{\n\tw := httptest.NewRecorder()\n\tresponseTestString := \"test\"\n\trecordRequest := NewResponseRecorder(w)\n\tbuf := []byte(responseTestString)\n\t_, _ = recordRequest.Write(buf)\n\tif recordRequest.size != len(buf) {\n\t\tt.Fatalf(\"Expected the bytes written counter to be %d, but instead found %d\\n\", len(buf), recordRequest.size)\n\t}\n\tif w.Body.String() != responseTestString {\n\t\tt.Fatalf(\"Expected Response Body to be %s , but found %s\\n\", responseTestString, w.Body.String())\n\t}\n}"} {"input": "package delete\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewDeleteFilesFileidentifierParams() *DeleteFilesFileidentifierParams {\n\tvar ()\n\treturn &DeleteFilesFileidentifierParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}\n\n\n\n\n\n\ntype DeleteFilesFileidentifierParams struct {\n\n\tFileidentifier string\n\n\ttimeout time.Duration\n}\n\n\nfunc (o *DeleteFilesFileidentifierParams) WithFileidentifier(fileidentifier string) *DeleteFilesFileidentifierParams {\n\to.Fileidentifier = fileidentifier\n\treturn o\n}\n\n\nfunc (o *DeleteFilesFileidentifierParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif err := r.SetPathParam(\"fileidentifier\", o.Fileidentifier); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc NewDeleteFilesFileidentifierParamsWithTimeout(timeout time.Duration) *DeleteFilesFileidentifierParams ", "output": "{\n\tvar ()\n\treturn &DeleteFilesFileidentifierParams{\n\n\t\ttimeout: timeout,\n\t}\n}"} {"input": "package testutil\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gopkg.in/yaml.v3\"\n)\n\ntype Context struct {\n\tName string `yaml:\"name,omitempty\"`\n\tContext struct {\n\t\tNamespace string `yaml:\"namespace,omitempty\"`\n\t} `yaml:\"context,omitempty\"`\n}\n\nfunc Ctx(name string) *Context { return &Context{Name: name} }\n\n\ntype Kubeconfig map[string]interface{}\n\nfunc KC() *Kubeconfig {\n\treturn &Kubeconfig{\n\t\t\"apiVersion\": \"v1\",\n\t\t\"kind\": \"Config\"}\n}\n\nfunc (k *Kubeconfig) Set(key string, v interface{}) *Kubeconfig { (*k)[key] = v; return k }\nfunc (k *Kubeconfig) WithCurrentCtx(s string) *Kubeconfig { (*k)[\"current-context\"] = s; return k }\nfunc (k *Kubeconfig) WithCtxs(c ...*Context) *Kubeconfig { (*k)[\"contexts\"] = c; return k }\n\nfunc (k *Kubeconfig) ToYAML(t *testing.T) string {\n\tt.Helper()\n\tvar v strings.Builder\n\tif err := yaml.NewEncoder(&v).Encode(*k); err != nil {\n\t\tt.Fatalf(\"failed to encode mock kubeconfig: %v\", err)\n\t}\n\treturn v.String()\n}\n\nfunc (c *Context) Ns(ns string) *Context ", "output": "{ c.Context.Namespace = ns; return c }"} {"input": "package utils\n\nimport \"fmt\"\n\n\n\n\n\n\n\n\ntype SafeGoroutineTester struct{}\n\n\n\n\n\nfunc (s *SafeGoroutineTester) Fatalf(format string, args ...interface{}) {\n\tfmt.Printf(format+\"\\n\", args...)\n\tpanic(\"MOCK TEST FATAL FAILURE\")\n}\n\nfunc (s *SafeGoroutineTester) Errorf(format string, args ...interface{}) ", "output": "{\n\tfmt.Printf(format, args...)\n\tpanic(\"MOCK TEST ERROR\")\n}"} {"input": "package test\n\nimport (\n\t\"bytes\"\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"strings\"\n)\n\ntype marshalerForTest struct {\n\tX string\n}\n\nfunc encode(str string) string {\n\tbuf := bytes.Buffer{}\n\tb64 := base64.NewEncoder(base64.StdEncoding, &buf)\n\tif _, err := b64.Write([]byte(str)); err != nil {\n\t\tpanic(err)\n\t}\n\tif err := b64.Close(); err != nil {\n\t\tpanic(err)\n\t}\n\treturn buf.String()\n}\n\nfunc decode(str string) string {\n\tif len(str) == 0 {\n\t\treturn \"\"\n\t}\n\tb64 := base64.NewDecoder(base64.StdEncoding, strings.NewReader(str))\n\tbs := make([]byte, len(str))\n\tif n, err := b64.Read(bs); err != nil {\n\t\tpanic(err)\n\t} else {\n\t\tbs = bs[:n]\n\t}\n\treturn string(bs)\n}\n\n\n\nfunc (m *marshalerForTest) UnmarshalJSON(text []byte) error {\n\tm.X = decode(strings.TrimPrefix(strings.Trim(string(text), `\"`), \"MANUAL__\"))\n\treturn nil\n}\n\nvar _ json.Marshaler = marshalerForTest{}\nvar _ json.Unmarshaler = &marshalerForTest{}\n\ntype typeForTest struct {\n\tS string\n\tM marshalerForTest\n\tI int8\n}\n\nfunc (m marshalerForTest) MarshalJSON() ([]byte, error) ", "output": "{\n\treturn []byte(`\"MANUAL__` + encode(m.X) + `\"`), nil\n}"} {"input": "package transport\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\n\ntype Config struct {\n\tUserAgent string\n\n\tTLS TLSConfig\n\n\tUsername string\n\tPassword string\n\n\tBearerToken string\n\n\tBearerTokenFile string\n\n\tImpersonate ImpersonationConfig\n\n\tDisableCompression bool\n\n\tTransport http.RoundTripper\n\n\tWrapTransport WrapperFunc\n\n\tDial func(ctx context.Context, network, address string) (net.Conn, error)\n\n\tProxy func(*http.Request) (*url.URL, error)\n}\n\n\ntype ImpersonationConfig struct {\n\tUserName string\n\tGroups []string\n\tExtra map[string][]string\n}\n\n\nfunc (c *Config) HasCA() bool {\n\treturn len(c.TLS.CAData) > 0 || len(c.TLS.CAFile) > 0\n}\n\n\nfunc (c *Config) HasBasicAuth() bool {\n\treturn len(c.Username) != 0\n}\n\n\n\n\n\nfunc (c *Config) HasCertAuth() bool {\n\treturn (len(c.TLS.CertData) != 0 || len(c.TLS.CertFile) != 0) && (len(c.TLS.KeyData) != 0 || len(c.TLS.KeyFile) != 0)\n}\n\n\nfunc (c *Config) HasCertCallback() bool {\n\treturn c.TLS.GetCert != nil\n}\n\n\n\n\n\nfunc (c *Config) Wrap(fn WrapperFunc) {\n\tc.WrapTransport = Wrappers(c.WrapTransport, fn)\n}\n\n\ntype TLSConfig struct {\n\tCAFile string \n\tCertFile string \n\tKeyFile string \n\tReloadTLSFiles bool \n\n\tInsecure bool \n\tServerName string \n\n\tCAData []byte \n\tCertData []byte \n\tKeyData []byte \n\n\tNextProtos []string\n\n\tGetCert func() (*tls.Certificate, error) \n}\n\nfunc (c *Config) HasTokenAuth() bool ", "output": "{\n\treturn len(c.BearerToken) != 0 || len(c.BearerTokenFile) != 0\n}"} {"input": "package logsearcher\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\ntype invalidFilenameFormatErr string\n\nfunc (e invalidFilenameFormatErr) Error() string {\n\treturn string(e)\n}\n\n\n\nfunc ListFiles(dir string, ch chan string) error {\n\tif !strings.HasSuffix(dir, \"/\") {\n\t\tdir = dir + \"/\"\n\t}\n\tdirLength := len(dir)\n\n\tvar previousErr error\n\n\tfilepath.Walk(dir, func(path string, info os.FileInfo, err error) error {\n\t\tif previousErr != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err != nil {\n\t\t\tpreviousErr = err\n\t\t\tclose(ch)\n\t\t\treturn err\n\t\t}\n\t\tif !info.IsDir() {\n\t\t\tif !strings.HasPrefix(path, dir) {\n\t\t\t\tclose(ch)\n\t\t\t\treturn invalidFilenameFormatErr(fmt.Sprintf(\"Expected file %v to start with %v\", path, dir))\n\t\t\t}\n\t\t\tch <- path[dirLength:]\n\t\t}\n\t\treturn nil\n\t})\n\tif previousErr == nil {\n\t\tclose(ch)\n\t}\n\treturn previousErr\n}\n\nfunc ListFolders(dir string, ch chan string) ", "output": "{\n\tif !strings.HasSuffix(dir, \"/\") {\n\t\tdir = dir + \"/\"\n\t}\n\tdirLength := len(dir)\n\n\tvar previousErr error\n\n\tfilepath.Walk(dir, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\tpreviousErr = err\n\t\t\tclose(ch)\n\t\t\treturn err\n\t\t}\n\t\tif info.IsDir() {\n\t\t\tch <- path[dirLength:]\n\t\t}\n\t\treturn nil\n\t})\n\tif previousErr == nil {\n\t\tclose(ch)\n\t}\n}"} {"input": "package faker\n\nimport \"testing\"\n\nfunc TestFakerColorName(t *testing.T) {\n\tf := NewDefault()\n\tl := f.ColorName()\n\tassertElementInSlice(t, l, colorNames)\n}\n\n\n\nfunc TestFakerHexColor(t *testing.T) ", "output": "{\n\tf := NewDefault()\n\tc := f.HexColor()\n\tassertStringRegexp(t, \"[0-9a-f]{8}\", c)\n}"} {"input": "package transporttest\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n)\n\n\n\n\ntype ContextMatcher struct {\n\tt *testing.T\n\tttl time.Duration\n\n\tTTLDelta time.Duration\n}\n\n\ntype ContextMatcherOption interface {\n\trun(*ContextMatcher)\n}\n\n\n\ntype ContextTTL time.Duration\n\n\n\n\n\nfunc NewContextMatcher(t *testing.T, options ...ContextMatcherOption) *ContextMatcher {\n\tmatcher := &ContextMatcher{t: t, TTLDelta: DefaultTTLDelta}\n\tfor _, opt := range options {\n\t\topt.run(matcher)\n\t}\n\treturn matcher\n}\n\n\n\n\nfunc (c *ContextMatcher) Matches(got interface{}) bool {\n\tctx, ok := got.(context.Context)\n\tif !ok {\n\t\tc.t.Logf(\"expected a Context but got a %T: %v\", got, got)\n\t\treturn false\n\t}\n\n\tif c.ttl != 0 {\n\t\td, ok := ctx.Deadline()\n\t\tif !ok {\n\t\t\tc.t.Logf(\n\t\t\t\t\"expected Context to have a TTL of %v but it has no deadline\", c.ttl)\n\t\t\treturn false\n\t\t}\n\n\t\tttl := time.Until(d)\n\t\tmaxTTL := c.ttl + c.TTLDelta\n\t\tminTTL := c.ttl - c.TTLDelta\n\t\tif ttl > maxTTL || ttl < minTTL {\n\t\t\tc.t.Logf(\"TTL out of expected bounds: %v < %v < %v\", minTTL, ttl, maxTTL)\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (c *ContextMatcher) String() string {\n\treturn fmt.Sprintf(\"ContextMatcher(TTL:%v±%v)\", c.ttl, c.TTLDelta)\n}\n\nfunc (ttl ContextTTL) run(c *ContextMatcher) ", "output": "{\n\tc.ttl = time.Duration(ttl)\n}"} {"input": "package utils\n\n\n\n\nfunc GetTernary(condition bool, a interface{}, b interface{}) interface{} ", "output": "{\n\tif condition {\n\t\treturn a\n\t}\n\treturn b\n}"} {"input": "package main\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n\t. \"github.com/CodyGuo/win\"\n)\n\nvar (\n\trt *gin.Engine\n\trootPrefix string\n)\n\nfunc main() {\n\trt = gin.Default()\n\trouter(rt)\n\n\tgo rt.Run(\":8945\")\n\n\tc := make(chan os.Signal, 1)\n\n\tsignal.Notify(c, os.Interrupt, os.Kill, syscall.SIGTERM)\n\t<-c\n\n\n\tos.Exit(0)\n}\n\n\n\n\nfunc ShutDown(c *gin.Context) {\n\tgetPrivileges()\n\tExitWindowsEx(EWX_SHUTDOWN, 0)\n}\n\nfunc getPrivileges() {\n\tvar hToken HANDLE\n\tvar tkp TOKEN_PRIVILEGES\n\n\tOpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &hToken)\n\tLookupPrivilegeValueA(nil, StringToBytePtr(SE_SHUTDOWN_NAME), &tkp.Privileges[0].Luid)\n\ttkp.PrivilegeCount = 1\n\ttkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED\n\tAdjustTokenPrivileges(hToken, false, &tkp, 0, nil, nil)\n}\n\nfunc router(r *gin.Engine) ", "output": "{\n\tg := &r.RouterGroup\n\tif rootPrefix != \"\" {\n\t\tg = r.Group(rootPrefix)\n\t}\n\n\t{\n\t\tg.GET(\"/\", func(c *gin.Context) { c.String(200, \"ok\") })\n\t\tg.GET(\"/ShutDown\", ShutDown)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\nvar fP2K = p2K\n\nfunc TestP2K(t *testing.T) {\n\tresult, _ := fP2K(1)\n\texpected := 0.453592\n\tif result != expected {\n\t\tt.Errorf(\"Result: %v Expected %v\", result, expected)\n\t}\n}\n\n\n\nfunc TestP2KNegativeValue(t *testing.T) ", "output": "{\n\tresult, err := fP2K(-1)\n\texpected := 0.453592\n\tif err == nil {\n\t\tt.Errorf(\"fP2K not support negative value\")\n\t}\n\tif result != 0 {\n\t\tt.Errorf(\"Result: %v Expected %v\", result, expected)\n\t}\n}"} {"input": "package missinggo\n\nimport \"io\"\n\ntype StatWriter struct {\n\tWritten int64\n\tw io.Writer\n}\n\n\n\nfunc NewStatWriter(w io.Writer) *StatWriter {\n\treturn &StatWriter{w: w}\n}\n\nvar ZeroReader zeroReader\n\ntype zeroReader struct{}\n\nfunc (me zeroReader) Read(b []byte) (n int, err error) {\n\tfor i := range b {\n\t\tb[i] = 0\n\t}\n\tn = len(b)\n\treturn\n}\n\nfunc (me *StatWriter) Write(b []byte) (n int, err error) ", "output": "{\n\tn, err = me.w.Write(b)\n\tme.Written += int64(n)\n\treturn\n}"} {"input": "package cloudguard\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype RiskScoreAggregationCollection struct {\n\n\tItems []RiskScoreAggregation `mandatory:\"true\" json:\"items\"`\n}\n\n\n\nfunc (m RiskScoreAggregationCollection) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package xml\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding/xml\"\n\t\"github.com/graniticio/granitic/v2/ws\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestMarshallAndWrite(t *testing.T) {\n\n\tmw := new(MarshalingWriter)\n\trw := new(resWriter)\n\n\tmw.MarshalAndWrite(target{A: 1}, rw)\n\n\tif rw.sw.String() != \"1\" {\n\t\tt.Fail()\n\t}\n\n}\n\nfunc TestUnmarshalling(t *testing.T) {\n\n\tr := new(http.Request)\n\tsr := strings.NewReader(\"1\")\n\n\trc := ioutil.NopCloser(sr)\n\n\tr.Body = rc\n\n\tum := new(Unmarshaller)\n\n\twsr := new(ws.Request)\n\twsr.RequestBody = new(target)\n\n\tum.Unmarshall(context.Background(), r, wsr)\n\n\ttar := wsr.RequestBody.(*target)\n\n\tif tar.A != 1 {\n\t\tt.Fail()\n\t}\n\n}\n\ntype target struct {\n\tXMLName xml.Name `xml:\"content\"`\n\tA int64 `xml:\"a\"`\n}\n\ntype resWriter struct {\n\tsw bytes.Buffer\n}\n\nfunc (rw *resWriter) Header() http.Header {\n\treturn nil\n}\n\n\n\nfunc (rw *resWriter) WriteHeader(statusCode int) {\n\n}\n\nfunc (rw *resWriter) Write(b []byte) (int, error) ", "output": "{\n\treturn rw.sw.Write(b)\n}"} {"input": "package server\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n)\n\nconst (\n\tChatReqTypeSetNickname = 101 + iota\n\tChatReqTypeGetNickname\n\tChatReqTypeListRooms\n\tChatReqTypeJoin\n\tChatReqTypeListNames\n\tChatReqTypeHide\n\tChatReqTypeUnhide\n\tChatReqTypeMsg\n\tChatReqTypeLeave\n)\n\n\ntype ChatRequest struct {\n\tWho *Chatter `json:\"-\"` \n\tRoomName string `json:\"roomName\"` \n\tReqType int `json:\"reqType\"` \n\tContent string `json:\"content\"` \n}\n\n\n\n\n\n\nfunc (r *ChatRequest) String() string {\n\tb, _ := json.Marshal(r)\n\treturn string(b)\n}\n\nfunc ChatRequestNew(c *Chatter, room string, reqt int, cont string) (*ChatRequest, error) ", "output": "{\n\tif reqt < ChatReqTypeSetNickname || reqt > ChatReqTypeLeave {\n\t\treturn nil, errors.New(\"Request Type is out of range.\")\n\t}\n\treturn &ChatRequest{\n\t\tWho: c,\n\t\tRoomName: room,\n\t\tReqType: reqt,\n\t\tContent: cont,\n\t}, nil\n}"} {"input": "package sim\n\nimport (\n\t\"github.com/sacloud/libsacloud/v2/helper/validate\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud/types\"\n)\n\ntype DeactivateRequest struct {\n\tID types.ID `request:\"-\" validate:\"required\"`\n}\n\n\n\nfunc (req *DeactivateRequest) Validate() error ", "output": "{\n\treturn validate.Struct(req)\n}"} {"input": "package blocker\n\nimport \"sort\"\n\ntype sources []string\n\nfunc (s *sources) Add(source string) {\n\tn := sort.SearchStrings(*s, source)\n\n\tif n < len(*s) && (*s)[n] == source {\n\t\treturn\n\t}\n\n\t*s = append(*s, \"\")\n\tcopy((*s)[n+1:], (*s)[n:])\n\t(*s)[n] = source\n}\n\nfunc (s *sources) Remove(source string) bool {\n\tif s == nil {\n\t\treturn false\n\t}\n\n\tn := sort.SearchStrings(*s, source)\n\n\tif n < len(*s) && (*s)[n] == source {\n\t\t*s = append((*s)[:n], (*s)[n+1:]...)\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc (s *sources) Has(source string) bool {\n\tif s == nil {\n\t\treturn false\n\t}\n\n\tn := sort.SearchStrings(*s, source)\n\n\tif n < len(*s) && (*s)[n] == source {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\n\nfunc newSources(s ...string) *sources {\n\tret := sources(s)\n\treturn &ret\n}\n\nfunc (s *sources) Len() int ", "output": "{\n\treturn len(*s)\n}"} {"input": "package stack\n\nimport (\n\t\"jvm/instructions/base\"\n\t\"jvm/rtda\"\n)\n\ntype SWAP struct{ base.NoOperandInstruction }\n\n\n\nfunc (self *SWAP) Execute(frame *rtda.Frame) ", "output": "{\n\tstack := frame.OperandStack()\n\tslot1 := stack.PopSlot()\n\tslot2 := stack.PopSlot()\n\tstack.PushSlot(slot1)\n\tstack.PushSlot(slot2)\n}"} {"input": "package sdl\n\n\nimport \"C\"\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"unsafe\"\n)\n\nconst SamplingRate = 11025\n\nfunc initAudio() {\n\tvar spec C.SDL_AudioSpec\n\tspec.freq = C.int(SamplingRate)\n\tspec.format = C.AUDIO_S8\n\tspec.channels = 1\n\tspec.samples = 512\n\tspec.userdata = nil\n\tC.openAudio(&spec)\n}\n\n\n\n\nfunc Play(input io.Reader) error {\n\tbuf, err := ioutil.ReadAll(input)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmutex.Lock()\n\tC.play((*C.Uint8)(unsafe.Pointer(&buf[0])), C.int(len(buf)))\n\tmutex.Unlock()\n\treturn nil\n}\n\nfunc ClearAudioBuffer() {\n\tmutex.Lock()\n\tC.stop()\n\tmutex.Unlock()\n}\n\nfunc BufferAudio(sound []int8) ", "output": "{\n\tif len(sound) == 0 {\n\t\treturn\n\t}\n\tmutex.Lock()\n\tC.play((*C.Uint8)(unsafe.Pointer(&sound[0])), C.int(len(sound)))\n\tmutex.Unlock()\n}"} {"input": "package common\n\nimport (\n\t\"log\"\n\t\"time\"\n\n\t\"gopkg.in/mgo.v2\"\n)\n\nvar session *mgo.Session\n\nfunc GetSession() *mgo.Session {\n\tif session == nil {\n\t\tvar err error\n\t\tsession, err = mgo.DialWithInfo(&mgo.DialInfo{\n\t\t\tAddrs: []string{AppConfig.MongoDBHost},\n\t\t\tUsername: AppConfig.DBUser,\n\t\t\tPassword: AppConfig.DBPwd,\n\t\t\tTimeout: 60 * time.Second,\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"[GetSession]: %s\\n\", err)\n\t\t}\n\t}\n\treturn session\n}\n\n\n\nfunc addIndexes() {\n\tvar err error\n\tuserIndex := mgo.Index{\n\t\tKey: []string{\"email\"},\n\t\tUnique: true,\n\t\tBackground: true,\n\t\tSparse: true,\n\t}\n\tsession := GetSession().Copy()\n\tdefer session.Close()\n\tuserCol := session.DB(AppConfig.Database).C(\"users\")\n\n\terr = userCol.EnsureIndex(userIndex)\n\tif err != nil {\n\t\tlog.Fatalf(\"[addIndexes]: %s\\n\", err)\n\t}\n}\n\nfunc createDbSession() ", "output": "{\n\tvar err error\n\tsession, err = mgo.DialWithInfo(&mgo.DialInfo{\n\t\tAddrs: []string{AppConfig.MongoDBHost},\n\t\tUsername: AppConfig.DBUser,\n\t\tPassword: AppConfig.DBPwd,\n\t\tTimeout: 60 * time.Second,\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"[createDbSession]: %s\\n\", err)\n\t}\n}"} {"input": "package cdsclient\n\nimport (\n\t\"context\"\n\t\"fmt\"\n)\n\n\n\nfunc (c *client) Maintenance(enable bool, hooks bool) error ", "output": "{\n\t_, err := c.PostJSON(context.Background(), fmt.Sprintf(\"/admin/maintenance?enable=%v&withHook=%v\", enable, hooks), nil, nil)\n\treturn err\n}"} {"input": "package channels\n\nimport (\n\t\"fmt\"\n)\n\n\n\nfunc main() {\n\ts := []int{7, 2, 8, -9, 4, 0}\n\n\tc := make(chan int)\n\tgo sum(s[:len(s)/2], c)\n\tgo sum(s[len(s)/2:], c)\n\n\tx, y := <-c, <-c \n\n\tfmt.Println(x, y, x+y)\n}\n\nfunc sum(s []int, c chan int) ", "output": "{\n\tsum := 0\n\tfor _, v := range s {\n\t\tsum += v\n\t}\n\tc <- sum \n}"} {"input": "package underscore\n\n\n\nfunc SelectBy(source interface{}, properties map[string]interface{}) interface{} {\n\treturn Select(source, func (value, _ interface{}) bool {\n\t\treturn IsMatch(value, properties)\n\t})\n}\n\n\nfunc (this *Query) Select(predicate interface{}) Queryer {\n\tthis.source = Select(this.source, predicate)\n\treturn this\n}\n\nfunc (this *Query) SelectBy(properties map[string]interface{}) Queryer {\n\tthis.source = SelectBy(this.source, properties)\n\treturn this\n}\n\nfunc Select(source, predicate interface{}) interface{} ", "output": "{\n\treturn filter(source, predicate, true)\n}"} {"input": "package common\n\ntype mockUploader struct {\n}\n\nfunc (uploader *mockUploader) Upload(destination string, path string) error {\n\treturn nil\n}\n\n\n\nfunc newMockUploader() Uploader {\n\treturn new(mockUploader)\n}\n\nfunc (uploader *mockUploader) Url(sourceAssetId, templateId, placeholderSize string, page int32) string ", "output": "{\n\treturn \"mock://\" + sourceAssetId\n}"} {"input": "package mysql\n\n\n\nimport (\n\t\"context\"\n)\n\n\n\n\nfunc A0In0Out(ctx context.Context, db DB) error ", "output": "{\n\tconst sqlstr = `CALL a_bit_of_everything.a_0_in_0_out()`\n\tlogf(sqlstr)\n\tif _, err := db.ExecContext(ctx, sqlstr); err != nil {\n\t\treturn logerror(err)\n\t}\n\treturn nil\n}"} {"input": "package main\n\ntype Human struct {\n\tname string\n\tage int\n\tphone string\n}\n\ntype Student struct {\n\tHuman\n\tschool string\n\tloan float32\n}\n\ntype Employee struct {\n\tHuman\n\tcompany string\n\tmoney float32\n}\n\n\ntype Men interface {\n\tSayHi()\n\tSing(lyrics string)\n\tGuzzle(beerStein string)\n}\n\ntype YoungChap interface {\n\tSayHi()\n\tSing(lyrics string)\n\tBorrowMoney(amount float32)\n}\n\ntype ElderlyGent interface {\n\tSayHi()\n\tSing(song string)\n\tSpendSalary(amount float32)\n}\n\nfunc (h *Human) SayHi() {\n\tfmt.Printf(\"Hi, I am %s you can call me on %s\\n\", h.name, h.phone)\n}\n\nfunc (h *Human) Sing(lyrics string) {\n\tfmt.Println(\"La la, la la la, la la la la...\", lyrics)\n}\n\nfunc (h *Human) Guzzle(beerStein string) {\n\tfmt.Println(\"Guzzle Guzzle Guzzle...\", beerStein)\n}\n\n\n\n\nfunc (s *Student) BorrowMoney(amount float32) {\n\ts.loan += amount\n}\n\nfunc (e *Employee) SpendSalary(amount float32) {\n\te.money -= e.amount\n}\n\nfunc (e *Employee) SayHi() ", "output": "{\n\tfmt.Printf(\"Hi, I am %s, I work at %s. Call me on %s\\n\", e.name, e.company, e.phone)\n}"} {"input": "package archive\n\nimport (\n\t\"archive/tar\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/docker/docker/pkg/longpath\"\n)\n\n\n\n\n\n\n\nfunc getWalkRoot(srcPath string, include string) string {\n\treturn filepath.Join(srcPath, include)\n}\n\n\n\n\nfunc CanonicalTarNameForPath(p string) (string, error) {\n\tif strings.Contains(p, \"/\") {\n\t\treturn \"\", fmt.Errorf(\"Windows path contains forward slash: %s\", p)\n\t}\n\treturn strings.Replace(p, string(os.PathSeparator), \"/\", -1), nil\n\n}\n\n\n\nfunc chmodTarEntry(perm os.FileMode) os.FileMode {\n\tperm &= 0755\n\tperm |= 0111\n\n\treturn perm\n}\n\nfunc setHeaderForSpecialDevice(hdr *tar.Header, ta *tarAppender, name string, stat interface{}) (nlink uint32, inode uint64, err error) {\n\treturn\n}\n\n\n\nfunc handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error {\n\treturn nil\n}\n\nfunc handleLChmod(hdr *tar.Header, path string, hdrInfo os.FileInfo) error {\n\treturn nil\n}\n\nfunc getFileUIDGID(stat interface{}) (int, int, error) {\n\treturn 0, 0, nil\n}\n\nfunc fixVolumePathPrefix(srcPath string) string ", "output": "{\n\treturn longpath.AddPrefix(srcPath)\n}"} {"input": "package transformers\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"sigs.k8s.io/kustomize/pkg/resmap\"\n\t\"sigs.k8s.io/kustomize/pkg/transformers/config\"\n)\n\n\ntype mapTransformer struct {\n\tm map[string]string\n\tfieldSpecs []config.FieldSpec\n}\n\nvar _ Transformer = &mapTransformer{}\n\n\nfunc NewLabelsMapTransformer(\n\tm map[string]string, fs []config.FieldSpec) (Transformer, error) {\n\treturn NewMapTransformer(fs, m)\n}\n\n\nfunc NewAnnotationsMapTransformer(\n\tm map[string]string, fs []config.FieldSpec) (Transformer, error) {\n\treturn NewMapTransformer(fs, m)\n}\n\n\n\n\n\n\nfunc (o *mapTransformer) Transform(m resmap.ResMap) error {\n\tfor id := range m {\n\t\tobjMap := m[id].Map()\n\t\tfor _, path := range o.fieldSpecs {\n\t\t\tif !id.Gvk().IsSelected(&path.Gvk) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\terr := mutateField(objMap, path.PathSlice(), path.CreateIfNotPresent, o.addMap)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (o *mapTransformer) addMap(in interface{}) (interface{}, error) {\n\tm, ok := in.(map[string]interface{})\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"%#v is expected to be %T\", in, m)\n\t}\n\tfor k, v := range o.m {\n\t\tm[k] = v\n\t}\n\treturn m, nil\n}\n\nfunc NewMapTransformer(\n\tpc []config.FieldSpec, m map[string]string) (Transformer, error) ", "output": "{\n\tif m == nil {\n\t\treturn NewNoOpTransformer(), nil\n\t}\n\tif pc == nil {\n\t\treturn nil, errors.New(\"fieldSpecs is not expected to be nil\")\n\t}\n\treturn &mapTransformer{fieldSpecs: pc, m: m}, nil\n}"} {"input": "package gorocksdb\n\n\nimport \"C\"\n\n\ntype Cache struct {\n\tc *C.rocksdb_cache_t\n}\n\n\nfunc NewLRUCache(capacity int) *Cache {\n\treturn NewNativeCache(C.rocksdb_cache_create_lru(C.size_t(capacity)))\n}\n\n\n\n\n\nfunc (c *Cache) Destroy() {\n\tC.rocksdb_cache_destroy(c.c)\n\tc.c = nil\n}\n\nfunc NewNativeCache(c *C.rocksdb_cache_t) *Cache ", "output": "{\n\treturn &Cache{c}\n}"} {"input": "package cli\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"strconv\"\n)\n\n\nfunc CheckError(err error) {\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}\n\n\nfunc CheckFatalError(err error) {\n\tif err != nil {\n\t\tCheckError(fmt.Errorf(\"Fatal error: %v\", err))\n\t}\n}\n\n\nfunc FileExists(path string) bool {\n\t_, err := os.Stat(path)\n\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tif os.IsNotExist(err) {\n\t\treturn false\n\t}\n\n\treturn false\n}\n\n\n\n\n\nfunc StopExecution(code int, pidfile string) {\n\tos.Remove(pidfile)\n\tos.Exit(code)\n}\n\nfunc WritePid(pidfile string) ", "output": "{\n\tdirname := path.Dir(pidfile)\n\tif !FileExists(dirname) {\n\t\tCheckFatalError(fmt.Errorf(\"Directory \\\"%s\\\" doesn't exist\", dirname))\n\t}\n\n\tif FileExists(pidfile) {\n\t\tCheckFatalError(fmt.Errorf(\"File \\\"%s\\\" already exist\", pidfile))\n\t}\n\n\tpid := os.Getpid()\n\terr := ioutil.WriteFile(pidfile, []byte(strconv.Itoa(pid)), os.FileMode(0644))\n\tCheckFatalError(err)\n}"} {"input": "package system\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nconst (\n\texecErrorMsgFmt = \"Running command: '%s', stdout: '%s', stderr: '%s'\"\n\texecShortErrorMaxLines = 100\n)\n\ntype ExecError struct {\n\tCommand string\n\tStdOut string\n\tStdErr string\n}\n\nfunc NewExecError(cmd, stdout, stderr string) ExecError {\n\treturn ExecError{\n\t\tCommand: cmd,\n\t\tStdOut: stdout,\n\t\tStdErr: stderr,\n\t}\n}\n\nfunc (e ExecError) Error() string {\n\treturn fmt.Sprintf(execErrorMsgFmt, e.Command, e.StdOut, e.StdErr)\n}\n\n\n\n\nfunc (e ExecError) truncateStr(in string, maxLines int) string {\n\toutLines := strings.Split(in, \"\\n\")\n\tif i := len(outLines); i > maxLines {\n\t\toutLines = outLines[i-maxLines:]\n\t}\n\n\treturn strings.Join(outLines, \"\\n\")\n}\n\nfunc (e ExecError) ShortError() string ", "output": "{\n\toutStr := e.truncateStr(e.StdOut, execShortErrorMaxLines)\n\terrStr := e.truncateStr(e.StdErr, execShortErrorMaxLines)\n\treturn fmt.Sprintf(execErrorMsgFmt, e.Command, outStr, errStr)\n}"} {"input": "package extended\n\nimport \"jvmgo/ch06/instructions/base\"\nimport \"jvmgo/ch06/rtda\"\n\n\ntype IFNULL struct{ base.BranchInstruction }\n\nfunc (self *IFNULL) Execute(frame *rtda.Frame) {\n\tref := frame.OperandStack().PopRef()\n\tif ref == nil {\n\t\tbase.Branch(frame, self.Offset)\n\t}\n}\n\n\ntype IFNONNULL struct{ base.BranchInstruction }\n\n\n\nfunc (self *IFNONNULL) Execute(frame *rtda.Frame) ", "output": "{\n\tref := frame.OperandStack().PopRef()\n\tif ref != nil {\n\t\tbase.Branch(frame, self.Offset)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/EconomistDigitalSolutions/goberry/web\"\n\n\t\"github.com/EconomistDigitalSolutions/watchman/journal\"\n\t_ \"github.com/EconomistDigitalSolutions/watchman/meter\"\n)\n\nvar (\n\tport string\n\tbuildstamp string\n\tgithash string\n\tversion string\n\tramlFile string\n\tserviceName string\n)\n\n\n\nfunc main() {\n\tflag.Parse()\n\n\tweb.NewRouter(ramlFile, buildstamp, githash)\n\n\tif version != \"\" {\n\t\tjournal.LogChannel(\"build\", fmt.Sprintf(\"build date: %s commit: %s\", buildstamp, githash))\n\t}\n\n\tjournal.LogChannel(\"information\", fmt.Sprintf(\"%s up on port %s\", serviceName, port))\n\tlog.Fatal(http.ListenAndServe(port, nil))\n}\n\nfunc init() ", "output": "{\n\tflag.StringVar(&port, \"port\", \":9494\", \"port to listen on\")\n\tflag.StringVar(&version, \"version\", \"\", \"output build date and commit data\")\n\tflag.StringVar(&ramlFile, \"ramlFile\", \"api.raml\", \"RAML file to parse\")\n\n\tserviceName = os.Getenv(\"SERVICE_NAME\")\n\tif serviceName == \"\" {\n\t\tserviceName = filepath.Base(os.Args[0])\n\t}\n\tjournal.Service = serviceName\n\n}"} {"input": "package help\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\ntype EvtPool struct {\n\theader DListNode\n}\n\nfunc (this *EvtPool) Init() {\n\tthis.header.Init(nil)\n}\n\nfunc (this *EvtPool) Eat(name string) {\n\tfmt.Printf(\"吃%s\\n\", name)\n}\n\nfunc (this *EvtPool) Post(d IEvent) bool {\n\n\tn := &DListNode{}\n\tn.Init(d)\n\n\tif !d.AddNode(n) {\n\t\treturn false\n\t}\n\n\told_pre := this.header.Pre\n\n\tthis.header.Pre = n\n\tn.Next = &this.header\n\tn.Pre = old_pre\n\told_pre.Next = n\n\n\treturn true\n}\n\nfunc (this *EvtPool) Run() {\n\tfor {\n\t\tif this.header.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\n\t\tn := this.header.Next\n\n\t\tn.Data.(IEvent).Exec(this)\n\n\t\tn.Data.(IEvent).Destroy()\n\t}\n}\n\ntype Evt_eat struct {\n\tEvt_base\n\tFoodName string\n}\n\n\n\nfunc TestDlist(t *testing.T) {\n\n\tvar g_Pool EvtPool\n\tg_Pool.Init()\n\n\tg_Pool.Post(&Evt_eat{FoodName: \"西瓜\"})\n\tg_Pool.Post(&Evt_eat{FoodName: \"葡萄\"})\n\tg_Pool.Post(&Evt_eat{FoodName: \"黄瓜\"})\n\tg_Pool.Post(&Evt_eat{FoodName: \"大蒜\"})\n\n\tg_Pool.Run()\n}\n\nfunc (this *Evt_eat) Exec() bool ", "output": "{\n\treturn true\n}"} {"input": "package client \n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/docker/docker/api/types/swarm\"\n\t\"github.com/docker/docker/errdefs\"\n)\n\nfunc TestNodeUpdateError(t *testing.T) {\n\tclient := &Client{\n\t\tclient: newMockClient(errorMock(http.StatusInternalServerError, \"Server error\")),\n\t}\n\n\terr := client.NodeUpdate(context.Background(), \"node_id\", swarm.Version{}, swarm.NodeSpec{})\n\tif err == nil || err.Error() != \"Error response from daemon: Server error\" {\n\t\tt.Fatalf(\"expected a Server Error, got %v\", err)\n\t}\n\tif !errdefs.IsSystem(err) {\n\t\tt.Fatalf(\"expected a Server Error, got %T\", err)\n\t}\n}\n\n\n\nfunc TestNodeUpdate(t *testing.T) ", "output": "{\n\texpectedURL := \"/nodes/node_id/update\"\n\n\tclient := &Client{\n\t\tclient: newMockClient(func(req *http.Request) (*http.Response, error) {\n\t\t\tif !strings.HasPrefix(req.URL.Path, expectedURL) {\n\t\t\t\treturn nil, fmt.Errorf(\"Expected URL '%s', got '%s'\", expectedURL, req.URL)\n\t\t\t}\n\t\t\tif req.Method != \"POST\" {\n\t\t\t\treturn nil, fmt.Errorf(\"expected POST method, got %s\", req.Method)\n\t\t\t}\n\t\t\treturn &http.Response{\n\t\t\t\tStatusCode: http.StatusOK,\n\t\t\t\tBody: ioutil.NopCloser(bytes.NewReader([]byte(\"body\"))),\n\t\t\t}, nil\n\t\t}),\n\t}\n\n\terr := client.NodeUpdate(context.Background(), \"node_id\", swarm.Version{}, swarm.NodeSpec{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}"} {"input": "package slack\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/nlopes/slack\"\n\t\"strings\"\n)\n\nfunc getUserWithUsername(username string) (user slack.User, err error) {\n\n\tusers, err := slackClient.GetUsers()\n\tif err != nil {\n\t\treturn slack.User{}, err\n\t}\n\n\tfor _, user := range users {\n\t\tif user.Name == username {\n\t\t\treturn user, nil\n\t\t}\n\t}\n\n\treturn slack.User{}, errors.New(fmt.Sprintf(\"No user with username %s\", username))\n}\n\n\n\nfunc parseUsername(name string) (username string, err error) ", "output": "{\n\n\tusername = strings.ToLower(name)\n\n\tif strings.Contains(username, \" \") {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"%s is not a Slack username\", name))\n\t}\n\n\tif strings.Contains(name, \"@\") {\n\t\tusername = strings.Replace(username, \"@\", \"\", 1)\n\t}\n\n\treturn\n}"} {"input": "package service\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/juju/errors\"\n\t\"github.com/juju/utils/shell\"\n\n\t\"github.com/juju/juju/juju/osenv\"\n\t\"github.com/juju/juju/service/common\"\n)\n\nconst (\n\tmaxAgentFiles = 20000\n\n\tagentServiceTimeout = 300 \n)\n\n\n\nfunc AgentConf(info AgentInfo, renderer shell.Renderer) common.Conf {\n\tconf := common.Conf{\n\t\tDesc: fmt.Sprintf(\"juju agent for %s\", info.name),\n\t\tExecStart: info.cmd(renderer),\n\t\tLogfile: info.logFile(renderer),\n\t\tEnv: osenv.FeatureFlags(),\n\t\tTimeout: agentServiceTimeout,\n\t}\n\n\tswitch info.Kind {\n\tcase AgentKindMachine:\n\t\tconf.Limit = map[string]int{\n\t\t\t\"nofile\": maxAgentFiles,\n\t\t}\n\tcase AgentKindUnit:\n\t\tconf.Desc = \"juju unit agent for \" + info.ID\n\t}\n\n\treturn conf\n}\n\n\n\n\n\n\nfunc ContainerAgentConf(info AgentInfo, renderer shell.Renderer, containerType string) common.Conf {\n\tconf := AgentConf(info, renderer)\n\n\tenvVars := map[string]string{\n\t\tosenv.JujuContainerTypeEnvKey: containerType,\n\t}\n\tosenv.MergeEnvironment(envVars, conf.Env)\n\tconf.Env = envVars\n\n\treturn conf\n}\n\n\n\nfunc ShutdownAfterConf(serviceName string) (common.Conf, error) {\n\tif serviceName == \"\" {\n\t\treturn common.Conf{}, errors.New(`missing \"after\" service name`)\n\t}\n\tdesc := \"juju shutdown job\"\n\treturn shutdownAfterConf(serviceName, desc), nil\n}\n\n\n\nfunc shutdownAfterConf(serviceName, desc string) common.Conf ", "output": "{\n\treturn common.Conf{\n\t\tDesc: desc,\n\t\tTransient: true,\n\t\tAfterStopped: serviceName,\n\t\tExecStart: \"/sbin/shutdown -h now\",\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/url\"\n\t\"sort\"\n\t\"strings\"\n)\n\ntype helloTransport interface {\n\tConnect(addr string) error\n\tClose() error\n\tRequest(req string) (reply string, err error)\n}\n\ntype transGenerator func() (helloTransport, error)\n\nvar transporter map[string]transGenerator = make(map[string]transGenerator)\n\nfunc registerTransport(id string, gen transGenerator) {\n\ttransporter[id] = gen\n}\n\nfunc transportList() []string {\n\tvar transports = make([]string, 0, len(transporter))\n\tfor id := range transporter {\n\t\ttransports = append(transports, id)\n\t}\n\tsort.StringSlice(transports).Sort()\n\treturn transports\n}\n\nfunc availableTransports() string {\n\tvar transports = transportList()\n\treturn strings.Join(transports, \",\")\n}\n\nfunc firstTransport() string {\n\tvar transports = transportList()\n\treturn transports[0]\n}\n\nfunc defaultAddr(addr string) string {\n\treturn fmt.Sprintf(\"%s://%s\", firstTransport(), addr)\n}\n\n\n\nfunc newTransport(addr string) (helloTransport, error) ", "output": "{\n\tvar uri, err = url.Parse(addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif generate, ok := transporter[uri.Scheme]; ok {\n\t\treturn generate()\n\t}\n\treturn nil, fmt.Errorf(\"invalid transport %q\", uri.Scheme)\n}"} {"input": "package taskqueue\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\ntype ReqRepTask struct {\n\tMsg string\n\tResultChan chan string\n}\n\ntype ReqRepTaskQueue chan *ReqRepTask\n\nfunc NewReqRepTaskQueue(workerNum int) ReqRepTaskQueue {\n\tqueue := make(ReqRepTaskQueue, 500)\n\n\tfor i := 0; i < workerNum; i++ {\n\t\tgo reqRepTaskQueueWorker(queue, i)\n\t}\n\n\treturn queue\n}\n\n\n\nfunc reqRepTaskQueueWorker(queue ReqRepTaskQueue, index int) ", "output": "{\n\tfor task := range queue {\n\t\trandom := rand.Intn(3)\n\t\ttime.Sleep(time.Duration(random) * time.Second)\n\n\t\techo := fmt.Sprintf(\"ReqRepTaskQueueWorker [%d] echo: %s\", index, task.Msg)\n\t\ttask.ResultChan <- echo\n\n\t\tclose(task.ResultChan)\n\t}\n}"} {"input": "package league\n\ntype Division struct {\n\tname string\n\tteams map[string]*Team\n\tconfrence *Conference\n\tleague *League\n}\n\nfunc (division *Division) GetTeams() map[string]*Team {\n\treturn division.teams\n}\n\nfunc (division *Division) GetName() string {\n\treturn division.name\n}\n\n\n\nfunc (division *Division) getLeague() *League {\n\treturn division.league\n}\n\nfunc (division *Division) GetConference() *Conference ", "output": "{\n\treturn division.confrence\n}"} {"input": "package money_test\n\nimport (\n\t\"github.com/reiver/go-money\"\n\n\t\"testing\"\n)\n\nfunc TestCADNickel(t *testing.T) {\n\n\tvar expected money.CAD = money.CADCents(5)\n\tvar actual money.CAD = money.CADNickel()\n\n\tif expected != actual {\n\t\tt.Error(\"The actual value is not equal to the expected value.\")\n\t\tt.Logf(\"EXPECTED: %q (%#v)\", expected, expected)\n\t\tt.Logf(\"ACTUAL: %q (%#v)\", actual, actual)\n\t\treturn\n\t}\n}\n\n\n\nfunc TestUSDNickel(t *testing.T) ", "output": "{\n\n\tvar expected money.USD = money.USDCents(5)\n\tvar actual money.USD = money.USDNickel()\n\n\tif expected != actual {\n\t\tt.Error(\"The actual value is not equal to the expected value.\")\n\t\tt.Logf(\"EXPECTED: %q (%#v)\", expected, expected)\n\t\tt.Logf(\"ACTUAL: %q (%#v)\", actual, actual)\n\t\treturn\n\t}\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/labstack/echo\"\n\n\t\"projects/onix/models\"\n\t\"projects/onix/utils\"\n)\n\n\ntype PostsController struct{}\n\n\nfunc (*PostsController) Get(c echo.Context) error {\n\tvar model models.Post\n\tvar title = c.QueryParam(\"title\")\n\n\tret, err := model.Get(title)\n\tif err != nil {\n\t\treturn c.JSON(400, utils.ErrMarshal(err.Error()))\n\t}\n\n\treturn c.JSON(200, ret)\n}\n\n\n\n\n\nfunc (*PostsController) Save(c echo.Context) error {\n\tvar model models.Post\n\tvar payload models.PostPayload\n\tvar status = c.QueryParam(\"status\")\n\n\tif err := c.Bind(&payload); err != nil {\n\t\treturn c.JSON(400, utils.ErrMarshal(err.Error()))\n\t}\n\n\tiss := 1\n\n\tpayload.AuthorID = iss\n\tret, err := model.Create(payload, status)\n\tif err != nil {\n\t\treturn c.JSON(400, utils.ErrMarshal(err.Error()))\n\t}\n\treturn c.JSON(200, ret)\n}\n\n\nfunc (*PostsController) Update(c echo.Context) error {\n\tvar model models.Post\n\tvar payload models.PostPayload\n\tvar status = c.QueryParam(\"status\")\n\n\tif err := c.Bind(&payload); err != nil {\n\t\treturn c.JSON(400, utils.ErrMarshal(err.Error()))\n\t}\n\n\tiss := 1\n\n\tpayload.UpdatedBy = iss\n\tret, err := model.Update(c.P(0), payload, status)\n\tif err != nil {\n\t\treturn c.JSON(400, utils.ErrMarshal(err.Error()))\n\t}\n\treturn c.JSON(200, ret)\n}\n\nfunc (*PostsController) GetOne(c echo.Context) error ", "output": "{\n\tvar model models.Post\n\n\tret, err := model.GetOne(c.P(0))\n\tif err != nil {\n\t\treturn c.JSON(400, utils.ErrMarshal(err.Error()))\n\t}\n\n\treturn c.JSON(200, ret)\n}"} {"input": "package cmake\n\nimport (\n\t\"github.com/pinpt/dialect/pkg/types\"\n\t\"strings\"\n)\n\ntype CMakeExaminer struct {\n\tinDoubleComment bool\n}\n\nfunc (e *CMakeExaminer) Examine(language string, filename string, line *types.DialectLine) error {\n\tlineBuf := strings.TrimSpace(line.Contents)\n\tif strings.HasPrefix(lineBuf, \"# \") {\n\t\tline.IsComment = true\n\t} else {\n\t\tline.IsCode = true\n\t}\n\n\treturn nil\n}\n\nfunc (e *CMakeExaminer) NewExaminer() types.DialectExaminer {\n\tex := new(CMakeExaminer)\n\treturn ex\n}\n\n\n\nfunc init() ", "output": "{\n\ttypes.RegisterExaminer(\"CMake\", &CMakeExaminer{})\n}"} {"input": "package app\n\nimport (\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n\t\"k8s.io/kubernetes/pkg/controller/disruption\"\n)\n\n\n\nfunc startDisruptionController(ctx ControllerContext) (bool, error) ", "output": "{\n\tif !ctx.AvailableResources[schema.GroupVersionResource{Group: \"policy\", Version: \"v1beta1\", Resource: \"poddisruptionbudgets\"}] {\n\t\treturn false, nil\n\t}\n\tgo disruption.NewDisruptionController(\n\t\tctx.NewInformerFactory.Core().V1().Pods(),\n\t\tctx.NewInformerFactory.Policy().V1beta1().PodDisruptionBudgets(),\n\t\tctx.NewInformerFactory.Core().V1().ReplicationControllers(),\n\t\tctx.NewInformerFactory.Extensions().V1beta1().ReplicaSets(),\n\t\tctx.NewInformerFactory.Extensions().V1beta1().Deployments(),\n\t\tctx.NewInformerFactory.Apps().V1beta1().StatefulSets(),\n\t\tctx.ClientBuilder.ClientOrDie(\"disruption-controller\"),\n\t).Run(ctx.Stop)\n\treturn true, nil\n}"} {"input": "package main\n\nimport (\n\t\"image\"\n\t\"net/url\"\n\n\t\"github.com/ChimeraCoder/anaconda\"\n\tartsparts \"github.com/OpenGLAMTools/ArtsParts\"\n)\n\nfunc initTwitter(conf Conf) {\n\tanaconda.SetConsumerKey(conf.Env[\"TWITTER_KEY\"])\n\tanaconda.SetConsumerSecret(conf.Env[\"TWITTER_SECRET\"])\n}\n\ntype tweetResponse struct {\n\ttwitterID int64\n\ttwitterIDString string\n\tmediaID int64\n\tmediaIDString string\n}\n\n\n\nfunc tweetImage(text string, img image.Image, twitterAPI *anaconda.TwitterApi) (tweetResponse, error) {\n\tvar resp tweetResponse\n\timgString, err := artsparts.ImageToBaseString(img)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\tm, err := twitterAPI.UploadMedia(imgString)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\tresp.mediaID = m.MediaID\n\tresp.mediaIDString = m.MediaIDString\n\tv := url.Values{\n\t\t\"media_ids\": []string{m.MediaIDString},\n\t}\n\ttweet, err := twitterAPI.PostTweet(text, v)\n\tlog.Infof(\"TweetImage: %#v\\n\", tweet)\n\tresp.twitterID = tweet.Id\n\tresp.twitterIDString = tweet.IdStr\n\treturn resp, err\n\n}\n\nfunc postPartTweet(ap *artsparts.Part, img image.Image, twitterAPI *anaconda.TwitterApi) error ", "output": "{\n\tlog.Infoln(\"-----postPartTweet----\")\n\tresp, err := tweetImage(ap.Text, img, twitterAPI)\n\tap.TweetID = resp.twitterID\n\tap.TweetIDString = resp.twitterIDString\n\tap.MediaID = resp.mediaID\n\tap.MediaIDString = resp.mediaIDString\n\treturn err\n}"} {"input": "package main\n\nimport (\n\t\"github.com/mkrautz/objc\"\n\t. \"github.com/mkrautz/objc/AppKit\"\n\t\"log\"\n\t\"runtime\"\n)\n\n\n\ntype AppDelegate struct {\n\tobjc.Object `objc:\"GOAppDelegate : NSObject\"`\n\tWindow objc.Object `objc:\"IBOutlet\"`\n}\n\nfunc (delegate *AppDelegate) ApplicationDidFinishLaunching(notification objc.Object) {\n\tlog.Printf(\"applicationDidFinishLaunching! %v\", notification)\n\n\tlog.Printf(\"Object: %v\", delegate.Object)\n\tlog.Printf(\"Window: %v\", delegate.Window)\n\n\tmainMenu := NSSharedApplication().MainMenu()\n\tlog.Printf(\"%v\", mainMenu)\n}\n\nfunc main() {\n\tNSApplicationMain()\n}\n\nfunc init() ", "output": "{\n\tdefer runtime.LockOSThread()\n\n\tc := objc.NewClass(AppDelegate{})\n\tc.AddMethod(\"applicationDidFinishLaunching:\", (*AppDelegate).ApplicationDidFinishLaunching)\n\tobjc.RegisterClass(c)\n}"} {"input": "package reaperlog\n\nimport (\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/rifflock/lfshook\"\n\t\"go.mozilla.org/mozlogrus\"\n)\n\nvar config LogConfig\n\ntype LogConfig struct {\n\tExtras bool\n}\n\nfunc EnableExtras() {\n\tconfig.Extras = true\n}\n\nfunc EnableMozlog() {\n\tmozlogrus.Enable(\"Reaper\")\n}\n\nfunc Extras() bool {\n\treturn config.Extras\n}\n\nfunc SetConfig(c *LogConfig) {\n\tconfig = *c\n}\n\nfunc AddLogFile(filename string) {\n\tlog.AddHook(lfshook.NewHook(lfshook.PathMap{\n\t\tlog.DebugLevel: filename,\n\t\tlog.InfoLevel: filename,\n\t\tlog.WarnLevel: filename,\n\t\tlog.ErrorLevel: filename,\n\t\tlog.FatalLevel: filename,\n\t\tlog.PanicLevel: filename,\n\t}))\n}\n\nfunc Debug(format string, args ...interface{}) {\n\tlog.Debugf(format, args...)\n}\n\n\n\nfunc Warning(format string, args ...interface{}) {\n\tlog.Warningf(format, args...)\n}\n\nfunc Fatal(format string, args ...interface{}) {\n\tlog.Fatalf(format, args...)\n}\n\nfunc Panic(format string, args ...interface{}) {\n\tlog.Panicf(format, args...)\n}\n\nfunc Error(format string, args ...interface{}) {\n\tlog.Errorf(format, args...)\n}\n\nfunc Info(format string, args ...interface{}) ", "output": "{\n\tlog.Infof(format, args...)\n}"} {"input": "package db\n\nimport (\n\t\"database/sql\"\n\t\"github.com/simplemvc/gocorelib/revel\"\n)\n\nvar (\n\tDb *sql.DB\n\tDriver string\n\tSpec string\n)\n\nfunc Init() {\n\tvar found bool\n\tif Driver, found = revel.Config.String(\"db.driver\"); !found {\n\t\trevel.ERROR.Fatal(\"No db.driver found.\")\n\t}\n\tif Spec, found = revel.Config.String(\"db.spec\"); !found {\n\t\trevel.ERROR.Fatal(\"No db.spec found.\")\n\t}\n\n\tvar err error\n\tDb, err = sql.Open(Driver, Spec)\n\tif err != nil {\n\t\trevel.ERROR.Fatal(err)\n\t}\n}\n\ntype Transactional struct {\n\t*revel.Controller\n\tTxn *sql.Tx\n}\n\n\nfunc (c *Transactional) Begin() revel.Result {\n\ttxn, err := Db.Begin()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tc.Txn = txn\n\treturn nil\n}\n\n\nfunc (c *Transactional) Rollback() revel.Result {\n\tif c.Txn != nil {\n\t\tif err := c.Txn.Rollback(); err != nil {\n\t\t\tif err != sql.ErrTxDone {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t\tc.Txn = nil\n\t}\n\treturn nil\n}\n\n\n\n\nfunc init() {\n\trevel.InterceptMethod((*Transactional).Begin, revel.BEFORE)\n\trevel.InterceptMethod((*Transactional).Commit, revel.AFTER)\n\trevel.InterceptMethod((*Transactional).Rollback, revel.FINALLY)\n}\n\nfunc (c *Transactional) Commit() revel.Result ", "output": "{\n\tif c.Txn != nil {\n\t\tif err := c.Txn.Commit(); err != nil {\n\t\t\tif err != sql.ErrTxDone {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t\tc.Txn = nil\n\t}\n\treturn nil\n}"} {"input": "package bc\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n)\n\ntype Bc interface {\n\tExec(string) error\n\tQuit()\n}\n\ntype bc struct {\n\tcmd *exec.Cmd\n\tstdin io.WriteCloser\n\tstdout io.ReadCloser\n}\n\nfunc Start() Bc {\n\tcmd := exec.Command(\"bc\")\n\tstdin, err := cmd.StdinPipe()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcmd.Stderr = os.Stderr\n\tcmd.Start()\n\treturn &bc{cmd, stdin, stdout}\n}\n\n\nvar inputSuffix = []byte(\"\\n\\\"\\x04\\\"\\n\")\n\nfunc (bc *bc) Exec(code string) error {\n\tbc.stdin.Write([]byte(code))\n\tbc.stdin.Write(inputSuffix)\n\tfor {\n\t\tb, err := readByte(bc.stdout)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif b == 0x04 {\n\t\t\tbreak\n\t\t}\n\t\tos.Stdout.Write([]byte{b})\n\t}\n\treturn nil\n}\n\n\n\nfunc (bc *bc) Quit() {\n\tbc.stdin.Close()\n\tbc.cmd.Wait()\n\tbc.stdout.Close()\n}\n\nfunc readByte(r io.Reader) (byte, error) ", "output": "{\n\tvar buf [1]byte\n\t_, err := r.Read(buf[:])\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn buf[0], nil\n}"} {"input": "package monator\n\nimport (\n \"time\"\n \"bytes\"\n \"encoding/json\"\n)\n\ntype CheckDuration time.Duration\n\nfunc (d CheckDuration) Hours() float64 {\n return time.Duration(d).Hours()\n}\n\nfunc (d CheckDuration) Minutes() float64 {\n return time.Duration(d).Minutes()\n}\n\nfunc (d CheckDuration) Nanoseconds() int64 {\n return time.Duration(d).Nanoseconds()\n}\n\n\n\nfunc (d CheckDuration) Milliseconds() int64 {\n return time.Duration(d).Nanoseconds() / int64(time.Millisecond)\n}\n\nfunc (d CheckDuration) String() string {\n \n rounded := ((time.Duration(d)).Nanoseconds() / int64(time.Millisecond)) * int64(time.Millisecond)\n return time.Duration(rounded).String()\n}\n\n\nfunc (d *CheckDuration) UnmarshalJSON(data []byte) error {\n b := bytes.NewBuffer(data)\n dec := json.NewDecoder(b)\n\n var s string\n\n if err := dec.Decode(&s); err != nil {\n return err\n }\n if duration, err := time.ParseDuration(s); err != nil {\n return err\n } else {\n *d = CheckDuration(duration)\n }\n\n return nil\n}\n\nfunc (d CheckDuration) Seconds() float64 ", "output": "{\n return time.Duration(d).Seconds()\n}"} {"input": "package bytealg\n\n\nfunc Count(b []byte, c byte) int\n\n\nfunc CountString(s string, c byte) int\n\n\n\nfunc countGenericString(s string, c byte) int {\n\tn := 0\n\tfor i := 0; i < len(s); i++ {\n\t\tif s[i] == c {\n\t\t\tn++\n\t\t}\n\t}\n\treturn n\n}\n\nfunc countGeneric(b []byte, c byte) int ", "output": "{\n\tn := 0\n\tfor _, x := range b {\n\t\tif x == c {\n\t\t\tn++\n\t\t}\n\t}\n\treturn n\n}"} {"input": "package seccomp\n\nimport (\n\tseccomp_compiler \"github.com/snapcore/snapd/sandbox/seccomp\"\n)\n\n\n\n\n\nfunc MockTemplate(fakeTemplate []byte) (restore func()) {\n\torig := defaultTemplate\n\torigBarePrivDropSyscalls := barePrivDropSyscalls\n\tdefaultTemplate = fakeTemplate\n\tbarePrivDropSyscalls = \"\"\n\treturn func() {\n\t\tdefaultTemplate = orig\n\t\tbarePrivDropSyscalls = origBarePrivDropSyscalls\n\t}\n}\n\nfunc MockKernelFeatures(f func() []string) (resture func()) {\n\told := kernelFeatures\n\tkernelFeatures = f\n\treturn func() {\n\t\tkernelFeatures = old\n\t}\n}\n\nfunc MockRequiresSocketcall(f func(string) bool) (restore func()) {\n\told := requiresSocketcall\n\trequiresSocketcall = f\n\treturn func() {\n\t\trequiresSocketcall = old\n\t}\n}\n\nfunc MockDpkgKernelArchitecture(f func() string) (restore func()) {\n\told := dpkgKernelArchitecture\n\tdpkgKernelArchitecture = f\n\treturn func() {\n\t\tdpkgKernelArchitecture = old\n\t}\n}\n\nfunc MockReleaseInfoId(s string) (restore func()) {\n\told := releaseInfoId\n\treleaseInfoId = s\n\treturn func() {\n\t\treleaseInfoId = old\n\t}\n}\n\nfunc MockReleaseInfoVersionId(s string) (restore func()) {\n\told := releaseInfoVersionId\n\treleaseInfoVersionId = s\n\treturn func() {\n\t\treleaseInfoVersionId = old\n\t}\n}\n\n\n\nfunc (b *Backend) VersionInfo() seccomp_compiler.VersionInfo {\n\treturn b.versionInfo\n}\n\nvar (\n\tRequiresSocketcall = requiresSocketcall\n\n\tGlobalProfileLE = globalProfileLE\n\tGlobalProfileBE = globalProfileBE\n\tIsBigEndian = isBigEndian\n)\n\nfunc MockSeccompCompilerLookup(f func(string) (string, error)) (restore func()) ", "output": "{\n\told := seccompCompilerLookup\n\tseccompCompilerLookup = f\n\treturn func() {\n\t\tseccompCompilerLookup = old\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/robfig/cron\"\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n)\n\nvar (\n\tpid = 0\n\n\thttpPorts = getEnv(\"HTTP_PORTS\", \"80 8080\")\n\ttlsPorts = getEnv(\"TLS_PORTS\", \"443 8443\")\n\n\tswarmRouterPort = getEnv(\"SWARM_ROUTER_PORT\", \"35353\")\n\n\tdefaultBackendPorts = getEnv(\"DEFAULT_BACKEND_PORTS\", \"80 443 8000 8080 8443 9000\")\n\n\toverrideBackendPorts = getEnv(\"OVERRIDE_BACKEND_PORTS\", \"\")\n\n\tbackendsVerifyTLS = getEnv(\"BACKENDS_VERIFY_TLS\", \"\")\n)\n\nfunc getEnv(key, defaultValue string) string {\n\tvalue, exists := os.LookupEnv(key)\n\tif !exists {\n\t\tvalue = defaultValue\n\t\tos.Setenv(key, defaultValue)\n\t}\n\treturn strings.TrimSpace(value)\n}\n\n\n\nfunc init() {\n\texecuteTemplate(\"/usr/local/etc/haproxy/haproxy.tmpl\", \"/usr/local/etc/haproxy/haproxy.cfg\")\n}\n\nfunc main() {\n\tc := cron.New()\n\tc.AddFunc(\"@daily\", reload)\n\tc.Start()\n\texit := make(chan bool, 1)\n\tgo router(exit, swarmRouterPort)\n\tgo haproxy(exit)\n\t<-exit\n}\n\nfunc haproxy(exit chan bool) ", "output": "{\n\tcmd := exec.Command(os.Args[1], os.Args[2:]...)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Start(); err != nil {\n\t\tlog.Fatalf(\"Start error: %s\", err.Error())\n\t}\n\tpid = cmd.Process.Pid\n\tlog.Printf(\"Started haproxy master process with pid: %d\", pid)\n\terr := cmd.Wait()\n\tlog.Printf(\"Exit error: %s\", err.Error())\n\texit <- true\n}"} {"input": "package repositories\n\n\n\n\nimport (\n\t\"net/http\"\n\n\tmiddleware \"github.com/go-openapi/runtime/middleware\"\n)\n\n\ntype GetOwnerRepositoriesHandlerFunc func(GetOwnerRepositoriesParams) middleware.Responder\n\n\n\n\n\ntype GetOwnerRepositoriesHandler interface {\n\tHandle(GetOwnerRepositoriesParams) middleware.Responder\n}\n\n\nfunc NewGetOwnerRepositories(ctx *middleware.Context, handler GetOwnerRepositoriesHandler) *GetOwnerRepositories {\n\treturn &GetOwnerRepositories{Context: ctx, Handler: handler}\n}\n\n\ntype GetOwnerRepositories struct {\n\tContext *middleware.Context\n\tHandler GetOwnerRepositoriesHandler\n}\n\nfunc (o *GetOwnerRepositories) ServeHTTP(rw http.ResponseWriter, r *http.Request) {\n\troute, rCtx, _ := o.Context.RouteInfo(r)\n\tif rCtx != nil {\n\t\tr = rCtx\n\t}\n\tvar Params = NewGetOwnerRepositoriesParams()\n\n\tif err := o.Context.BindValidRequest(r, route, &Params); err != nil { \n\t\to.Context.Respond(rw, r, route.Produces, route, err)\n\t\treturn\n\t}\n\n\tres := o.Handler.Handle(Params) \n\n\to.Context.Respond(rw, r, route.Produces, route, res)\n\n}\n\nfunc (fn GetOwnerRepositoriesHandlerFunc) Handle(params GetOwnerRepositoriesParams) middleware.Responder ", "output": "{\n\treturn fn(params)\n}"} {"input": "package model\n\nimport (\n\t\"go-common/app/service/main/archive/model/archive\"\n)\n\n\ntype ArcToView struct {\n\t*archive.Archive3\n\tPage *archive.Page3 `json:\"page,omitempty\"`\n\tCount int `json:\"count\"`\n\tCid int64 `json:\"cid\"`\n\tProgress int64 `json:\"progress\"`\n\tAddTime int64 `json:\"add_at\"`\n}\n\n\ntype WebArcToView struct {\n\t*archive.View3\n\tBangumiInfo *Bangumi `json:\"bangumi,omitempty\"`\n\tCid int64 `json:\"cid\"`\n\tProgress int64 `json:\"progress\"`\n\tAddTime int64 `json:\"add_at\"`\n}\n\n\ntype ToView struct {\n\tAid int64 `json:\"aid,omitempty\"`\n\tUnix int64 `json:\"now,omitempty\"`\n}\n\n\ntype ToViews []*ToView\n\nfunc (h ToViews) Len() int { return len(h) }\n\nfunc (h ToViews) Swap(i, j int) { h[i], h[j] = h[j], h[i] }\n\nfunc (h ToViews) Less(i, j int) bool ", "output": "{ return h[i].Unix > h[j].Unix }"} {"input": "package api\n\nimport (\n\t\"errors\"\n\t\"net\"\n\t\"net/http\"\n\n\t\"github.com/coreos/fleet/log\"\n)\n\nvar unavailable = &unavailableHdlr{}\n\n\n\ntype Server struct {\n\tlisteners []net.Listener\n\tapi http.Handler\n\tcur http.Handler\n}\n\nfunc (s *Server) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\ts.cur.ServeHTTP(rw, req)\n}\n\nfunc (s *Server) Serve() {\n\tfor i, _ := range s.listeners {\n\t\tl := s.listeners[i]\n\t\tgo func() {\n\t\t\terr := http.Serve(l, s)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Failed serving HTTP on listener: %s\", l.Addr)\n\t\t\t}\n\t\t}()\n\t}\n}\n\n\n\n\nfunc (s *Server) Available(stop chan bool) {\n\ts.cur = s.api\n\t<-stop\n\ts.cur = unavailable\n}\n\ntype unavailableHdlr struct{}\n\nfunc (uh *unavailableHdlr) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\tsendError(rw, http.StatusServiceUnavailable, errors.New(\"fleet server currently unavailable\"))\n}\n\nfunc NewServer(listeners []net.Listener, hdlr http.Handler) *Server ", "output": "{\n\treturn &Server{\n\t\tlisteners: listeners,\n\t\tapi: hdlr,\n\t\tcur: unavailable,\n\t}\n}"} {"input": "package implementation\n\nimport (\n\t\"crypto/tls\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/go-openapi/swag\"\n\t\"github.com/go-swagger/go-swagger/examples/auto-configure/restapi/operations\"\n)\n\ntype ConfigureImpl struct {\n\tflags Flags\n}\n\ntype Flags struct {\n\tExample1 string `long:\"example1\" description:\"Sample for showing how to configure cmd-line flags\"`\n\tExample2 string `long:\"example2\" description:\"Further info at https://github.com/jessevdk/go-flags\"`\n}\n\nfunc (i *ConfigureImpl) ConfigureFlags(api *operations.AToDoListApplicationAPI) {\n\tapi.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{\n\t\t{\n\t\t\tShortDescription: \"Example Flags\",\n\t\t\tLongDescription: \"\",\n\t\t\tOptions: &i.flags,\n\t\t},\n\t}\n}\n\nfunc (i *ConfigureImpl) ConfigureTLS(tlsConfig *tls.Config) {\n}\n\nfunc (i *ConfigureImpl) ConfigureServer(s *http.Server, scheme, addr string) {\n\tif i.flags.Example1 != \"something\" {\n\t\tlog.Println(\"example1 argument is not something\")\n\t}\n}\n\n\n\nfunc (i *ConfigureImpl) SetupGlobalMiddleware(handler http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tlog.Printf(\"Recieved request on path: %v\", req.URL.String())\n\t\thandler.ServeHTTP(w, req)\n\t})\n}\n\nfunc (i *ConfigureImpl) CustomConfigure(api *operations.AToDoListApplicationAPI) {\n\tapi.Logger = log.Printf\n\tapi.ServerShutdown = func() {\n\t\tlog.Printf(\"Running ServerShutdown function\")\n\t}\n}\n\nfunc (i *ConfigureImpl) SetupMiddlewares(handler http.Handler) http.Handler ", "output": "{\n\treturn handler\n}"} {"input": "package v1\n\nimport context \"context\"\n\nimport proto \"github.com/golang/protobuf/proto\"\nimport \"go-common/library/net/rpc/liverpc\"\n\nvar _ proto.Message \n\n\n\n\n\n\ntype CaptchaRPCClient interface {\n\tCreate(ctx context.Context, req *CaptchaCreateReq, opts ...liverpc.CallOption) (resp *CaptchaCreateResp, err error)\n}\n\n\n\n\n\ntype captchaRPCClient struct {\n\tclient *liverpc.Client\n}\n\n\nfunc NewCaptchaRPCClient(client *liverpc.Client) CaptchaRPCClient {\n\treturn &captchaRPCClient{\n\t\tclient: client,\n\t}\n}\n\n\n\n\n\n\n\nfunc doRPCRequest(ctx context.Context, client *liverpc.Client, version int, method string, in, out proto.Message, opts []liverpc.CallOption) (err error) {\n\terr = client.Call(ctx, version, method, in, out, opts...)\n\treturn\n}\n\nfunc (c *captchaRPCClient) Create(ctx context.Context, in *CaptchaCreateReq, opts ...liverpc.CallOption) (*CaptchaCreateResp, error) ", "output": "{\n\tout := new(CaptchaCreateResp)\n\terr := doRPCRequest(ctx, c.client, 1, \"Captcha.create\", in, out, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}"} {"input": "package metrics\n\nimport (\n\t\"expvar\"\n\t\"runtime\"\n\t\"sync\"\n)\n\nvar (\n\tm *expvar.Map\n\tonce sync.Once\n)\n\n\nfunc init() {\n\tonce.Do(func() {\n\t\tm = expvar.NewMap(\"errors\")\n\t\tm.Add(\"APIErrors\", 0)\n\t\tm.Add(\"RESTErrors\", 0)\n\t})\n\texpvar.Publish(\"goroutines\", expvar.Func(goroutines))\n}\n\n\n\n\n\nfunc RESTError() {\n\tm.Add(\"RESTErrors\", 1)\n}\n\nfunc goroutines() interface{} {\n\treturn runtime.NumGoroutine()\n}\n\nfunc APIError() ", "output": "{\n\tm.Add(\"APIErrors\", 1)\n}"} {"input": "package pgjson\n\nimport (\n\t\"io\"\n)\n\nvar provider Provider = StdProvider{}\n\nfunc SetProvider(p Provider) {\n\tprovider = p\n}\n\ntype Provider interface {\n\tMarshal(v interface{}) ([]byte, error)\n\tUnmarshal(data []byte, v interface{}) error\n\tNewEncoder(w io.Writer) Encoder\n\tNewDecoder(r io.Reader) Decoder\n}\n\ntype Decoder interface {\n\tDecode(v interface{}) error\n\tUseNumber()\n}\n\ntype Encoder interface {\n\tEncode(v interface{}) error\n}\n\nfunc Marshal(v interface{}) ([]byte, error) {\n\treturn provider.Marshal(v)\n}\n\nfunc Unmarshal(data []byte, v interface{}) error {\n\treturn provider.Unmarshal(data, v)\n}\n\nfunc NewEncoder(w io.Writer) Encoder {\n\treturn provider.NewEncoder(w)\n}\n\n\n\nfunc NewDecoder(r io.Reader) Decoder ", "output": "{\n\treturn provider.NewDecoder(r)\n}"} {"input": "package eulerlibs\n\nimport \"testing\"\n\n\n\nfunc BenchmarkPrimeFactor(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tMaxPrimeFactor(600851475143)\n\t}\n}\n\nfunc TestMaxPrimeFactor(t *testing.T) ", "output": "{\n\texpected := 5\n\tactual := MaxPrimeFactor(10)\n\tif expected != actual {\n\t\tt.Errorf(\"(p3) expected:%d - actual:%d\", expected, actual)\n\t}\n}"} {"input": "package aesample\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/mzimmerman/aesample/subpkga\"\n\t\"github.com/mzimmerman/aesample/util\"\n)\n\nfunc init() {\n\thttp.HandleFunc(\"/\", root)\n\thttp.HandleFunc(\"/subpkga\", subpkga.Root)\n\tutil.Log(\"aesample init()\")\n}\n\n\n\nfunc root(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tfmt.Fprint(w, \"Hello, you've reached aesample, the root package does nothing\")\n}"} {"input": "package topovalidator\n\nimport (\n\t\"fmt\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"vitess.io/vitess/go/vt/topo\"\n\n\ttopodatapb \"vitess.io/vitess/go/vt/proto/topodata\"\n)\n\n\n\n\n\n\n\nfunc RegisterKeyspaceValidator() {\n\tRegisterValidator(\"Keyspace Validator\", &KeyspaceValidator{})\n}\n\n\ntype KeyspaceValidator struct{}\n\n\nfunc (kv *KeyspaceValidator) Audit(ctx context.Context, ts *topo.Server, w *Workflow) error {\n\tkeyspaces, err := ts.GetKeyspaces(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, keyspace := range keyspaces {\n\t\t_, err := ts.GetKeyspace(ctx, keyspace)\n\t\tif err != nil {\n\t\t\tw.AddFixer(keyspace, fmt.Sprintf(\"Error: %v\", err), &KeyspaceFixer{\n\t\t\t\tts: ts,\n\t\t\t\tkeyspace: keyspace,\n\t\t\t}, []string{\"Create\", \"Delete\"})\n\t\t}\n\t}\n\treturn nil\n}\n\n\ntype KeyspaceFixer struct {\n\tts *topo.Server\n\tkeyspace string\n}\n\n\n\n\nfunc (kf *KeyspaceFixer) Action(ctx context.Context, name string) error ", "output": "{\n\tif name == \"Create\" {\n\t\treturn kf.ts.CreateKeyspace(ctx, kf.keyspace, &topodatapb.Keyspace{})\n\t}\n\tif name == \"Delete\" {\n\t\treturn kf.ts.DeleteKeyspace(ctx, kf.keyspace)\n\t}\n\treturn fmt.Errorf(\"unknown KeyspaceFixer action: %v\", name)\n}"} {"input": "package lineargo\n\n\nimport \"C\"\nimport \"unsafe\"\n\nfunc mapCDouble(in []float64) []C.double {\n\tout := make([]C.double, len(in), len(in))\n\tfor i, val := range in {\n\t\tout[i] = C.double(val)\n\t}\n\treturn out\n}\n\nfunc mapCInt(in []int) []C.int {\n\tout := make([]C.int, len(in), len(in))\n\tfor i, val := range in {\n\t\tout[i] = C.int(val)\n\t}\n\treturn out\n}\n\n\n\n\nfunc doubleToFloats(in *C.double, size int) []float64 ", "output": "{\n\tdefer C.free(unsafe.Pointer(in))\n\toutD := (*[1 << 30]C.double)(unsafe.Pointer(in))[:size:size]\n\tout := make([]float64, size, size)\n\tfor i := 0; i < size; i++ {\n\t\tout[i] = float64(outD[i])\n\t}\n\n\treturn out\n}"} {"input": "package mocks\n\nimport (\n\tcli \"github.com/stackanetes/kubernetes-entrypoint/client\"\n\tv1batch \"k8s.io/client-go/1.5/kubernetes/typed/batch/v1\"\n\tv1core \"k8s.io/client-go/1.5/kubernetes/typed/core/v1\"\n\tv1beta1extensions \"k8s.io/client-go/1.5/kubernetes/typed/extensions/v1beta1\"\n)\n\ntype Client struct {\n\tv1core.PodInterface\n\tv1core.ServiceInterface\n\tv1beta1extensions.DaemonSetInterface\n\tv1core.EndpointsInterface\n\tv1batch.JobInterface\n}\n\nfunc (c Client) Pods(namespace string) v1core.PodInterface {\n\treturn c.PodInterface\n}\n\nfunc (c Client) Services(namespace string) v1core.ServiceInterface {\n\treturn c.ServiceInterface\n}\n\n\n\nfunc (c Client) Endpoints(namespace string) v1core.EndpointsInterface {\n\treturn c.EndpointsInterface\n}\nfunc (c Client) Jobs(namespace string) v1batch.JobInterface {\n\treturn c.JobInterface\n}\n\nfunc NewClient() cli.ClientInterface {\n\treturn Client{\n\t\tNewPClient(),\n\t\tNewSClient(),\n\t\tNewDSClient(),\n\t\tNewEClient(),\n\t\tNewJClient(),\n\t}\n}\n\nfunc (c Client) DaemonSets(namespace string) v1beta1extensions.DaemonSetInterface ", "output": "{\n\treturn c.DaemonSetInterface\n}"} {"input": "package api\n\nimport (\n\t\"bytes\"\n\t\"encoding/base64\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/url\"\n)\n\ntype PageToken struct {\n\tLimit uint16\n\tPage uint16\n}\n\nfunc DefaultPageToken(limit uint16) PageToken {\n\treturn PageToken{Limit: limit, Page: 1}\n}\n\nfunc (tok PageToken) Next() PageToken {\n\treturn PageToken{Limit: tok.Limit, Page: tok.Page + 1}\n}\n\n\n\nfunc decodePageToken(value string) (*PageToken, error) {\n\tdec, err := base64.URLEncoding.DecodeString(value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdb := bytes.NewBuffer(dec)\n\n\tvar tok PageToken\n\terr = binary.Read(db, binary.LittleEndian, &tok)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &tok, nil\n}\n\nfunc findNextPageToken(u *url.URL, limit uint16) (*PageToken, error) {\n\tvalues := u.Query()[\"nextPageToken\"]\n\n\tif len(values) > 1 {\n\t\treturn nil, errors.New(\"too many values for page token\")\n\t}\n\n\tif len(values) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tval := values[0]\n\ttok, err := decodePageToken(val)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = validatePageToken(tok, limit)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn tok, nil\n}\n\nfunc validatePageToken(tok *PageToken, limit uint16) error {\n\tif tok.Limit != limit {\n\t\treturn fmt.Errorf(\"token limit must be %d\", limit)\n\t}\n\n\tif tok.Page == 0 {\n\t\treturn errors.New(\"token page must be greater than zero\")\n\t}\n\n\treturn nil\n}\n\nfunc (tok PageToken) Encode() string ", "output": "{\n\tbuf := bytes.Buffer{}\n\tbinary.Write(&buf, binary.LittleEndian, tok)\n\treturn base64.URLEncoding.EncodeToString(buf.Bytes())\n}"} {"input": "package ui\n\nimport (\n\t\"io\"\n\n\t\"github.com/cheggaaa/pb\"\n)\n\ntype FileReporter struct {\n\tui UI\n}\n\nfunc NewFileReporter(ui UI) FileReporter {\n\treturn FileReporter{ui: ui}\n}\n\ntype ReadSeekCloser interface {\n\tio.Seeker\n\tio.ReadCloser\n}\n\nfunc (r FileReporter) Write(b []byte) (int, error) {\n\tr.ui.BeginLinef(\"%s\", b)\n\treturn len(b), nil\n}\n\nfunc (r FileReporter) TrackUpload(size int64, reader io.ReadCloser) ReadSeekCloser {\n\treturn &ReadCloserProxy{reader: reader, bar: r.buildBar(size), ui: r.ui}\n}\n\nfunc (r FileReporter) TrackDownload(size int64, writer io.Writer) io.Writer {\n\treturn io.MultiWriter(writer, r.buildBar(size))\n}\n\n\n\ntype ReadCloserProxy struct {\n\treader io.ReadCloser\n\tbar *pb.ProgressBar\n\tui UI\n}\n\nfunc (p ReadCloserProxy) Seek(offset int64, whence int) (int64, error) {\n\tseeker, ok := p.reader.(io.Seeker)\n\tif ok {\n\t\treturn seeker.Seek(offset, whence)\n\t}\n\n\treturn 0, nil\n}\n\nfunc (p *ReadCloserProxy) Read(bs []byte) (int, error) {\n\tn, err := p.reader.Read(bs)\n\tp.bar.Add(n)\n\treturn n, err\n}\n\nfunc (p *ReadCloserProxy) Close() error {\n\terr := p.reader.Close()\n\tp.bar.Finish()\n\tp.ui.BeginLinef(\"\\n\")\n\treturn err\n}\n\nfunc (r FileReporter) buildBar(size int64) *pb.ProgressBar ", "output": "{\n\tbar := pb.New(int(size))\n\tbar.Output = r\n\tbar.NotPrint = true\n\tbar.ShowCounters = false\n\tbar.ShowTimeLeft = true\n\tbar.ShowSpeed = true\n\tbar.SetWidth(80)\n\tbar.SetMaxWidth(80)\n\tbar.SetUnits(pb.U_BYTES)\n\tbar.Format(\"\\x00#\\x00#\\x00 \\x00\")\n\tbar.Start()\n\treturn bar\n}"} {"input": "package etcd\n\nimport (\n\t\"testing\"\n\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/registry/generic\"\n\t\"k8s.io/kubernetes/pkg/registry/registrytest\"\n\t\"k8s.io/kubernetes/pkg/runtime\"\n\tetcdtesting \"k8s.io/kubernetes/pkg/storage/etcd/testing\"\n)\n\nvar testTTL uint64 = 60\n\nfunc newStorage(t *testing.T) (*REST, *etcdtesting.EtcdTestServer) {\n\tetcdStorage, server := registrytest.NewEtcdStorage(t, \"\")\n\treturn NewREST(etcdStorage, generic.UndecoratedStorage, testTTL), server\n}\n\nfunc validNewEvent(namespace string) *api.Event {\n\treturn &api.Event{\n\t\tObjectMeta: api.ObjectMeta{\n\t\t\tName: \"foo\",\n\t\t\tNamespace: namespace,\n\t\t},\n\t\tReason: \"forTesting\",\n\t\tInvolvedObject: api.ObjectReference{\n\t\t\tKind: \"Pod\",\n\t\t\tName: \"bar\",\n\t\t\tNamespace: namespace,\n\t\t},\n\t}\n}\n\nfunc TestCreate(t *testing.T) {\n\tstorage, server := newStorage(t)\n\tdefer server.Terminate(t)\n\ttest := registrytest.New(t, storage.Etcd)\n\tevent := validNewEvent(test.TestNamespace())\n\tevent.ObjectMeta = api.ObjectMeta{}\n\ttest.TestCreate(\n\t\tevent,\n\t\t&api.Event{},\n\t)\n}\n\n\n\nfunc TestDelete(t *testing.T) {\n\tstorage, server := newStorage(t)\n\tdefer server.Terminate(t)\n\ttest := registrytest.New(t, storage.Etcd)\n\ttest.TestDelete(validNewEvent(test.TestNamespace()))\n}\n\nfunc TestUpdate(t *testing.T) ", "output": "{\n\tstorage, server := newStorage(t)\n\tdefer server.Terminate(t)\n\ttest := registrytest.New(t, storage.Etcd).AllowCreateOnUpdate()\n\ttest.TestUpdate(\n\t\tvalidNewEvent(test.TestNamespace()),\n\t\tfunc(obj runtime.Object) runtime.Object {\n\t\t\tobject := obj.(*api.Event)\n\t\t\tobject.Reason = \"forDifferentTesting\"\n\t\t\treturn object\n\t\t},\n\t\tfunc(obj runtime.Object) runtime.Object {\n\t\t\tobject := obj.(*api.Event)\n\t\t\tobject.InvolvedObject.Namespace = \"different-namespace\"\n\t\t\treturn object\n\t\t},\n\t)\n}"} {"input": "package uchiwa\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestMergeStringSlice(t *testing.T) {\n\tvar a1, a2 []string\n\n\tslice := MergeStringSlices(a1, a2)\n\tassert.Equal(t, []string(nil), slice, \"if both slices are empty, it should return an empty slice\")\n\n\ta1 = []string{\"1\", \"2\"}\n\tslice = MergeStringSlices(a1, a2)\n\tassert.Equal(t, a1, slice, \"if one slice is empty, it should return the other slice\")\n\n\ta2 = []string{\"2\"}\n\tslice = MergeStringSlices(a1, a2)\n\tassert.Equal(t, a1, slice, \"if one slice is empty, it should return the other slice\")\n\n\ta2 = []string{\"2\", \"3\"}\n\tslice = MergeStringSlices(a1, a2)\n\tassert.Equal(t, []string{\"1\", \"2\", \"3\"}, slice, \"if one slice is empty, it should return the other slice\")\n\n}\n\nfunc TestSliceIntersection(t *testing.T) ", "output": "{\n\tvar a1, a2 []string\n\n\tfound := SliceIntersection(a1, a2)\n\tassert.Equal(t, false, found, \"if both slices are empty, it should return false\")\n\n\ta1 = []string{\"foo\", \"bar\"}\n\tfound = SliceIntersection(a1, a2)\n\tassert.Equal(t, false, found, \"if one slice is empty, it should return false\")\n\n\ta2 = []string{\"baz\", \"qux\"}\n\tfound = SliceIntersection(a1, a2)\n\tassert.Equal(t, false, found, \"it should return false is none of the elements in the slices are shared\")\n\n\ta2 = append(a2, \"foo\")\n\tfound = SliceIntersection(a1, a2)\n\tassert.Equal(t, true, found, \"it should return true if at least one element is shared between the slices\")\n}"} {"input": "package metrics\n\nimport (\n\t\"database/sql\"\n\t\"errors\"\n\t\"sync\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n)\n\nvar (\n\tbufferMetrics = map[string]metric{\n\t\t\"buffers_checkpoint\": metric{Name: \"checkpoint_total\", Help: \"Number of buffers written during checkpoints\"},\n\t\t\"buffers_clean\": metric{Name: \"clean_total\", Help: \"Number of buffers written by the background writer\"},\n\t\t\"maxwritten_clean\": metric{Name: \"maxwritten_clean_total\", Help: \"Number of times the background writer stopped a cleaning scan because it had written too many buffers\"},\n\t\t\"buffers_backend\": metric{Name: \"backend_total\", Help: \"Number of buffers written directly by a backend\"},\n\t\t\"buffers_backend_fsync\": metric{Name: \"backend_fsync_total\", Help: \"Number of times a backend had to execute its own fsync call (normally the background writer handles those even when the backend does its own write)\"},\n\t\t\"buffers_alloc\": metric{Name: \"alloc_total\", Help: \"Number of buffers allocated\"},\n\t}\n)\n\ntype BufferMetrics struct {\n\tmutex sync.Mutex\n\tmetrics map[string]prometheus.Gauge\n}\n\nfunc NewBufferMetrics() *BufferMetrics {\n\treturn &BufferMetrics{\n\t\tmetrics: map[string]prometheus.Gauge{},\n\t}\n}\n\n\n\nfunc (b *BufferMetrics) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, m := range b.metrics {\n\t\tm.Describe(ch)\n\t}\n}\n\nfunc (b *BufferMetrics) Collect(ch chan<- prometheus.Metric) {\n\tfor _, m := range b.metrics {\n\t\tm.Collect(ch)\n\t}\n}\n\n\nvar _ Collection = new(BufferMetrics)\n\nfunc (b *BufferMetrics) Scrape(db *sql.DB) error ", "output": "{\n\tb.mutex.Lock()\n\tdefer b.mutex.Unlock()\n\n\tresult, err := getMetrics(db, bufferMetrics, \"pg_stat_bgwriter\", nil)\n\tif err != nil {\n\t\treturn errors.New(\"error running table stats query on database: \" + err.Error())\n\t}\n\n\tfor key, val := range result {\n\t\tif _, ok := b.metrics[key]; !ok {\n\t\t\tb.metrics[key] = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tSubsystem: \"buffers\",\n\t\t\t\tName: bufferMetrics[key].Name,\n\t\t\t\tHelp: bufferMetrics[key].Help,\n\t\t\t})\n\t\t}\n\n\t\tb.metrics[key].Set(val)\n\t}\n\n\treturn nil\n}"} {"input": "package cli\n\nimport (\n\t\"strings\"\n)\n\ntype MultiError struct {\n\tErrors []error\n}\n\n\n\nfunc (m MultiError) Error() string {\n\terrs := make([]string, len(m.Errors))\n\tfor i, err := range m.Errors {\n\t\terrs[i] = err.Error()\n\t}\n\n\treturn strings.Join(errs, \"\\n\")\n}\n\nfunc NewMultiError(err ...error) MultiError ", "output": "{\n\treturn MultiError{Errors: err}\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tx, y := 10, 4\n\tfmt.Println(\"Original x, y: \", x, y)\n\n\tswap(&x, &y)\n\tfmt.Println(\"After swap x, y: \", x, y)\n}\n\n\n\nfunc swap(x, y *int) ", "output": "{\n\ttemp := *x\n\t*x = *y\n\t*y = temp\n}"} {"input": "package helpers\n\nimport (\n\t\"os\"\n\t\"strconv\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\n\n\nfunc SkipIfClientCredentialsNotSet() (string, string) {\n\tprivateClientID := os.Getenv(\"CF_INT_CLIENT_ID\")\n\tprivateClientSecret := os.Getenv(\"CF_INT_CLIENT_SECRET\")\n\n\tif privateClientID == \"\" || privateClientSecret == \"\" {\n\t\tSkip(\"CF_INT_CLIENT_ID or CF_INT_CLIENT_SECRET is not set\")\n\t}\n\n\treturn privateClientID, privateClientSecret\n}\n\n\n\n\n\nfunc SkipIfClientCredentialsTestMode() {\n\tif ClientCredentialsTestMode() {\n\t\tSkip(\"CF_INT_CLIENT_CREDENTIALS_TEST_MODE is enabled\")\n\t}\n}\n\nfunc ClientCredentialsTestMode() bool {\n\tenvVar := os.Getenv(\"CF_INT_CLIENT_CREDENTIALS_TEST_MODE\")\n\n\tif envVar == \"\" {\n\t\treturn false\n\t}\n\n\ttestMode, err := strconv.ParseBool(envVar)\n\tExpect(err).ToNot(HaveOccurred(), \"CF_INT_CLIENT_CREDENTIALS_TEST_MODE should be boolean\")\n\n\treturn testMode\n}\n\nfunc SkipIfCustomClientCredentialsNotSet() (string, string) ", "output": "{\n\tcustomClientID := os.Getenv(\"CF_INT_CUSTOM_CLIENT_ID\")\n\tcustomClientSecret := os.Getenv(\"CF_INT_CUSTOM_CLIENT_SECRET\")\n\n\tif customClientID == \"\" || customClientSecret == \"\" {\n\t\tSkip(\"CF_INT_CUSTOM_CLIENT_ID or CF_INT_CUSTOM_CLIENT_SECRET is not set\")\n\t}\n\n\treturn customClientID, customClientSecret\n}"} {"input": "package keymanagement\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ImportKeyVersionRequest struct {\n\n\tKeyId *string `mandatory:\"true\" contributesTo:\"path\" name:\"keyId\"`\n\n\tImportKeyVersionDetails `contributesTo:\"body\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\n\n\n\nfunc (request ImportKeyVersionRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request ImportKeyVersionRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ImportKeyVersionRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ImportKeyVersionResponse struct {\n\n\tRawResponse *http.Response\n\n\tKeyVersion `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ImportKeyVersionResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ImportKeyVersionResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ImportKeyVersionRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package main\n\nimport (\n\t\"github.com/go-martini/martini\"\n\t\"github.com/martini-contrib/render\"\n)\n\nfunc main() {\n\n\tm := martini.Classic()\n\n\tStaticOptions := martini.StaticOptions{Prefix: \"public\"}\n\tm.Use(martini.Static(\"public\", StaticOptions))\n\tm.Use(martini.Static(\"public\", StaticOptions))\n\tm.Use(martini.Static(\"public\", StaticOptions))\n\tm.Use(martini.Static(\"public\", StaticOptions))\n\n\tm.Use(render.Renderer(render.Options{\n\t\tDirectory: \"templates\", \n\t\tLayout: \"layout\", \n\t\tExtensions: []string{\".tmpl\"}, \n\t\tCharset: \"UTF-8\", \n\t}))\n\n\tm.Get(\"/\", IndexRouter)\n\tm.Get(\"/about\", AboutRoute)\n\tm.Get(\"/contact\", ContactRoute)\n\tm.Get(\"/signin\", SigninRoute)\n\tm.Get(\"/signup\", SignupRoute)\n\n\tm.Run()\n}\n\nfunc IndexRouter(r render.Render) {\n\tr.HTML(200, \"home/index\", nil)\n}\n\nfunc AboutRoute(r render.Render) {\n\tr.HTML(200, \"home/about\", nil)\n}\n\nfunc ContactRoute(r render.Render) {\n\tr.HTML(200, \"home/contact\", nil)\n}\n\n\n\nfunc SignupRoute(r render.Render) {\n\tr.HTML(200, \"account/signup\", nil)\n}\n\nfunc SigninRoute(r render.Render) ", "output": "{\n\tr.HTML(200, \"account/signin\", nil)\n}"} {"input": "package git\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/Originate/git-town/src/command\"\n\t\"github.com/Originate/git-town/src/util\"\n)\n\n\n\nfunc EnsureDoesNotHaveConflicts() {\n\tutil.Ensure(!HasConflicts(), \"You must resolve the conflicts before continuing\")\n}\n\n\n\nfunc EnsureDoesNotHaveOpenChanges(message string) {\n\tutil.Ensure(!HasOpenChanges(), \"You have uncommitted changes. \"+message)\n}\n\n\nvar rootDirectory string\n\n\n\nfunc GetRootDirectory() string {\n\tif rootDirectory == \"\" {\n\t\trootDirectory = command.MustRun(\"git\", \"rev-parse\", \"--show-toplevel\").OutputSanitized()\n\t}\n\treturn rootDirectory\n}\n\n\n\n\n\nfunc HasOpenChanges() bool {\n\treturn command.MustRun(\"git\", \"status\", \"--porcelain\").OutputSanitized() != \"\"\n}\n\n\n\nfunc HasShippableChanges(branchName string) bool {\n\treturn command.MustRun(\"git\", \"diff\", Config().GetMainBranch()+\"..\"+branchName).OutputSanitized() != \"\"\n}\n\n\n\nfunc IsMergeInProgress() bool {\n\t_, err := os.Stat(fmt.Sprintf(\"%s/.git/MERGE_HEAD\", GetRootDirectory()))\n\treturn err == nil\n}\n\n\n\nfunc IsRebaseInProgress() bool {\n\treturn command.MustRun(\"git\", \"status\").OutputContainsText(\"rebase in progress\")\n}\n\nfunc HasConflicts() bool ", "output": "{\n\treturn command.MustRun(\"git\", \"status\").OutputContainsText(\"Unmerged paths\")\n}"} {"input": "package main\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\nconst (\n\tFilePermission = 0644\n\n\tDirPermission = 0755\n)\n\n\n\n\n\n\n\n\n\nfunc dirExists(paths ...string) error {\n\tpath := strings.Join(paths, string(filepath.Separator))\n\n\tstat, err := os.Lstat(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !stat.IsDir() {\n\t\treturn newError(\"Path is not a directory.\")\n\t}\n\n\treturn nil\n}\n\nfunc ValidatePath(path string) (string, error) ", "output": "{\n\tpath, err := filepath.Abs(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = dirExists(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = dirExists(path, \"posts\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = dirExists(path, \"static\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = dirExists(path, \"templates\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdeploy := filepath.Join(path, \"deploy\")\n\terr = os.RemoveAll(deploy)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = os.MkdirAll(filepath.Join(deploy, \"posts\"), DirPermission)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn path, os.MkdirAll(filepath.Join(deploy, \"tags\"), DirPermission)\n}"} {"input": "package remote\n\nimport (\n\t\"os\"\n\n\t\"go.ligato.io/cn-infra/v2/config\"\n\t\"go.ligato.io/cn-infra/v2/db/keyval/etcd\"\n\t\"go.ligato.io/cn-infra/v2/logging/logrus\"\n)\n\n\n\n\nfunc CreateEtcdClient(configFile string) (*etcd.BytesConnectionEtcd, error) ", "output": "{\n\tif configFile == \"\" {\n\t\tconfigFile = os.Getenv(\"ETCD_CONFIG\")\n\t}\n\n\tcfg := &etcd.Config{}\n\tif configFile != \"\" {\n\t\tif err := config.ParseConfigFromYamlFile(configFile, cfg); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tetcdConfig, err := etcd.ConfigToClient(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn etcd.NewEtcdConnectionWithBytes(*etcdConfig, logrus.DefaultLogger())\n}"} {"input": "package util\n\nimport (\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com/mholt/archiver/v3\"\n\t\"github.com/nuclio/errors\"\n\t\"github.com/nuclio/logger\"\n)\n\ntype Decompressor struct {\n\tlogger logger.Logger\n}\n\n\n\nfunc (d *Decompressor) Decompress(source string, target string) error {\n\tif err := archiver.Unarchive(source, target); err != nil {\n\t\treturn errors.Wrapf(err, \"Failed to decompress file %s\", source)\n\t}\n\n\treturn nil\n}\n\nfunc IsCompressed(source string) bool {\n\n\tif IsJar(source) {\n\t\treturn false\n\t}\n\n\tunarchiver, err := archiver.ByExtension(source)\n\tif err != nil {\n\t\treturn false\n\t}\n\tu, ok := unarchiver.(archiver.Unarchiver)\n\tif !ok {\n\t\treturn false\n\t}\n\n\treturn u != nil\n}\n\nfunc IsJar(source string) bool {\n\treturn strings.ToLower(path.Ext(source)) == \".jar\"\n}\n\nfunc NewDecompressor(parentLogger logger.Logger) (*Decompressor, error) ", "output": "{\n\tnewDecompressor := &Decompressor{\n\t\tlogger: parentLogger,\n\t}\n\n\treturn newDecompressor, nil\n}"} {"input": "package ufile\n\nimport (\n\t\"github.com/ucloud/ucloud-sdk-go/ucloud/request\"\n\t\"github.com/ucloud/ucloud-sdk-go/ucloud/response\"\n)\n\n\ntype CreateBucketRequest struct {\n\trequest.CommonBase\n\n\n\n\tBucketName *string `required:\"true\"`\n\n\tType *string `required:\"false\"`\n}\n\n\ntype CreateBucketResponse struct {\n\tresponse.CommonBase\n\n\tBucketId string\n\n\tBucketName string\n}\n\n\nfunc (c *UFileClient) NewCreateBucketRequest() *CreateBucketRequest {\n\treq := &CreateBucketRequest{}\n\n\tc.Client.SetupRequest(req)\n\n\treq.SetRetryable(false)\n\treturn req\n}\n\n\n\n\nfunc (c *UFileClient) CreateBucket(req *CreateBucketRequest) (*CreateBucketResponse, error) ", "output": "{\n\tvar err error\n\tvar res CreateBucketResponse\n\n\treqCopier := *req\n\n\terr = c.Client.InvokeAction(\"CreateBucket\", &reqCopier, &res)\n\tif err != nil {\n\t\treturn &res, err\n\t}\n\n\treturn &res, nil\n}"} {"input": "package discogs\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\nfunc TestGetArtist(t *testing.T) {\n\n\texpectedResult := \"Blunted Dummies\"\n\n\tclient := getClient(t)\n\tartist, _, err := client.Database.GetArtist(4130)\n\tcheck(t, err)\n\n\tassert(t, artist.Name == expectedResult, fmt.Sprintf(\"Artist.name expected %s, received %s \", expectedResult, artist.Name))\n}\n\n\n\n\nfunc TestGetArtistReleases(t *testing.T) ", "output": "{\n\n\texpectedResult := 1\n\n\tclient := getClient(t)\n\treleases, _, err := client.Database.GetArtistReleases(4130)\n\tcheck(t, err)\n\n\tassert(t, releases.Pagination.Pages == expectedResult, fmt.Sprintf(\"Artist.Pagination.Pages expected %d, received %d\", expectedResult, releases.Pagination.Pages))\n\n}"} {"input": "package state\n\nimport (\n\t\"strconv\"\n\t. \"bugnuts/maps\"\n\t. \"bugnuts/torus\"\n\t. \"bugnuts/util\"\n)\n\nfunc (s *State) FoodLocations() (l []Location) {\n\tfor loc := range s.Food {\n\t\tl = append(l, Location(loc))\n\t}\n\n\treturn l\n}\n\nfunc (s *State) HillLocations(player int) (l []Location) {\n\tfor loc, hill := range s.Hills {\n\t\tif hill.Player == player && hill.Killed == 0 {\n\t\t\tl = append(l, Location(loc))\n\t\t}\n\t}\n\n\treturn l\n}\n\nfunc (s *State) EnemyHillLocations(player int) (l []Location) {\n\tfor loc, hill := range s.Hills {\n\t\tif hill.Player != player && hill.Killed == 0 {\n\t\t\tl = append(l, Location(loc))\n\t\t}\n\t}\n\n\treturn l\n}\n\n\n\nfunc (s *State) Stepable(loc Location) bool {\n\ti := s.Map.Grid[loc]\n\n\treturn i != WATER && i != BLOCK && i != FOOD\n}\n\nfunc (m *Metrics) DumpSeen() string {\n\tmax := Max(m.Seen)\n\tstr := \"\"\n\n\tfor r := 0; r < m.Rows; r++ {\n\t\tfor c := 0; c < m.Cols; c++ {\n\t\t\tstr += strconv.Itoa(m.Seen[r*m.Cols+c] * 10 / (max + 1))\n\t\t}\n\t\tstr += \"\\n\"\n\t}\n\n\treturn str\n}\n\nfunc (s *State) ValidStep(loc Location) bool ", "output": "{\n\ti := s.Map.Grid[loc]\n\n\treturn i != WATER && i != BLOCK && i != OCCUPIED && i != FOOD && i != MY_ANT && i != MY_HILLANT\n}"} {"input": "package aianomalydetection\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype DataSourceDetailsInflux struct {\n\tVersionSpecificDetails InfluxDetails `mandatory:\"true\" json:\"versionSpecificDetails\"`\n\n\tUserName *string `mandatory:\"true\" json:\"userName\"`\n\n\tPasswordSecretId *string `mandatory:\"true\" json:\"passwordSecretId\"`\n\n\tMeasurementName *string `mandatory:\"true\" json:\"measurementName\"`\n\n\tUrl *string `mandatory:\"true\" json:\"url\"`\n}\n\nfunc (m DataSourceDetailsInflux) String() string {\n\treturn common.PointerString(m)\n}\n\n\nfunc (m DataSourceDetailsInflux) MarshalJSON() (buff []byte, e error) {\n\ttype MarshalTypeDataSourceDetailsInflux DataSourceDetailsInflux\n\ts := struct {\n\t\tDiscriminatorParam string `json:\"dataSourceType\"`\n\t\tMarshalTypeDataSourceDetailsInflux\n\t}{\n\t\t\"INFLUX\",\n\t\t(MarshalTypeDataSourceDetailsInflux)(m),\n\t}\n\n\treturn json.Marshal(&s)\n}\n\n\n\n\nfunc (m *DataSourceDetailsInflux) UnmarshalJSON(data []byte) (e error) ", "output": "{\n\tmodel := struct {\n\t\tVersionSpecificDetails influxdetails `json:\"versionSpecificDetails\"`\n\t\tUserName *string `json:\"userName\"`\n\t\tPasswordSecretId *string `json:\"passwordSecretId\"`\n\t\tMeasurementName *string `json:\"measurementName\"`\n\t\tUrl *string `json:\"url\"`\n\t}{}\n\n\te = json.Unmarshal(data, &model)\n\tif e != nil {\n\t\treturn\n\t}\n\tvar nn interface{}\n\tnn, e = model.VersionSpecificDetails.UnmarshalPolymorphicJSON(model.VersionSpecificDetails.JsonData)\n\tif e != nil {\n\t\treturn\n\t}\n\tif nn != nil {\n\t\tm.VersionSpecificDetails = nn.(InfluxDetails)\n\t} else {\n\t\tm.VersionSpecificDetails = nil\n\t}\n\n\tm.UserName = model.UserName\n\n\tm.PasswordSecretId = model.PasswordSecretId\n\n\tm.MeasurementName = model.MeasurementName\n\n\tm.Url = model.Url\n\n\treturn\n}"} {"input": "package native\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\n\t\"github.com/docker/docker/pkg/reexec\"\n\t\"github.com/docker/libcontainer\"\n)\n\nfunc init() {\n\treexec.Register(DriverName, initializer)\n}\n\nfunc fatal(err error) {\n\tif lerr, ok := err.(libcontainer.Error); ok {\n\t\tlerr.Detail(os.Stderr)\n\t\tos.Exit(1)\n\t}\n\n\tfmt.Fprintln(os.Stderr, err)\n\tos.Exit(1)\n}\n\nfunc initializer() {\n\truntime.GOMAXPROCS(1)\n\truntime.LockOSThread()\n\tfactory, err := libcontainer.New(\"\")\n\tif err != nil {\n\t\tfatal(err)\n\t}\n\tif err := factory.StartInitialization(); err != nil {\n\t\tfatal(err)\n\t}\n\n\tpanic(\"unreachable\")\n}\n\n\n\nfunc writeError(err error) ", "output": "{\n\tfmt.Fprint(os.Stderr, err)\n\tos.Exit(1)\n}"} {"input": "package probe_test\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/minio/mc/pkg/probe\"\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc Test(t *testing.T) { TestingT(t) }\n\ntype MySuite struct{}\n\nvar _ = Suite(&MySuite{})\n\nfunc testDummy0() *probe.Error {\n\t_, e := os.Stat(\"this-file-cannot-exit\")\n\treturn probe.NewError(e)\n}\n\nfunc testDummy1() *probe.Error {\n\treturn testDummy0().Trace(\"DummyTag1\")\n}\n\nfunc testDummy2() *probe.Error {\n\treturn testDummy1().Trace(\"DummyTag2\")\n}\n\nfunc (s *MySuite) TestProbe(c *C) {\n\tprobe.Init() \n\tprobe.SetAppInfo(\"Commit-ID\", \"7390cc957239\")\n\tes := testDummy2().Trace(\"TopOfStack\")\n\tc.Assert(es, Not(Equals), nil)\n\n\tnewES := es.Trace()\n\tc.Assert(newES, Not(Equals), nil)\n}\n\n\n\nfunc (s *MySuite) TestWrappedError(c *C) ", "output": "{\n\t_, e := os.Stat(\"this-file-cannot-exit\")\n\tes := probe.NewError(e) \n\te = probe.WrapError(es) \n\t_, ok := probe.UnwrapError(e)\n\tc.Assert(ok, Equals, true)\n}"} {"input": "package v1\n\nimport context \"context\"\n\nimport proto \"github.com/golang/protobuf/proto\"\nimport \"go-common/library/net/rpc/liverpc\"\n\nvar _ proto.Message \n\n\n\n\n\n\ntype AdminSilent interface {\n\tGetShieldRule(context.Context, *AdminSilentGetShieldRuleReq) (*AdminSilentGetShieldRuleResp, error)\n}\n\n\n\n\n\ntype adminSilentRpcClient struct {\n\tclient *liverpc.Client\n}\n\n\n\nfunc NewAdminSilentRpcClient(client *liverpc.Client) AdminSilent {\n\treturn &adminSilentRpcClient{\n\t\tclient: client,\n\t}\n}\n\n\n\n\n\n\n\nfunc doRpcRequest(ctx context.Context, client *liverpc.Client, version int, method string, in, out proto.Message) (err error) {\n\terr = client.Call(ctx, version, method, in, out)\n\treturn\n}\n\nfunc (c *adminSilentRpcClient) GetShieldRule(ctx context.Context, in *AdminSilentGetShieldRuleReq) (*AdminSilentGetShieldRuleResp, error) ", "output": "{\n\tout := new(AdminSilentGetShieldRuleResp)\n\terr := doRpcRequest(ctx, c.client, 1, \"AdminSilent.get_shield_rule\", in, out)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}"} {"input": "package redis\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/deepfabric/elasticell/pkg/pb/raftcmdpb\"\n\t\"github.com/fagongzi/goetty\"\n\tgredis \"github.com/fagongzi/goetty/protocol/redis\"\n\t\"github.com/fagongzi/util/format\"\n\t\"github.com/fagongzi/util/hack\"\n)\n\nconst (\n\tpong = \"PONG\"\n)\n\nvar (\n\tErrNotSupportCommand = []byte(\"command is not support\")\n\tErrInvalidCommandResp = []byte(\"invalid command\")\n\tPongResp = []byte(\"PONG\")\n\tOKStatusResp = []byte(\"OK\")\n)\n\n\n\n\n\nfunc WriteScorePairArray(lst []*raftcmdpb.ScorePair, withScores bool, buf *goetty.ByteBuf) {\n\tbuf.WriteByte('*')\n\tif len(lst) == 0 {\n\t\tbuf.Write(gredis.NullArray)\n\t\tbuf.Write(gredis.Delims)\n\t} else {\n\t\tif withScores {\n\t\t\tbuf.Write(hack.StringToSlice(strconv.Itoa(len(lst) * 2)))\n\t\t\tbuf.Write(gredis.Delims)\n\t\t} else {\n\t\t\tbuf.Write(hack.StringToSlice(strconv.Itoa(len(lst))))\n\t\t\tbuf.Write(gredis.Delims)\n\t\t}\n\n\t\tfor i := 0; i < len(lst); i++ {\n\t\t\tgredis.WriteBulk(lst[i].Member, buf)\n\n\t\t\tif withScores {\n\t\t\t\tgredis.WriteBulk(format.Float64ToString(lst[i].Score), buf)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc WriteFVPairArray(lst []*raftcmdpb.FVPair, buf *goetty.ByteBuf) ", "output": "{\n\tbuf.WriteByte('*')\n\tif len(lst) == 0 {\n\t\tbuf.Write(gredis.NullArray)\n\t\tbuf.Write(gredis.Delims)\n\t} else {\n\t\tbuf.Write(hack.StringToSlice(strconv.Itoa(len(lst) * 2)))\n\t\tbuf.Write(gredis.Delims)\n\n\t\tfor i := 0; i < len(lst); i++ {\n\t\t\tgredis.WriteBulk(lst[i].Field, buf)\n\t\t\tgredis.WriteBulk(lst[i].Value, buf)\n\t\t}\n\t}\n}"} {"input": "package x\n\nimport (\n\t\"bytes\"\n\t\"net/http\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/pkg/errors\"\n\t\"github.com/sirupsen/logrus\"\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"github.com/ory/x/logrusx\"\n)\n\ntype errStackTracer struct{}\n\nfunc (s *errStackTracer) StackTrace() errors.StackTrace {\n\treturn errors.StackTrace{}\n}\n\n\n\nfunc TestLogError(t *testing.T) {\n\tr, err := http.NewRequest(http.MethodGet, \"https://hydra/some/endpoint\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tbuf := bytes.NewBuffer([]byte{})\n\tl := logrusx.New(\"\", \"\", logrusx.ForceLevel(logrus.TraceLevel))\n\tl.Logger.Out = buf\n\tLogError(r, errors.New(\"asdf\"), l)\n\n\tt.Logf(\"%s\", string(buf.Bytes()))\n\n\tassert.True(t, strings.Contains(string(buf.Bytes()), \"trace\"))\n\n\tLogError(r, errors.Wrap(new(errStackTracer), \"\"), l)\n}\n\nfunc TestLogErrorDoesNotPanic(t *testing.T) {\n\tr, err := http.NewRequest(http.MethodGet, \"https://hydra/some/endpoint\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tLogError(r, errors.New(\"asdf\"), nil)\n}\n\nfunc (s *errStackTracer) Error() string ", "output": "{\n\treturn \"foo\"\n}"} {"input": "package mos\n\nimport (\n\t\"github.com/atnet/gof/web\"\n\t\"net/http\"\n)\n\nvar (\n\troutes *web.RouteMap = new(web.RouteMap)\n)\n\n\n\n\nfunc handleError(w http.ResponseWriter, err error) {\n\tw.Write([]byte(`` + err.Error() + ``))\n}\n\n\nfunc registerRoutes() {\n\tmc := new(mainC)\n\troutes.Add(\"/\",mc.Index)\n}\n\nfunc init(){\n\tregisterRoutes()\n}\n\nfunc Handle(ctx *web.Context) ", "output": "{\n\troutes.Handle(ctx)\n}"} {"input": "package mpb\n\nimport (\n\t\"io\"\n\t\"strings\"\n\t\"unicode/utf8\"\n\n\t\"github.com/vbauerster/mpb/decor\"\n)\n\n\ntype SpinnerAlignment int\n\n\nconst (\n\tSpinnerOnLeft SpinnerAlignment = iota\n\tSpinnerOnMiddle\n\tSpinnerOnRight\n)\n\nvar defaultSpinnerStyle = []string{\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"}\n\ntype spinnerFiller struct {\n\tframes []string\n\tcount uint\n\talignment SpinnerAlignment\n}\n\n\n\nfunc (s *spinnerFiller) Fill(w io.Writer, width int, stat *decor.Statistics) ", "output": "{\n\n\tframe := s.frames[s.count%uint(len(s.frames))]\n\tframeWidth := utf8.RuneCountInString(frame)\n\n\tif width < frameWidth {\n\t\treturn\n\t}\n\n\tswitch rest := width - frameWidth; s.alignment {\n\tcase SpinnerOnLeft:\n\t\tio.WriteString(w, frame+strings.Repeat(\" \", rest))\n\tcase SpinnerOnMiddle:\n\t\tstr := strings.Repeat(\" \", rest/2) + frame + strings.Repeat(\" \", rest/2+rest%2)\n\t\tio.WriteString(w, str)\n\tcase SpinnerOnRight:\n\t\tio.WriteString(w, strings.Repeat(\" \", rest)+frame)\n\t}\n\ts.count++\n}"} {"input": "package billing\n\nimport original \"github.com/Azure/azure-sdk-for-go/services/billing/mgmt/2017-04-24-preview/billing\"\n\nconst (\n\tDefaultBaseURI = original.DefaultBaseURI\n)\n\ntype ManagementClient = original.ManagementClient\ntype InvoicesClient = original.InvoicesClient\ntype DownloadURL = original.DownloadURL\ntype ErrorDetails = original.ErrorDetails\ntype ErrorResponse = original.ErrorResponse\ntype Invoice = original.Invoice\ntype InvoiceProperties = original.InvoiceProperties\ntype InvoicesListResult = original.InvoicesListResult\ntype Operation = original.Operation\ntype OperationDisplay = original.OperationDisplay\ntype OperationListResult = original.OperationListResult\ntype Period = original.Period\ntype PeriodProperties = original.PeriodProperties\ntype PeriodsListResult = original.PeriodsListResult\ntype Resource = original.Resource\ntype OperationsClient = original.OperationsClient\ntype PeriodsClient = original.PeriodsClient\n\nfunc NewOperationsClient(subscriptionID string) OperationsClient {\n\treturn original.NewOperationsClient(subscriptionID)\n}\n\nfunc NewPeriodsClient(subscriptionID string) PeriodsClient {\n\treturn original.NewPeriodsClient(subscriptionID)\n}\nfunc NewPeriodsClientWithBaseURI(baseURI string, subscriptionID string) PeriodsClient {\n\treturn original.NewPeriodsClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc UserAgent() string {\n\treturn original.UserAgent() + \" profiles/preview\"\n}\nfunc Version() string {\n\treturn original.Version()\n}\nfunc New(subscriptionID string) ManagementClient {\n\treturn original.New(subscriptionID)\n}\nfunc NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient {\n\treturn original.NewWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewInvoicesClient(subscriptionID string) InvoicesClient {\n\treturn original.NewInvoicesClient(subscriptionID)\n}\nfunc NewInvoicesClientWithBaseURI(baseURI string, subscriptionID string) InvoicesClient {\n\treturn original.NewInvoicesClientWithBaseURI(baseURI, subscriptionID)\n}\n\nfunc NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient ", "output": "{\n\treturn original.NewOperationsClientWithBaseURI(baseURI, subscriptionID)\n}"} {"input": "package group\n\nimport (\n\t\"github.com/wandoulabs/codis/pkg/models\"\n\n\tlog \"github.com/ngaut/logging\"\n)\n\ntype Group struct {\n\tmaster string\n\tredisServers map[string]*models.Server\n}\n\nfunc (g *Group) Master() string {\n\treturn g.master\n}\n\n\n\nfunc NewGroup(groupInfo models.ServerGroup) *Group ", "output": "{\n\tg := &Group{\n\t\tredisServers: make(map[string]*models.Server),\n\t}\n\n\tfor _, server := range groupInfo.Servers {\n\t\tif server.Type == models.SERVER_TYPE_MASTER {\n\t\t\tif len(g.master) > 0 {\n\t\t\t\tlog.Fatalf(\"two master not allowed: %+v\", groupInfo)\n\t\t\t}\n\n\t\t\tg.master = server.Addr\n\t\t}\n\t\tg.redisServers[server.Addr] = server\n\t}\n\n\tif len(g.master) == 0 {\n\t\tlog.Fatalf(\"master not found: %+v\", groupInfo)\n\t}\n\n\treturn g\n}"} {"input": "package appfilesfakes\n\nimport (\n\t\"sync\"\n\n\t\"code.cloudfoundry.org/cli/cf/api/appfiles\"\n)\n\ntype FakeAppFilesRepository struct {\n\tListFilesStub func(appGUID string, instance int, path string) (files string, apiErr error)\n\tlistFilesMutex sync.RWMutex\n\tlistFilesArgsForCall []struct {\n\t\tappGUID string\n\t\tinstance int\n\t\tpath string\n\t}\n\tlistFilesReturns struct {\n\t\tresult1 string\n\t\tresult2 error\n\t}\n}\n\n\n\nfunc (fake *FakeAppFilesRepository) ListFilesCallCount() int {\n\tfake.listFilesMutex.RLock()\n\tdefer fake.listFilesMutex.RUnlock()\n\treturn len(fake.listFilesArgsForCall)\n}\n\nfunc (fake *FakeAppFilesRepository) ListFilesArgsForCall(i int) (string, int, string) {\n\tfake.listFilesMutex.RLock()\n\tdefer fake.listFilesMutex.RUnlock()\n\treturn fake.listFilesArgsForCall[i].appGUID, fake.listFilesArgsForCall[i].instance, fake.listFilesArgsForCall[i].path\n}\n\nfunc (fake *FakeAppFilesRepository) ListFilesReturns(result1 string, result2 error) {\n\tfake.ListFilesStub = nil\n\tfake.listFilesReturns = struct {\n\t\tresult1 string\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nvar _ appfiles.Repository = new(FakeAppFilesRepository)\n\nfunc (fake *FakeAppFilesRepository) ListFiles(appGUID string, instance int, path string) (files string, apiErr error) ", "output": "{\n\tfake.listFilesMutex.Lock()\n\tfake.listFilesArgsForCall = append(fake.listFilesArgsForCall, struct {\n\t\tappGUID string\n\t\tinstance int\n\t\tpath string\n\t}{appGUID, instance, path})\n\tfake.listFilesMutex.Unlock()\n\tif fake.ListFilesStub != nil {\n\t\treturn fake.ListFilesStub(appGUID, instance, path)\n\t} else {\n\t\treturn fake.listFilesReturns.result1, fake.listFilesReturns.result2\n\t}\n}"} {"input": "package violetear\n\nimport (\n\t\"net/http\"\n\t\"time\"\n)\n\n\ntype ResponseWriter struct {\n\thttp.ResponseWriter\n\trequestID string\n\tsize, status int\n\tstart time.Time\n}\n\n\nfunc NewResponseWriter(w http.ResponseWriter, rid string) *ResponseWriter {\n\treturn &ResponseWriter{\n\t\tResponseWriter: w,\n\t\trequestID: rid,\n\t\tstart: time.Now(),\n\t\tstatus: http.StatusOK,\n\t}\n}\n\n\nfunc (w *ResponseWriter) Status() int {\n\treturn w.status\n}\n\n\n\n\n\nfunc (w *ResponseWriter) RequestTime() string {\n\treturn time.Since(w.start).String()\n}\n\n\nfunc (w *ResponseWriter) RequestID() string {\n\treturn w.requestID\n}\n\n\n\nfunc (w *ResponseWriter) Write(data []byte) (int, error) {\n\tsize, err := w.ResponseWriter.Write(data)\n\tw.size += size\n\treturn size, err\n}\n\n\n\nfunc (w *ResponseWriter) WriteHeader(statusCode int) {\n\tw.status = statusCode\n\tw.ResponseWriter.WriteHeader(statusCode)\n}\n\nfunc (w *ResponseWriter) Size() int ", "output": "{\n\treturn w.size\n}"} {"input": "package tpu\n\nimport (\n\t\"strings\"\n\n\tapiv1 \"k8s.io/api/core/v1\"\n)\n\nconst (\n\tResourceTPUPrefix = \"cloud-tpus.google.com/\"\n)\n\n\n\nfunc clearTPURequest(pod *apiv1.Pod) *apiv1.Pod {\n\tsanitized := pod.DeepCopy()\n\tfor _, container := range sanitized.Spec.Containers {\n\t\tfor name := range container.Resources.Requests {\n\t\t\tif strings.HasPrefix(string(name), ResourceTPUPrefix) {\n\t\t\t\tdelete(container.Resources.Requests, name)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn sanitized\n}\n\n\n\nfunc ClearTPURequests(pods []*apiv1.Pod) []*apiv1.Pod {\n\tpodsWithTPU := make(map[int]*apiv1.Pod)\n\tfor i, pod := range pods {\n\t\tif hasTPURequest(pod) {\n\t\t\tpodsWithTPU[i] = clearTPURequest(pod)\n\t\t}\n\t}\n\n\tif len(podsWithTPU) == 0 {\n\t\treturn pods\n\t}\n\n\tsanitizedPods := make([]*apiv1.Pod, len(pods))\n\tfor i, pod := range pods {\n\t\tif sanitized, found := podsWithTPU[i]; found {\n\t\t\tsanitizedPods[i] = sanitized\n\t\t} else {\n\t\t\tsanitizedPods[i] = pod\n\t\t}\n\t}\n\treturn sanitizedPods\n}\n\nfunc hasTPURequest(pod *apiv1.Pod) bool ", "output": "{\n\tfor _, container := range pod.Spec.Containers {\n\t\tfor name := range container.Resources.Requests {\n\t\t\tif strings.HasPrefix(string(name), ResourceTPUPrefix) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}"} {"input": "package location\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype (\n\tlocation struct {\n\t\tscheme string\n\t\thost string\n\t\tbase string\n\t\theaders Headers\n\t}\n)\n\n\n\nfunc (l *location) applyToContext(c *gin.Context) {\n\tvalue := new(url.URL)\n\tvalue.Scheme = l.resolveScheme(c.Request)\n\tvalue.Host = l.resolveHost(c.Request)\n\tvalue.Path = l.base\n\tc.Set(key, value)\n}\n\nfunc (l *location) resolveScheme(r *http.Request) string {\n\tswitch {\n\tcase r.Header.Get(l.headers.Scheme) == \"https\":\n\t\treturn \"https\"\n\tcase r.URL.Scheme == \"https\":\n\t\treturn \"https\"\n\tcase r.TLS != nil:\n\t\treturn \"https\"\n\tcase strings.HasPrefix(r.Proto, \"HTTPS\"):\n\t\treturn \"https\"\n\tdefault:\n\t\treturn l.scheme\n\t}\n}\n\nfunc (l *location) resolveHost(r *http.Request) (host string) {\n\tswitch {\n\tcase r.Header.Get(l.headers.Host) != \"\":\n\t\treturn r.Header.Get(l.headers.Host)\n\tcase r.Header.Get(\"X-Host\") != \"\":\n\t\treturn r.Header.Get(\"X-Host\")\n\tcase r.Host != \"\":\n\t\treturn r.Host\n\tcase r.URL.Host != \"\":\n\t\treturn r.URL.Host\n\tdefault:\n\t\treturn l.host\n\t}\n}\n\nfunc newLocation(config Config) *location ", "output": "{\n\treturn &location{\n\t\tscheme: config.Scheme,\n\t\thost: config.Host,\n\t\tbase: config.Base,\n\t\theaders: config.Headers,\n\t}\n}"} {"input": "package state\n\nimport (\n\t\"net/url\"\n\n\t\"gopkg.in/juju/charm.v3\"\n)\n\n\ntype charmDoc struct {\n\tURL *charm.URL `bson:\"_id\"`\n\tMeta *charm.Meta\n\tConfig *charm.Config\n\tActions *charm.Actions\n\tBundleURL *url.URL\n\tBundleSha256 string\n\tPendingUpload bool\n\tPlaceholder bool\n}\n\n\ntype Charm struct {\n\tst *State\n\tdoc charmDoc\n}\n\nfunc newCharm(st *State, cdoc *charmDoc) (*Charm, error) {\n\treturn &Charm{st: st, doc: *cdoc}, nil\n}\n\nfunc (c *Charm) String() string {\n\treturn c.doc.URL.String()\n}\n\n\nfunc (c *Charm) URL() *charm.URL {\n\tclone := *c.doc.URL\n\treturn &clone\n}\n\n\n\nfunc (c *Charm) Revision() int {\n\treturn c.doc.URL.Revision\n}\n\n\nfunc (c *Charm) Meta() *charm.Meta {\n\treturn c.doc.Meta\n}\n\n\nfunc (c *Charm) Config() *charm.Config {\n\treturn c.doc.Config\n}\n\n\nfunc (c *Charm) Actions() *charm.Actions {\n\treturn c.doc.Actions\n}\n\n\n\nfunc (c *Charm) BundleURL() *url.URL {\n\treturn c.doc.BundleURL\n}\n\n\nfunc (c *Charm) BundleSha256() string {\n\treturn c.doc.BundleSha256\n}\n\n\n\nfunc (c *Charm) IsUploaded() bool {\n\treturn !c.doc.PendingUpload\n}\n\n\n\n\n\nfunc (c *Charm) IsPlaceholder() bool ", "output": "{\n\treturn c.doc.Placeholder\n}"} {"input": "package server\n\nimport (\n\t\"fmt\"\n\t\"github.com/centurylinkcloud/clc-go-cli/base\"\n)\n\ntype Server struct {\n\tServerId string\n\tServerName string\n}\n\nfunc (s *Server) Validate() error {\n\tif (s.ServerId == \"\") == (s.ServerName == \"\") {\n\t\treturn fmt.Errorf(\"Exactly one of the server-id and server-name must be set.\")\n\t}\n\treturn nil\n}\n\nfunc (s *Server) InferID(cn base.Connection) error {\n\tif s.ServerName == \"\" {\n\t\treturn nil\n\t}\n\n\tID, err := IDByName(cn, s.ServerName)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.ServerId = ID\n\treturn nil\n}\n\n\n\nfunc (s *Server) GetNames(cn base.Connection, property string) ([]string, error) ", "output": "{\n\tif property != \"ServerName\" {\n\t\treturn nil, nil\n\t}\n\n\treturn GetNames(cn, \"all\")\n}"} {"input": "package comm\n\nimport (\n\t\"context\"\n\n\t\"github.com/hyperledger/fabric/common/semaphore\"\n\t\"google.golang.org/grpc\"\n)\n\ntype Semaphore interface {\n\tAcquire(ctx context.Context) error\n\tRelease()\n}\n\ntype Throttle struct {\n\tnewSemaphore NewSemaphoreFunc\n\tsemaphore Semaphore\n}\n\ntype ThrottleOption func(t *Throttle)\ntype NewSemaphoreFunc func(size int) Semaphore\n\n\n\nfunc NewThrottle(maxConcurrency int, options ...ThrottleOption) *Throttle {\n\tt := &Throttle{\n\t\tnewSemaphore: func(count int) Semaphore { return semaphore.New(count) },\n\t}\n\n\tfor _, optionFunc := range options {\n\t\toptionFunc(t)\n\t}\n\n\tt.semaphore = t.newSemaphore(maxConcurrency)\n\treturn t\n}\n\nfunc (t *Throttle) UnaryServerIntercptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {\n\tif err := t.semaphore.Acquire(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\tdefer t.semaphore.Release()\n\n\treturn handler(ctx, req)\n}\n\nfunc (t *Throttle) StreamServerInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {\n\tctx := ss.Context()\n\tif err := t.semaphore.Acquire(ctx); err != nil {\n\t\treturn err\n\t}\n\tdefer t.semaphore.Release()\n\n\treturn handler(srv, ss)\n}\n\nfunc WithNewSemaphore(newSemaphore NewSemaphoreFunc) ThrottleOption ", "output": "{\n\treturn func(t *Throttle) {\n\t\tt.newSemaphore = newSemaphore\n\t}\n}"} {"input": "package markdown\n\nimport (\n\t\"bufio\"\n\t\"io\"\n)\n\ntype writer interface {\n\tWrite([]byte) (int, error)\n\tWriteByte(byte) error\n\tWriteString(string) (int, error)\n\tFlush() error\n}\n\ntype monadicWriter struct {\n\twriter\n\terr error\n}\n\nfunc newMonadicWriter(w io.Writer) *monadicWriter {\n\tif w, ok := w.(writer); ok {\n\t\treturn &monadicWriter{writer: w}\n\t}\n\treturn &monadicWriter{writer: bufio.NewWriter(w)}\n}\n\nfunc (w *monadicWriter) Write(p []byte) (n int, err error) {\n\tif w.err != nil {\n\t\treturn\n\t}\n\n\tn, err = w.writer.Write(p)\n\tw.err = err\n\treturn\n}\n\n\n\nfunc (w *monadicWriter) WriteString(s string) (n int, err error) {\n\tif w.err != nil {\n\t\treturn\n\t}\n\n\tn, err = w.writer.WriteString(s)\n\tw.err = err\n\treturn\n}\n\nfunc (w *monadicWriter) Flush() (err error) {\n\tif w.err != nil {\n\t\treturn\n\t}\n\n\terr = w.writer.Flush()\n\tw.err = err\n\treturn\n}\n\nfunc (w *monadicWriter) WriteByte(b byte) (err error) ", "output": "{\n\tif w.err != nil {\n\t\treturn\n\t}\n\n\terr = w.writer.WriteByte(b)\n\tw.err = err\n\treturn\n}"} {"input": "package echo\n\nimport (\n\t\"context\"\n\n\t\"github.com/uber/zanzibar/examples/example-gateway/build/endpoints/tchannel/echo/module\"\n\t\"github.com/uber/zanzibar/examples/example-gateway/build/endpoints/tchannel/echo/workflow\"\n\t\"github.com/uber/zanzibar/examples/example-gateway/build/gen-code/endpoints-idl/endpoints/tchannel/echo/echo\"\n\tzanzibar \"github.com/uber/zanzibar/runtime\"\n)\n\n\n\n\ntype echoWorkflow struct{}\n\n\nfunc (w echoWorkflow) Handle(\n\tctx context.Context,\n\treqHeaders zanzibar.Header,\n\treq *echo.Echo_Echo_Args,\n) (context.Context, string, zanzibar.Header, error) {\n\treturn ctx, req.Msg, nil, nil\n}\n\nfunc NewEchoEchoWorkflow(deps *module.Dependencies) workflow.EchoEchoWorkflow ", "output": "{\n\treturn &echoWorkflow{}\n}"} {"input": "package logging\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/Sirupsen/logrus\"\n)\n\nconst (\n\tLogFieldVolume = \"volume\"\n\tLogFieldVolumeDev = \"volume_dev\"\n\tLogFieldVolumeName = \"volume_name\"\n\tLogFieldOrigVolume = \"original_volume\"\n\tLogFieldSnapshot = \"snapshot\"\n\tLogFieldLastSnapshot = \"last_snapshot\"\n\tLogEventBackupURL = \"backup_url\"\n\tLogFieldDestURL = \"dest_url\"\n\tLogFieldKind = \"kind\"\n\tLogFieldFilepath = \"filepath\"\n\n\tLogFieldEvent = \"event\"\n\tLogEventBackup = \"backup\"\n\tLogEventRestore = \"restore\"\n\tLogEventCompare = \"compare\"\n\n\tLogFieldReason = \"reason\"\n\tLogReasonStart = \"start\"\n\tLogReasonComplete = \"complete\"\n\tLogReasonFallback = \"fallback\"\n\n\tLogFieldObject = \"object\"\n\tLogObjectSnapshot = \"snapshot\"\n\tLogObjectConfig = \"config\"\n)\n\n\ntype Error struct {\n\tentry *logrus.Entry\n\terror\n}\n\n\n\n\nfunc ErrorWithFields(pkg string, fields logrus.Fields, format string, v ...interface{}) Error ", "output": "{\n\tfields[\"pkg\"] = pkg\n\tentry := logrus.WithFields(fields)\n\tentry.Message = fmt.Sprintf(format, v...)\n\n\treturn Error{entry, fmt.Errorf(format, v...)}\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/gofxh/blog/app\"\n\t\"github.com/gofxh/blog/app/log\"\n)\n\nconst (\n\tSETTING_FORMAT_TEXT int8 = 16 \n\tSETTING_FORMAT_JSON int8 = 26 \n)\n\nvar Settings map[string]*Setting = make(map[string]*Setting)\n\n\ntype Setting struct {\n\tName string `xorm:\"unique(setting-name)\"`\n\tValue string\n\tFormat int8 `xorm:\"not null\"`\n\tUserId int64 `xorm:\"unique(setting-name)\"`\n}\n\n\nfunc (s *Setting) GetString() string {\n\treturn s.Value\n}\n\n\nfunc (s *Setting) GetJson(value interface{}) error {\n\treturn json.Unmarshal([]byte(s.Value), value)\n}\n\n\nfunc NewDefaultSetting(uid int64) []*Setting {\n\tm := make([]*Setting, 0)\n\tm = append(m, &Setting{\"theme\", \"default\", SETTING_FORMAT_TEXT, uid})\n\treturn m\n}\n\n\n\n\n\nfunc ReadSettingsToGlobal() error {\n\tsettings := make([]*Setting, 0)\n\tif err := app.Db.Find(&settings); err != nil {\n\t\tlog.Error(\"Db|ReadSettingsToGlobal|%s\", err.Error())\n\t\treturn err\n\t}\n\tfor _, s := range settings {\n\t\tSettings[s.Name] = s\n\t}\n\treturn nil\n}\n\nfunc SaveSettings(ss []*Setting) error ", "output": "{\n\tsess := app.Db.NewSession()\n\tdefer sess.Close()\n\tif err := sess.Begin(); err != nil {\n\t\tlog.Error(\"Db|SaveSettings|%s\", err.Error())\n\t\treturn err\n\t}\n\tfor _, s := range ss {\n\t\tsess.Insert(s)\n\t}\n\tif err := sess.Commit(); err != nil {\n\t\tlog.Error(\"Db|SaveSettings|%s\", err.Error())\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/kormat/go-slackapi/config\"\n\t\"github.com/kormat/go-slackapi/users\"\n)\n\ntype UserInfo struct {\n\tArgs struct {\n\t\tID string `description:\"User ID\"`\n\t} `positional-args:\"yes\" required:\"yes\"`\n}\ntype UserList struct{}\n\nvar userInfo UserInfo\nvar userList UserList\n\nfunc init() {\n\tparser.AddCommand(\"users.info\", \"Show user info\", \"\", &userInfo)\n\tparser.AddCommand(\"users.list\", \"List users\", \"\", &userList)\n}\n\n\n\nfunc (ul *UserList) Execute(_ []string) error {\n\tif config.CfgErr != nil {\n\t\treturn config.CfgErr\n\t}\n\tulist, err := users.List()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor i, u := range ulist {\n\t\tfmt.Printf(\"%d. `%s` (Id: %s)\\n\", i, u.Name, u.ID)\n\t}\n\treturn nil\n}\n\nfunc (u *UserInfo) Execute(_ []string) error ", "output": "{\n\tif config.CfgErr != nil {\n\t\treturn config.CfgErr\n\t}\n\tinfo, err := users.Info(u.Args.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(info)\n\treturn nil\n}"} {"input": "package persistence\nimport (\n\t. \"github.com/BitSmashers/Ezzah/model\"\n\t\"log\"\n)\n\n\ntype ConnectionTestImpl struct {\n\tartists []Artist\n}\n\nvar limit = 50\n\nfunc NewConnectionTest() ConnectionTestImpl {\n\treturn ConnectionTestImpl{make([]Artist, 0, 10)}\n}\n\n\n\nfunc (c *ConnectionTestImpl) SaveArtist(a Artist) {\n\tc.artists = addArtist(c.artists, a)\n}\n\nfunc (c *ConnectionTestImpl) SaveArtists(artists []Artist) {\n\tfor _, a := range artists {\n\t\tc.SaveArtist(a)\n\t}\n}\n\nfunc (c *ConnectionTestImpl) ToString() string {\n\treturn \"InMemory : \"\n}\n\nfunc (c *ConnectionTestImpl) FindArtists(name string) []Artist {\n\tresult := make([]Artist, limit, limit)\n\tidx := 0\n\tfor _, a := range c.artists {\n\t\tif a.Name == name {\n\t\t\tresult[idx] = a\n\t\t\tidx++\n\t\t}\n\t}\n\treturn result[0:idx]\n}\n\nfunc (c *ConnectionTestImpl) SaveAlbum(artist Artist, a Album) {\n}\n\nfunc (c *ConnectionTestImpl) SaveAlbums(artist Artist, albums []Album) {\n}\n\nfunc (c *ConnectionTestImpl) FindAlbum(title string) *Album {\n\treturn nil\n}\n\nfunc (c *ConnectionTestImpl) FindAlbums(artist Artist) []Album {\n\treturn nil\n}\n\nfunc (c *ConnectionTestImpl) DeleteArtist(id string) {\n}\n\nfunc (c *ConnectionTestImpl) FindSongsByArtist(artistName string) []Song {\n\nreturn nil\n}\nfunc (c *ConnectionTestImpl) SaveSong(song Song) {\n}\nfunc (c *ConnectionTestImpl) ClearDbPerLabel(label string) {\n}\n\nfunc addArtist(slice []Artist, element Artist) []Artist ", "output": "{\n\tif (len(slice) == cap(slice)) {\n\t\tlog.Println(\"Slice is full : \", cap(slice))\n\t}else {\n\t\tn := len(slice)\n\t\tslice = slice[0 : n + 1]\n\t\tslice[n] = element\n\t}\n\treturn slice\n\n}"} {"input": "package bookit\n\n\n\n\nconst (\n\tErrBookingNotFound = Error(\"Booking not found\")\n\tErrBookingExists = Error(\"Booking already exists, cannot create same booking twice\")\n\tErrBookingIDRequired = Error(\"No ID was received in booking_service, something must have gone during ID creation\")\n\tErrBookingUnmarshal = Error(\"An unexpected error occured when booking was read in database, please try again or contact system administrator\")\n\tErrBookingNoChange = Error(\"No change was done\")\n)\n\n\ntype Error string\n\n\n\n\nfunc (e Error) Error() string ", "output": "{ return string(e) }"} {"input": "package stats\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/go-webpack/webpack/util\"\n\t\"github.com/pkg/errors\"\n)\n\ntype assetList map[string][]string\n\n\n\n\nfunc parseChunk(d []string, akey string, assets *assetList) {\n\t(*assets)[akey+\".js\"] = util.Filter(d, func(v string) bool {\n\t\treturn strings.HasSuffix(v, \".js\")\n\t})\n\n\t(*assets)[akey+\".css\"] = util.Filter(d, func(v string) bool {\n\t\treturn strings.HasSuffix(v, \".css\")\n\t})\n}\n\n\nfunc parseManifest(data []byte) (assetList, error) {\n\tvar err error\n\n\tresp := statsResponse{}\n\terr = json.Unmarshal(data, &resp)\n\tif err != nil {\n\t\treturn assetList{}, errors.Wrap(err, \"go-webpack: Error parsing manifest - json decode\")\n\t}\n\twebpackBase := resp.PublicPath\n\n\tassets := make(assetList, len(resp.AssetsByChunkName))\n\n\tfor akey, aval := range resp.AssetsByChunkName {\n\t\tvar d []string\n\t\terr = json.Unmarshal(*aval, &d)\n\t\tif err != nil {\n\t\t\treturn assets, errors.Wrap(err, fmt.Sprintf(\"go-webpack: Error when parsing manifest for %s: %s %s\", akey, err, string(*aval)))\n\t\t}\n\t\tfor i, v := range d {\n\t\t\td[i] = webpackBase + v\n\t\t}\n\n\t\tparseChunk(d, akey, &assets)\n\t}\n\treturn assets, nil\n}\n\nfunc Read(isDev bool, host, fsPath, webPath string) (assetList, error) ", "output": "{\n\tvar data []byte\n\tvar err error\n\n\tif isDev {\n\t\tdata, err = devManifest(host, webPath)\n\t} else {\n\t\tdata, err = prodManifest(fsPath)\n\t}\n\n\tif err != nil {\n\t\treturn assetList{}, errors.Wrap(err, \"go-webpack: Error reading manifest\")\n\t}\n\n\treturn parseManifest(data)\n}"} {"input": "package awspublicip\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com/dan-v/awslambdaproxy/pkg/server/publicip\"\n\t\"io/ioutil\"\n\t\"net\"\n\t\"net/http\"\n\t\"time\"\n)\n\nconst (\n\tDefaultHTTPTimeout = time.Second * 10\n\tAWSProviderURL = \"http://checkip.amazonaws.com/\"\n)\n\ntype PublicIPClient struct {\n\tproviderURL string\n\thttpClient *http.Client\n}\n\nfunc New() *PublicIPClient {\n\treturn &PublicIPClient{\n\t\tproviderURL: AWSProviderURL,\n\t\thttpClient: &http.Client{\n\t\t\tTimeout: DefaultHTTPTimeout,\n\t\t},\n\t}\n}\n\nfunc (p *PublicIPClient) GetIP() (string, error) {\n\tresp, err := p.httpClient.Get(p.providerURL)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"http request to get ip address from %v failed: %w\", p.providerURL, err)\n\t}\n\tdefer resp.Body.Close()\n\n\tbuf, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"reading response body from %v failed: %w\", p.providerURL, err)\n\t}\n\n\tip := string(bytes.TrimSpace(buf))\n\tif net.ParseIP(ip) == nil {\n\t\treturn \"\", fmt.Errorf(\"unable to parse ip %v: %w\",\n\t\t\tpublicip.ErrInvalidIPAddress, publicip.ErrInvalidIPAddress)\n\t}\n\treturn ip, nil\n}\n\n\n\nfunc (p *PublicIPClient) ProviderURL() string ", "output": "{\n\treturn p.providerURL\n}"} {"input": "package x11\n\nimport (\n\t\"C\"\n\t\"unsafe\"\n\n\t\"github.com/richardwilkes/toolbox/xmath/geom\"\n\t\"github.com/richardwilkes/ui/keys\"\n)\n\ntype CrossingEvent C.XCrossingEvent\n\nfunc (evt *CrossingEvent) Window() Window {\n\treturn Window(evt.window)\n}\n\nfunc (evt *CrossingEvent) Where() geom.Point {\n\treturn geom.Point{X: float64(evt.x), Y: float64(evt.y)}\n}\n\nfunc (evt *CrossingEvent) Modifiers() keys.Modifiers {\n\treturn Modifiers(evt.state)\n}\n\n\n\nfunc (evt *CrossingEvent) ToEvent() *Event ", "output": "{\n\treturn (*Event)(unsafe.Pointer(evt))\n}"} {"input": "package ukvm\n\nimport (\n\t\"github.com/solo-io/unik/pkg/providers/common\"\n\t\"github.com/solo-io/unik/pkg/types\"\n)\n\n\n\nfunc (p *UkvmProvider) GetVolume(nameOrIdPrefix string) (*types.Volume, error) ", "output": "{\n\treturn common.GetVolume(p, nameOrIdPrefix)\n}"} {"input": "package connect\n\nimport (\n\t\"github.com/LilyPad/GoLilyPad/packet/connect\"\n)\n\ntype EventRedirect struct {\n\tServer string\n\tPlayer string\n}\n\n\n\nfunc WrapEventRedirect(packet *connect.PacketRedirectEvent) (this *EventRedirect) ", "output": "{\n\tthis = new(EventRedirect)\n\tthis.Server = packet.Server\n\tthis.Player = packet.Player\n\treturn\n}"} {"input": "func MergeSort(slice []int) []int { \n\tif len(slice) < 2 { \n\t\treturn slice\n\t}\n\tmid := (len(slice)) / 2 \n\treturn Merge(MergeSort(slice[:mid]), MergeSort(slice[mid:]))\n}\n\n\n\nfunc Merge(left, right []int) []int ", "output": "{\n\tsize := len(left)+len(right)\n\ti := 0 \n\tj:= 0\n\tslice := make([]int, size, size)\n\tfor k := 0; k < size; k++ {\n\t\tif i > len(left)-1 && j <= len(right)-1 {\n\t\t\tslice[k] = right[j]\n\t\t\tj++\n\t\t} else if j > len(right)-1 && i <= len(left)-1 {\n\t\t\tslice[k] = left[i]\n\t\t\ti++\n\t\t} else if left[i] < right[j] {\n\t\t\tslice[k] = left[i]\n\t\t\ti++\n\t\t} else {\n\t\t\tslice[k] = right[j]\n\t\t\tj++\n\t\t}\n\t}\n\treturn slice\n}"} {"input": "package dml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/dml\"\n)\n\n\n\nfunc TestCT_ColorMappingOverrideChoiceMarshalUnmarshal(t *testing.T) {\n\tv := dml.NewCT_ColorMappingOverrideChoice()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := dml.NewCT_ColorMappingOverrideChoice()\n\txml.Unmarshal(buf, v2)\n}\n\nfunc TestCT_ColorMappingOverrideChoiceConstructor(t *testing.T) ", "output": "{\n\tv := dml.NewCT_ColorMappingOverrideChoice()\n\tif v == nil {\n\t\tt.Errorf(\"dml.NewCT_ColorMappingOverrideChoice must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed dml.CT_ColorMappingOverrideChoice should validate: %s\", err)\n\t}\n}"} {"input": "package packet_proxy\n\nimport (\n\t\"github.com/bettercap/bettercap/session\"\n)\n\ntype PacketProxy struct {\n\tsession.SessionModule\n}\n\nfunc NewPacketProxy(s *session.Session) *PacketProxy {\n\treturn &PacketProxy{\n\t\tSessionModule: session.NewSessionModule(\"packet.proxy\", s),\n\t}\n}\n\nfunc (mod PacketProxy) Name() string {\n\treturn \"packet.proxy\"\n}\n\nfunc (mod PacketProxy) Description() string {\n\treturn \"Not supported on this OS\"\n}\n\nfunc (mod PacketProxy) Author() string {\n\treturn \"Simone Margaritelli \"\n}\n\nfunc (mod *PacketProxy) Configure() (err error) {\n\treturn session.ErrNotSupported\n}\n\n\n\nfunc (mod *PacketProxy) Stop() error {\n\treturn session.ErrNotSupported\n}\n\nfunc (mod *PacketProxy) Start() error ", "output": "{\n\treturn session.ErrNotSupported\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"k8s.io/klog\"\n)\n\nfunc main() {\n\tinfoLogLine := getEnvOrDie(\"KLOG_INFO_LOG\")\n\twarningLogLine := getEnvOrDie(\"KLOG_WARNING_LOG\")\n\terrorLogLine := getEnvOrDie(\"KLOG_ERROR_LOG\")\n\tfatalLogLine := getEnvOrDie(\"KLOG_FATAL_LOG\")\n\n\tklog.InitFlags(nil)\n\tflag.Parse()\n\tklog.Info(infoLogLine)\n\tklog.Warning(warningLogLine)\n\tklog.Error(errorLogLine)\n\tklog.Flush()\n\tklog.Fatal(fatalLogLine)\n}\n\n\n\nfunc getEnvOrDie(name string) string ", "output": "{\n\tval, ok := os.LookupEnv(name)\n\tif !ok {\n\t\tfmt.Fprintf(os.Stderr, name+\" could not be found in environment\")\n\t\tos.Exit(1)\n\t}\n\treturn val\n}"} {"input": "package expr\n\nimport (\n\t\"github.com/grafana/metrictank/api/models\"\n)\n\ntype FuncUnique struct {\n\tin []GraphiteFunc\n}\n\nfunc NewUnique() GraphiteFunc {\n\treturn &FuncUnique{}\n}\n\n\n\nfunc (s *FuncUnique) Context(context Context) Context {\n\treturn context\n}\n\nfunc (s *FuncUnique) Exec(dataMap DataMap) ([]models.Series, error) {\n\tseries, _, err := consumeFuncs(dataMap, s.in)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tseenNames := make(map[string]bool)\n\tvar uniqueSeries []models.Series\n\tfor _, serie := range series {\n\t\tif _, ok := seenNames[serie.Target]; !ok {\n\t\t\tseenNames[serie.Target] = true\n\t\t\tuniqueSeries = append(uniqueSeries, serie)\n\t\t}\n\t}\n\treturn uniqueSeries, nil\n}\n\nfunc (s *FuncUnique) Signature() ([]Arg, []Arg) ", "output": "{\n\treturn []Arg{\n\t\tArgSeriesLists{val: &s.in}}, []Arg{ArgSeriesList{}}\n}"} {"input": "package fever\n\nimport (\n\t\"net/http\"\n\t\"strconv\"\n\n\t\"github.com/pkg/errors\"\n\t\"github.com/urandom/readeef/content\"\n\t\"github.com/urandom/readeef/content/repo\"\n\t\"github.com/urandom/readeef/log\"\n\t\"github.com/urandom/readeef/pool\"\n)\n\nfunc unreadItemIDs(\n\tr *http.Request,\n\tresp resp,\n\tuser content.User,\n\tservice repo.Service,\n\tlog log.Log,\n) error {\n\tlog.Infoln(\"Fetching unread fever item ids\")\n\n\tids, err := service.ArticleRepo().IDs(user,\n\t\tcontent.UnreadOnly, content.Filters(content.GetUserFilters(user)))\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"getting unread ids\")\n\t}\n\n\tbuf := pool.Buffer.Get()\n\tdefer pool.Buffer.Put(buf)\n\n\tfor i := range ids {\n\t\tif i != 0 {\n\t\t\tbuf.WriteString(\",\")\n\t\t}\n\n\t\tbuf.WriteString(strconv.FormatInt(int64(ids[i]), 10))\n\t}\n\n\tresp[\"unread_item_ids\"] = buf.String()\n\n\treturn nil\n}\n\n\n\nfunc init() {\n\tactions[\"unread_item_ids\"] = unreadItemIDs\n\tactions[\"saved_item_ids\"] = savedItemIDs\n}\n\nfunc savedItemIDs(\n\tr *http.Request,\n\tresp resp,\n\tuser content.User,\n\tservice repo.Service,\n\tlog log.Log,\n) error ", "output": "{\n\tlog.Infoln(\"Fetching saved fever item ids\")\n\n\tids, err := service.ArticleRepo().IDs(user,\n\t\tcontent.FavoriteOnly, content.Filters(content.GetUserFilters(user)))\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"getting unread ids\")\n\t}\n\n\tbuf := pool.Buffer.Get()\n\tdefer pool.Buffer.Put(buf)\n\n\tfor i := range ids {\n\t\tif i != 0 {\n\t\t\tbuf.WriteString(\",\")\n\t\t}\n\n\t\tbuf.WriteString(strconv.FormatInt(int64(ids[i]), 10))\n\t}\n\n\tresp[\"saved_item_ids\"] = buf.String()\n\n\treturn nil\n}"} {"input": "package gutil\n\n\nimport (\n\t\"bufio\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc NewReadForString(str string) *bufio.Reader {\n\treturn bufio.NewReader(strings.NewReader(str))\n}\n\n\nfunc ReadLine(red *bufio.Reader) (string, bool) {\n\tline, _, err := red.ReadLine()\n\tif err != nil {\n\t\treturn \"\", false\n\t}\n\treturn string(line), true\n}\n\n\n\n\nfunc ReadPath(path string) []string ", "output": "{\n\tif file, err := os.Open(path); CheckSucceed(err) {\n\t\tvar strs []string\n\t\tbuff := bufio.NewReader(file)\n\t\tfor {\n\t\t\tif str, ok := ReadLine(buff); ok {\n\t\t\t\tstrs = append(strs, str)\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\treturn strs\n\t}\n\treturn nil\n}"} {"input": "package suggest\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/suggest-go/suggest/pkg/metric\"\n)\n\n\ntype SearchConfig struct {\n\tquery string\n\ttopK int\n\tmetric metric.Metric\n\tsimilarity float64\n}\n\n\n\n\nfunc NewSearchConfig(query string, topK int, metric metric.Metric, similarity float64) (SearchConfig, error) ", "output": "{\n\tif topK <= 0 {\n\t\treturn SearchConfig{}, fmt.Errorf(\"topK should be greater or equal to 1\")\n\t}\n\n\tif similarity <= 0 || similarity > 1 {\n\t\treturn SearchConfig{}, fmt.Errorf(\"similarity shouble be in (0.0, 1.0]\")\n\t}\n\n\treturn SearchConfig{\n\t\tquery: query,\n\t\ttopK: topK,\n\t\tmetric: metric,\n\t\tsimilarity: similarity,\n\t}, nil\n}"} {"input": "package rest\n\nimport \"net/http\"\n\ntype StaticResource struct {\n\tResourceBase\n\tresult *Result\n\tself Link\n}\n\nfunc NewStaticResource(result *Result, self Link) Resource {\n\treturn &StaticResource{\n\t\tresult: result,\n\t\tself: self,\n\t}\n}\n\nfunc StaticContent(content []byte, contentType string, selfHref string) Resource {\n\treturn NewStaticResource(\n\t\tOk().AddHeader(\"Content-Type\", contentType).WithBody(content),\n\t\tSimpleLink(selfHref),\n\t)\n}\n\nfunc (r StaticResource) Get(request *http.Request) (interface{}, error) {\n\treturn r.result, nil\n}\n\n\n\nfunc (r StaticResource) Self() Link ", "output": "{\n\treturn r.self\n}"} {"input": "package processors\n\nimport (\n\t\"github.com/golangci/golangci-lint/pkg/config\"\n\t\"github.com/golangci/golangci-lint/pkg/result\"\n)\n\ntype lineToCount map[int]int\ntype fileToLineToCount map[string]lineToCount\n\ntype UniqByLine struct {\n\tflc fileToLineToCount\n\tcfg *config.Config\n}\n\nfunc NewUniqByLine(cfg *config.Config) *UniqByLine {\n\treturn &UniqByLine{\n\t\tflc: fileToLineToCount{},\n\t\tcfg: cfg,\n\t}\n}\n\nvar _ Processor = &UniqByLine{}\n\nfunc (p UniqByLine) Name() string {\n\treturn \"uniq_by_line\"\n}\n\n\n\nfunc (p UniqByLine) Finish() {}\n\nfunc (p *UniqByLine) Process(issues []result.Issue) ([]result.Issue, error) ", "output": "{\n\tif !p.cfg.Output.UniqByLine {\n\t\treturn issues, nil\n\t}\n\n\treturn filterIssues(issues, func(i *result.Issue) bool {\n\t\tif i.Replacement != nil && p.cfg.Issues.NeedFix {\n\t\t\treturn true\n\t\t}\n\n\t\tlc := p.flc[i.FilePath()]\n\t\tif lc == nil {\n\t\t\tlc = lineToCount{}\n\t\t\tp.flc[i.FilePath()] = lc\n\t\t}\n\n\t\tconst limit = 1\n\t\tcount := lc[i.Line()]\n\t\tif count == limit {\n\t\t\treturn false\n\t\t}\n\n\t\tlc[i.Line()]++\n\t\treturn true\n\t}), nil\n}"} {"input": "package state\n\nimport (\n\t\"net/url\"\n\n\t\"gopkg.in/juju/charm.v3\"\n)\n\n\ntype charmDoc struct {\n\tURL *charm.URL `bson:\"_id\"`\n\tMeta *charm.Meta\n\tConfig *charm.Config\n\tActions *charm.Actions\n\tBundleURL *url.URL\n\tBundleSha256 string\n\tPendingUpload bool\n\tPlaceholder bool\n}\n\n\ntype Charm struct {\n\tst *State\n\tdoc charmDoc\n}\n\nfunc newCharm(st *State, cdoc *charmDoc) (*Charm, error) {\n\treturn &Charm{st: st, doc: *cdoc}, nil\n}\n\nfunc (c *Charm) String() string {\n\treturn c.doc.URL.String()\n}\n\n\nfunc (c *Charm) URL() *charm.URL {\n\tclone := *c.doc.URL\n\treturn &clone\n}\n\n\n\nfunc (c *Charm) Revision() int {\n\treturn c.doc.URL.Revision\n}\n\n\nfunc (c *Charm) Meta() *charm.Meta {\n\treturn c.doc.Meta\n}\n\n\nfunc (c *Charm) Config() *charm.Config {\n\treturn c.doc.Config\n}\n\n\nfunc (c *Charm) Actions() *charm.Actions {\n\treturn c.doc.Actions\n}\n\n\n\n\n\n\nfunc (c *Charm) BundleSha256() string {\n\treturn c.doc.BundleSha256\n}\n\n\n\nfunc (c *Charm) IsUploaded() bool {\n\treturn !c.doc.PendingUpload\n}\n\n\n\nfunc (c *Charm) IsPlaceholder() bool {\n\treturn c.doc.Placeholder\n}\n\nfunc (c *Charm) BundleURL() *url.URL ", "output": "{\n\treturn c.doc.BundleURL\n}"} {"input": "package helpers\n\nimport (\n\t\"os\"\n\t\"strconv\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\n\n\nfunc SkipIfClientCredentialsNotSet() (string, string) {\n\tprivateClientID := os.Getenv(\"CF_INT_CLIENT_ID\")\n\tprivateClientSecret := os.Getenv(\"CF_INT_CLIENT_SECRET\")\n\n\tif privateClientID == \"\" || privateClientSecret == \"\" {\n\t\tSkip(\"CF_INT_CLIENT_ID or CF_INT_CLIENT_SECRET is not set\")\n\t}\n\n\treturn privateClientID, privateClientSecret\n}\n\n\n\nfunc SkipIfCustomClientCredentialsNotSet() (string, string) {\n\tcustomClientID := os.Getenv(\"CF_INT_CUSTOM_CLIENT_ID\")\n\tcustomClientSecret := os.Getenv(\"CF_INT_CUSTOM_CLIENT_SECRET\")\n\n\tif customClientID == \"\" || customClientSecret == \"\" {\n\t\tSkip(\"CF_INT_CUSTOM_CLIENT_ID or CF_INT_CUSTOM_CLIENT_SECRET is not set\")\n\t}\n\n\treturn customClientID, customClientSecret\n}\n\nfunc SkipIfClientCredentialsTestMode() {\n\tif ClientCredentialsTestMode() {\n\t\tSkip(\"CF_INT_CLIENT_CREDENTIALS_TEST_MODE is enabled\")\n\t}\n}\n\n\n\nfunc ClientCredentialsTestMode() bool ", "output": "{\n\tenvVar := os.Getenv(\"CF_INT_CLIENT_CREDENTIALS_TEST_MODE\")\n\n\tif envVar == \"\" {\n\t\treturn false\n\t}\n\n\ttestMode, err := strconv.ParseBool(envVar)\n\tExpect(err).ToNot(HaveOccurred(), \"CF_INT_CLIENT_CREDENTIALS_TEST_MODE should be boolean\")\n\n\treturn testMode\n}"} {"input": "package libproxy\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"time\"\n)\n\n\n\ntype UnixProxy struct {\n\tlistener net.Listener\n\tfrontendAddr net.Addr\n\tbackendAddr *net.UnixAddr\n}\n\n\nfunc NewUnixProxy(listener net.Listener, backendAddr *net.UnixAddr) (*UnixProxy, error) {\n\tlog.Printf(\"NewUnixProxy from %s -> %s\\n\", listener.Addr().String(), backendAddr.String())\n\treturn &UnixProxy{\n\t\tlistener: listener,\n\t\tfrontendAddr: listener.Addr(),\n\t\tbackendAddr: backendAddr,\n\t}, nil\n}\n\n\nfunc HandleUnixConnection(client Conn, backendAddr *net.UnixAddr, quit <-chan struct{}) error {\n\tstart := time.Now()\n\tfor {\n\t\tbackend, err := net.DialUnix(\"unix\", nil, backendAddr)\n\t\tif err != nil {\n\t\t\tif errIsConnectionRefused(err) {\n\t\t\t\tif time.Since(start) > 120*time.Second {\n\t\t\t\t\tlog.Errorf(\"failed to connect to %s after 120s. The server appears to be down.\", backendAddr.String())\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlog.Infof(\"%s appears to not be started yet: will retry in 5s\", backendAddr.String())\n\t\t\t\ttime.Sleep(5 * time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"can't forward traffic to backend unix/%v: %s\", backendAddr, err)\n\t\t}\n\t\treturn ProxyStream(client, backend, quit)\n\t}\n}\n\n\n\n\n\nfunc (proxy *UnixProxy) Close() { proxy.listener.Close() }\n\n\nfunc (proxy *UnixProxy) FrontendAddr() net.Addr { return proxy.frontendAddr }\n\n\nfunc (proxy *UnixProxy) BackendAddr() net.Addr { return proxy.backendAddr }\n\nfunc (proxy *UnixProxy) Run() ", "output": "{\n\tquit := make(chan struct{})\n\tdefer close(quit)\n\tfor {\n\t\tclient, err := proxy.listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Stopping proxy on unix/%v for unix/%v (%s)\", proxy.frontendAddr, proxy.backendAddr, err)\n\t\t\treturn\n\t\t}\n\t\tgo HandleUnixConnection(client.(Conn), proxy.backendAddr, quit)\n\t}\n}"} {"input": "package syscall\n\nconst SizeofSockaddrInet4 = 16\nconst SizeofSockaddrInet6 = 28\nconst SizeofSockaddrUnix = 110\n\ntype RawSockaddrInet4 struct {\n\tLen uint8\n\tFamily uint8\n\tPort uint16\n\tAddr [4]byte \n\tZero [8]uint8\n}\n\nfunc (sa *RawSockaddrInet4) setLen() Socklen_t {\n\tsa.Len = SizeofSockaddrInet4\n\treturn SizeofSockaddrInet4\n}\n\ntype RawSockaddrInet6 struct {\n\tLen uint8\n\tFamily uint8\n\tPort uint16\n\tFlowinfo uint32\n\tAddr [16]byte \n\tScope_id uint32\n}\n\nfunc (sa *RawSockaddrInet6) setLen() Socklen_t {\n\tsa.Len = SizeofSockaddrInet6\n\treturn SizeofSockaddrInet6\n}\n\ntype RawSockaddrUnix struct {\n\tLen uint8\n\tFamily uint8\n\tPath [108]int8\n}\n\nfunc (sa *RawSockaddrUnix) setLen(n int) {\n\tsa.Len = uint8(3 + n) \n}\n\n\n\nfunc (sa *RawSockaddrUnix) adjustAbstract(sl Socklen_t) Socklen_t {\n\treturn sl\n}\n\ntype RawSockaddr struct {\n\tLen uint8\n\tFamily uint8\n\tData [14]int8\n}\n\n\nfunc BindToDevice(fd int, device string) (err error) {\n\treturn ENOSYS\n}\n\nfunc anyToSockaddrOS(rsa *RawSockaddrAny) (Sockaddr, error) {\n\treturn nil, EAFNOSUPPORT\n}\n\nfunc (sa *RawSockaddrUnix) getLen() (int, error) ", "output": "{\n\tif sa.Len < 3 || sa.Len > SizeofSockaddrUnix {\n\t\treturn 0, EINVAL\n\t}\n\tn := int(sa.Len) - 3 \n\tfor i := 0; i < n; i++ {\n\t\tif sa.Path[i] == 0 {\n\t\t\tn = i\n\t\t\tbreak\n\t\t}\n\t}\n\treturn n, nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n)\n\n\n\nfunc main() {\n\thttp.HandleFunc(\"/\", sayHelloName)\n\terr := http.ListenAndServe(\":9090\", nil)\n\tif err != nil {\n\t\tlog.Fatal(\"ListenAndServe:\", err)\n\t}\n}\n\nfunc sayHelloName(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tr.ParseForm()\n\tfmt.Println(r.Form)\n\tfmt.Println(\"path:\", r.URL.Path)\n\tfmt.Println(\"scheme:\", r.URL.Scheme)\n\tfmt.Println(r.Form[\"url_long\"])\n\tfor k, v := range r.Form {\n\t\tfmt.Println(\"key:\", k, \", value:\", strings.Join(v, \"\"))\n\t}\n\tfmt.Fprintf(w, \"Hello astaxie!\")\n}"} {"input": "package osutil\n\nimport (\n\t\"syscall\"\n\t\"time\"\n)\n\nfunc init() {\n\ttimeToTimeval = timeToTimeval32\n}\n\n\n\nfunc timeToTimeval32(t time.Time) *syscall.Timeval ", "output": "{\n\treturn &syscall.Timeval{\n\t\tSec: int32(t.Unix()),\n\t\tUsec: int32(t.Nanosecond() / 1000),\n\t}\n}"} {"input": "package server\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/tangfeixiong/go-to-docker/pb\"\n\t\"github.com/tangfeixiong/go-to-openstack-bootcamp/kopos/kopit/pkg/gopacketctl\"\n)\n\n\n\nfunc (m *myService) sniffEtherNetworking(req *pb.EthernetSniffingData) (*pb.EthernetSniffingData, error) ", "output": "{\n\tresp := new(pb.EthernetSniffingData)\n\n\tif nil == req || \"\" == req.Iface {\n\t\tresp.StateCode = 10\n\t\tresp.StateMessage = \"Request required\"\n\t\treturn resp, fmt.Errorf(\"Request required\")\n\t}\n\n\tcontent, err := gopacketctl.PcapdumpOnce(req.Iface, time.Second*3)\n\tif nil != err {\n\t\tresp.StateCode = 100\n\t\tresp.StateMessage = err.Error()\n\t\treturn resp, err\n\t}\n\tresp.StatsAndPackets = content\n\treturn resp, err\n}"} {"input": "package models\n\n\ntype StockInfoSearchResponse struct {\n Results []StockInfo `json:\"results\"`\n}\n\n\n\nfunc (r StockInfoSearchResponse) String() string ", "output": "{\n retVal := \"\"\n for index,element := range r.Results {\n if index > 0 {\n retVal = retVal + \", \" + element.String()\n } else {\n retVal = element.String()\n }\n }\n return retVal\n}"} {"input": "package vcl\n\n\n\n\nimport (\n\t. \"github.com/ying32/govcl/vcl/api\"\n\t. \"github.com/ying32/govcl/vcl/types\"\n)\n\ntype (\n\tNSObject uintptr\n\n\tNSWindow uintptr\n\n\tNSURL uintptr\n)\n\n\nfunc HandleToPlatformHandle(h HWND) NSObject {\n\treturn NSObject(h)\n}\n\nfunc (f *TForm) PlatformWindow() NSWindow {\n\tr, _, _ := NSWindow_FromForm.Call(f.instance)\n\treturn NSWindow(r)\n}\n\nfunc (n NSWindow) TitleVisibility() NSWindowTitleVisibility {\n\tr, _, _ := NSWindow_titleVisibility.Call(uintptr(n))\n\treturn NSWindowTitleVisibility(r)\n}\n\nfunc (n NSWindow) SetTitleVisibility(flag NSWindowTitleVisibility) {\n\tNSWindow_setTitleVisibility.Call(uintptr(n), uintptr(flag))\n}\n\nfunc (n NSWindow) TitleBarAppearsTransparent() bool {\n\tr, _, _ := NSWindow_titlebarAppearsTransparent.Call(uintptr(n))\n\treturn DBoolToGoBool(r)\n}\n\n\n\nfunc (n NSWindow) SetRepresentedURL(url NSURL) {\n\tNSWindow_setRepresentedURL.Call(uintptr(n), uintptr(url))\n}\n\nfunc (n NSWindow) StyleMask() uint {\n\tr, _, _ := NSWindow_styleMask.Call(uintptr(n))\n\treturn uint(r)\n}\n\nfunc (n NSWindow) SetStyleMask(mask uint) {\n\tNSWindow_setStyleMask.Call(uintptr(n), uintptr(mask))\n}\n\nfunc (n NSWindow) SetTitleBarAppearsTransparent(flag bool) ", "output": "{\n\tNSWindow_setTitlebarAppearsTransparent.Call(uintptr(n), GoBoolToDBool(flag))\n}"} {"input": "package godspeed\n\nimport (\n\t\"io\"\n\t\"net/http\"\n)\n\ntype bodyWrapperFactory func(http.ResponseWriter) io.Writer\n\ntype bodyWrapper struct {\n\trespw http.ResponseWriter\n\tw io.Writer\n\tposthandler bodyWrapperFactory\n}\n\nfunc (w *bodyWrapper) Header() http.Header {\n\treturn w.respw.Header()\n}\n\nfunc (w *bodyWrapper) Write(data []byte) (int, error) {\n\tif w.w == nil {\n\t\tw.w = w.posthandler(w.respw)\n\t}\n\treturn w.w.Write(data)\n}\n\nfunc (w *bodyWrapper) WriteHeader(s int) {\n\tw.respw.WriteHeader(s)\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc wrapBody(respw http.ResponseWriter, writerGen bodyWrapperFactory) *bodyWrapper {\n\treturn &bodyWrapper{\n\t\trespw: respw,\n\t\tposthandler: writerGen,\n\t}\n}\n\nfunc (w *bodyWrapper) Close() error ", "output": "{\n\tvar err error\n\tif c, ok := w.w.(io.Closer); ok {\n\t\terr = c.Close()\n\t}\n\treturn err\n}"} {"input": "package cluster\n\nimport (\n\t\"net\"\n\n\t\"github.com/hashicorp/memberlist\"\n)\n\ntype Node struct {\n\tAddr string\n}\n\ntype Discovery interface {\n\tDiscover(addr ...string) (RemoteCluster, error)\n}\n\ntype RemoteCluster interface {\n\tMembers() []Node\n\tJoin(cb func(ip string) (net.Addr, error)) (Cluster, error)\n}\n\ntype Cluster interface {\n\tSelf() Node\n\tMembers() []Node\n\tLeave() error\n}\n\ntype gossipDiscovery struct {\n}\n\nfunc (gd *gossipDiscovery) Discover(addrs ...string) (RemoteCluster, error) {\n\tcfg := memberlist.DefaultLANConfig()\n\tlist, err := memberlist.Create(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = list.Join(addrs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &gossipCluster{list: list}, nil\n}\n\ntype gossipCluster struct {\n\tlist *memberlist.Memberlist\n}\n\nfunc (gd *gossipCluster) Members() []Node {\n\n\n\n\treturn nil\n}\n\n\n\nfunc (gd *gossipCluster) Join(cb func(ip string) (net.Addr, error)) (Cluster, error) ", "output": "{\n\taddr, err := cb(gd.list.LocalNode().Addr.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_ = addr\n\n\treturn nil, nil\n}"} {"input": "package crypto\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\nfunc BenchmarkRandom(b *testing.B) {\n\tfor index := 0; index < b.N; index++ {\n\t\tRandom(32)\n\t}\n}\n\nfunc TestEncrypt(t *testing.T) {\n\tsrc := \"I'mAPlainSecret\"\n\tos.Setenv(\"SECRET_KEY\", \"secretkey@example.com\")\n\tConvey(\"auth.Encrypt Test\", t, func() {\n\t\tsecret := Encrypt(src)\n\t\tSo(len(secret), ShouldEqual, 60)\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t})\n}\n\n\n\nfunc BenchmarkMixin(b *testing.B) {\n\tsrc := \"I'mAPlainSecret\"\n\tos.Setenv(\"SECRET_KEY\", \"secretkey@example.com\")\n\tfor index := 0; index < b.N; index++ {\n\t\tmixin(src)\n\t}\n}\n\nfunc BenchmarkEncrypt(b *testing.B) {\n\tsrc := \"I'mAPlainSecret\"\n\tos.Setenv(\"SECRET_KEY\", \"secretkey@example.com\")\n\tfor index := 0; index < b.N; index++ {\n\t\tEncrypt(src)\n\t}\n}\n\nfunc BenchmarkVerify(b *testing.B) {\n\tsrc := \"I'mAPlainSecret\"\n\tos.Setenv(\"SECRET_KEY\", \"secretkey@example.com\")\n\tsecret := Encrypt(src)\n\tfor index := 0; index < b.N; index++ {\n\t\tVerify(src, secret)\n\t}\n}\n\nfunc TestVerify(t *testing.T) ", "output": "{\n\tsrc := \"I'mAPlainSecret\"\n\tConvey(\"auth.Verify Test\", t, func() {\n\t\tfor index := 0; index < 10; index++ {\n\t\t\tsecret := Encrypt(src)\n\t\t\tSo(Verify(src, secret), ShouldBeTrue)\n\t\t}\n\t})\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"time\"\n)\n\n\nvar TopicCache = make([]*Topic, 0, 16)\n\ntype Topic struct {\n\tId int `json:\"id\"`\n\tTitle string `json:\"title\"`\n\tContent string `json:\"content\"`\n\tCreatedAt time.Time `json:\"created_at\"`\n}\n\nfunc FindTopic(id int) (*Topic, error) {\n\tif err := checkIndex(id); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn TopicCache[id-1], nil\n}\n\nfunc (t *Topic) Create() error {\n\tt.Id = len(TopicCache) + 1\n\tt.CreatedAt = time.Now()\n\tTopicCache = append(TopicCache, t)\n\treturn nil\n}\n\nfunc (t *Topic) Update() error {\n\tif err := checkIndex(t.Id); err != nil {\n\t\treturn err\n\t}\n\tTopicCache[t.Id-1] = t\n\treturn nil\n}\n\n\n\n\nfunc checkIndex(id int) error {\n\tif id > 0 && len(TopicCache) <= id-1 {\n\t\treturn errors.New(\"The topic is not exists!\")\n\t}\n\n\treturn nil\n}\n\nfunc (t *Topic) Delete() error ", "output": "{\n\tif err := checkIndex(t.Id); err != nil {\n\t\treturn err\n\t}\n\tTopicCache[t.Id-1] = nil\n\treturn nil\n}"} {"input": "package http\n\nimport (\n\t\"fmt\"\n\t\"github.com/denniscollective/dragonfly.go/dragonfly\"\n\t\"github.com/gorilla/handlers\"\n\t\"github.com/gorilla/mux\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n)\n\nfunc StartServer() error {\n\tr := mux.NewRouter()\n\tr.HandleFunc(\"/favicon.ico\", hollar)\n\tr.HandleFunc(\"/{b64JobString}\", serveFile)\n\n\terr := http.ListenAndServe(\":2345\", handle(r))\n\treturn err\n}\n\ntype benchmarkHandler struct {\n\thandler http.Handler\n}\n\nfunc (h benchmarkHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tt := time.Now()\n\th.handler.ServeHTTP(w, req)\n\tfmt.Println(time.Now().Sub(t))\n}\n\nfunc handle(h http.Handler) http.Handler {\n\n\treturn benchmarkHandler{handlers.CombinedLoggingHandler(os.Stdout, h)}\n\n}\n\n\n\nfunc serveFile(response http.ResponseWriter, request *http.Request) {\n\tresponse.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\n\tvars := mux.Vars(request)\n\tjobStr := vars[\"b64JobString\"]\n\tfile, err := dragonfly.ImageFor(jobStr)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tdata, _ := ioutil.ReadAll(file)\n\tresponse.Write(data)\n}\n\nfunc hollar(response http.ResponseWriter, r *http.Request) ", "output": "{\n\tfmt.Println(\"hollar\")\n}"} {"input": "package config\n\nimport (\n\t\"io/ioutil\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\n\n\n\nfunc TestDumpConfig(t *testing.T) ", "output": "{\n\tbs, err := GetExampleConfigFileBytes()\n\tassert.NoError(t, err, \"Should be able to create example config\")\n\tioutil.WriteFile(\"config_dump.toml\", bs, 0644)\n}"} {"input": "package lib\n\nimport (\n\t\"strings\"\n\n\tcvmfsUtil \"github.com/cvmfs/docker-graphdriver/plugins/util\"\n)\n\n\n\n\n\n\n\n\nfunc MakeThinImage(m Manifest, repoLocation string, origin string) cvmfsUtil.ThinImage ", "output": "{\n\tlayers := make([]cvmfsUtil.ThinImageLayer, len(m.Layers))\n\n\turl_base := \"cvmfs://\" + repoLocation\n\tfor i, l := range m.Layers {\n\t\td := strings.Split(l.Digest, \":\")[1]\n\t\turl := url_base + \"/\" + d\n\t\tlayers[i] = cvmfsUtil.ThinImageLayer{Digest: d, Url: url}\n\t}\n\n\treturn cvmfsUtil.ThinImage{Layers: layers,\n\t\tOrigin: origin,\n\t\tVersion: thinImageVersion}\n}"} {"input": "package mountinfo\n\nimport \"strings\"\n\n\n\n\n\n\n\n\n\n\n\ntype FilterFunc func(*Info) (skip, stop bool)\n\n\n\n\n\n\n\n\nfunc PrefixFilter(prefix string) FilterFunc {\n\treturn func(m *Info) (bool, bool) {\n\t\tskip := !strings.HasPrefix(m.Mountpoint+\"/\", prefix+\"/\")\n\t\treturn skip, false\n\t}\n}\n\n\nfunc SingleEntryFilter(mp string) FilterFunc {\n\treturn func(m *Info) (bool, bool) {\n\t\tif m.Mountpoint == mp {\n\t\t\treturn false, true \n\t\t}\n\t\treturn true, false \n\t}\n}\n\n\n\n\n\n\nfunc ParentsFilter(path string) FilterFunc {\n\treturn func(m *Info) (bool, bool) {\n\t\tskip := !strings.HasPrefix(path, m.Mountpoint)\n\t\treturn skip, false\n\t}\n}\n\n\n\n\nfunc FSTypeFilter(fstype ...string) FilterFunc ", "output": "{\n\treturn func(m *Info) (bool, bool) {\n\t\tfor _, t := range fstype {\n\t\t\tif m.FSType == t {\n\t\t\t\treturn false, false \n\t\t\t}\n\t\t}\n\t\treturn true, false \n\t}\n}"} {"input": "package stripe\n\nimport \"encoding/json\"\n\n\ntype Application struct {\n\tID string `json:\"id\"`\n\tName string `json:\"name\"`\n}\n\n\n\n\n\n\nfunc (a *Application) UnmarshalJSON(data []byte) error ", "output": "{\n\tif id, ok := ParseID(data); ok {\n\t\ta.ID = id\n\t\treturn nil\n\t}\n\n\ttype application Application\n\tvar v application\n\tif err := json.Unmarshal(data, &v); err != nil {\n\t\treturn err\n\t}\n\n\t*a = Application(v)\n\treturn nil\n}"} {"input": "package nntptest\n\nimport \"bytes\"\n\n\n\ntype ResponseRecorder struct {\n\tCode int\n\tBody *bytes.Buffer\n\twroteHeader bool\n}\n\n\n\n\n\nfunc (rw *ResponseRecorder) Write(buf []byte) (int, error) {\n\tif !rw.wroteHeader {\n\t\trw.WriteHeader(403)\n\t\treturn 0, nil\n\t}\n\tif rw.Body != nil {\n\t\trw.Body.Write(buf)\n\t}\n\treturn len(buf), nil\n}\n\n\nfunc (rw *ResponseRecorder) WriteHeader(code int) {\n\tif !rw.wroteHeader {\n\t\trw.Code = code\n\t}\n\trw.wroteHeader = true\n}\n\nfunc NewRecorder() *ResponseRecorder ", "output": "{\n\treturn &ResponseRecorder{\n\t\tBody: new(bytes.Buffer),\n\t\tCode: 403,\n\t}\n}"} {"input": "package keys\n\nimport \"context\"\n\n\ntype keySetType int\n\n\nconst keySet = keySetType(0)\n\n\nfunc Get(ctx context.Context) []interface{} {\n\tseen := map[interface{}]bool{}\n\tresult := make([]interface{}, 0, 10)\n\tfor link, _ := ctx.Value(keySet).(*Link); link != nil; link = link.Next {\n\t\tif !seen[link.Value] {\n\t\t\tseen[link.Value] = true\n\t\t\tresult = append(result, link.Value)\n\t\t}\n\t}\n\treturn result\n}\n\n\nfunc WithValue(ctx context.Context, key interface{}, value interface{}) context.Context {\n\told, _ := ctx.Value(keySet).(*Link)\n\tctx = context.WithValue(ctx, key, value)\n\treturn context.WithValue(ctx, keySet, &Link{Value: key, Next: old})\n}\n\n\n\n\n\nfunc Clone(ctx context.Context, from context.Context) context.Context ", "output": "{\n\tfor _, key := range Get(from) {\n\t\tctx = WithValue(ctx, key, from.Value(key))\n\t}\n\treturn ctx\n}"} {"input": "package mock_test\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/pingcap/check\"\n\t\"github.com/pingcap/tidb/br/pkg/mock\"\n\t\"github.com/pingcap/tidb/util/testleak\"\n)\n\nfunc Test(t *testing.T) {\n\tTestingT(t)\n}\n\nvar _ = Suite(&testClusterSuite{})\n\ntype testClusterSuite struct {\n\tmock *mock.Cluster\n}\n\nfunc (s *testClusterSuite) SetUpSuite(c *C) {\n\tvar err error\n\ts.mock, err = mock.NewCluster()\n\tc.Assert(err, IsNil)\n}\n\n\n\nfunc (s *testClusterSuite) TestSmoke(c *C) {\n\tc.Assert(s.mock.Start(), IsNil)\n\ts.mock.Stop()\n}\n\nfunc (s *testClusterSuite) TearDownSuite(c *C) ", "output": "{\n\ttestleak.AfterTest(c)()\n}"} {"input": "package tracing\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/gotgo/fw/logging\"\n)\n\ntype Receiver struct {\n\tReceiverName string\n\tWriter TraceMessageWriter\n\tLog logging.Logger `inject:\"\"`\n}\n\nfunc (ft *Receiver) Name() string {\n\treturn ft.ReceiverName\n}\n\n\n\nfunc (ft *Receiver) Close() {\n\tif err := ft.Writer.Close(); err != nil {\n\t\tft.Log.Error(\"failed to close trace writer\", err)\n\t}\n}\n\nfunc (ft *Receiver) Receive(m *TraceMessage) ", "output": "{\n\tif bytes, err := json.MarshalIndent(m, \"\", \"\\t\"); err != nil {\n\t\tft.Log.MarshalFail(\"trace receive\", m, err)\n\t} else if _, err := ft.Writer.Write(bytes); err != nil {\n\t\tft.Log.Error(\"failed to write to receiver\", err)\n\t}\n}"} {"input": "package utils\n\nimport (\n\t\"github.com/goincremental/negroni-sessions\"\n\t\"net/http\"\n)\n\ntype SessionManager interface {\n\tGet(*http.Request, string) string\n\tSet(*http.Request, string, string)\n\tDelete(*http.Request, string)\n}\n\ntype SessionManagerImpl struct {\n}\n\nfunc NewSessionManager() *SessionManagerImpl {\n\treturn &SessionManagerImpl{}\n}\n\n\n\nfunc (sa *SessionManagerImpl) Set(req *http.Request, key, value string) {\n\tsessions.GetSession(req).Set(key, value)\n}\n\nfunc (sa *SessionManagerImpl) Delete(req *http.Request, key string) {\n\tsessions.GetSession(req).Delete(key)\n}\n\nfunc (sa *SessionManagerImpl) Get(req *http.Request, key string) string ", "output": "{\n\tif val := sessions.GetSession(req).Get(key); val != nil {\n\t\treturn val.(string)\n\t}\n\n\treturn \"\"\n}"} {"input": "package cache\n\nimport (\n\t\"context\"\n\n\t\"github.com/go-kit/log\"\n\t\"github.com/go-kit/log/level\"\n\n\tutil_log \"github.com/grafana/loki/pkg/util/log\"\n)\n\n\ntype RedisCache struct {\n\tname string\n\tredis *RedisClient\n\tlogger log.Logger\n}\n\n\n\n\n\nfunc (c *RedisCache) Fetch(ctx context.Context, keys []string) (found []string, bufs [][]byte, missed []string, err error) {\n\tdata, err := c.redis.MGet(ctx, keys)\n\tif err != nil {\n\t\tlevel.Error(c.logger).Log(\"msg\", \"failed to get from redis\", \"name\", c.name, \"err\", err)\n\t\tmissed = make([]string, len(keys))\n\t\tcopy(missed, keys)\n\t\treturn\n\t}\n\tfor i, key := range keys {\n\t\tif data[i] != nil {\n\t\t\tfound = append(found, key)\n\t\t\tbufs = append(bufs, data[i])\n\t\t} else {\n\t\t\tmissed = append(missed, key)\n\t\t}\n\t}\n\treturn\n}\n\n\nfunc (c *RedisCache) Store(ctx context.Context, keys []string, bufs [][]byte) error {\n\terr := c.redis.MSet(ctx, keys, bufs)\n\tif err != nil {\n\t\tlevel.Error(c.logger).Log(\"msg\", \"failed to put to redis\", \"name\", c.name, \"err\", err)\n\t}\n\treturn err\n}\n\n\nfunc (c *RedisCache) Stop() {\n\t_ = c.redis.Close()\n}\n\nfunc NewRedisCache(name string, redisClient *RedisClient, logger log.Logger) *RedisCache ", "output": "{\n\tutil_log.WarnExperimentalUse(\"Redis cache\", logger)\n\tcache := &RedisCache{\n\t\tname: name,\n\t\tredis: redisClient,\n\t\tlogger: logger,\n\t}\n\tif err := cache.redis.Ping(context.Background()); err != nil {\n\t\tlevel.Error(logger).Log(\"msg\", \"error connecting to redis\", \"name\", name, \"err\", err)\n\t}\n\treturn cache\n}"} {"input": "package nagiosplugin\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestCheck(t *testing.T) {\n\trand.Seed(time.Now().UTC().UnixNano())\n\tc := NewCheck()\n\texpected := \"CRITICAL: 200000 terrifying space monkeys in the engineroom | space_monkeys=200000c;10000;100000;0;4294967296\"\n\tnSpaceMonkeys := float64(200000)\n\tmaxSpaceMonkeys := float64(1 << 32)\n\tc.AddPerfDatum(\"space_monkeys\", \"c\", nSpaceMonkeys, 0, maxSpaceMonkeys, 10000, 100000)\n\tc.AddResult(CRITICAL, fmt.Sprintf(\"%v terrifying space monkeys in the engineroom\", nSpaceMonkeys))\n\tc.AddResult(WARNING, fmt.Sprintf(\"%v slightly annoying space monkeys in the engineroom\", nSpaceMonkeys))\n\tresult := c.String()\n\tif expected != result {\n\t\tt.Errorf(\"Expected check output %v, got check output %v\", expected, result)\n\t}\n}\n\n\n\nfunc TestOUWCStatusPolicy(t *testing.T) {\n\tc := NewCheckWithOptions(CheckOptions{\n\t\tStatusPolicy: NewOUWCStatusPolicy(),\n\t})\n\tc.AddResult(WARNING, \"Isolated-frame flux emission outside threshold\")\n\tc.AddResult(UNKNOWN, \"No response from betaform amplifier\")\n\n\texpected := \"WARNING\"\n\tactual := strings.SplitN(c.String(), \":\", 2)[0]\n\tif actual != expected {\n\t\tt.Errorf(\"Expected %v status, got %v\", expected, actual)\n\t}\n}\n\nfunc TestDefaultStatusPolicy(t *testing.T) ", "output": "{\n\tc := NewCheck()\n\tc.AddResult(WARNING, \"Isolated-frame flux emission outside threshold\")\n\tc.AddResult(UNKNOWN, \"No response from betaform amplifier\")\n\n\texpected := \"UNKNOWN\"\n\tactual := strings.SplitN(c.String(), \":\", 2)[0]\n\tif actual != expected {\n\t\tt.Errorf(\"Expected %v status, got %v\", expected, actual)\n\t}\n}"} {"input": "package cmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/viper\"\n\n\t\"github.com/Huawei/containerops/common\"\n)\n\nvar cfgFile string\nvar verbose, timestamp bool\n\n\nvar RootCmd = &cobra.Command{\n\tUse: \"singular\",\n\tShort: \"Singular is deploy and operation tools for ContainerOps platform.\",\n\tLong: `Singular design for deploy and operation ContainerOps platform,\nmostly focus on Kubernetes, Prometheus, others in the Cloud Native technology stack.\nWe are trying to deploy stack cross cloud, OpenStack, bare metals. `,\n}\n\n\n\n\n\nfunc initConfig() {\n\tif err := common.SetConfig(cfgFile); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc init() ", "output": "{\n\tcobra.OnInitialize(initConfig)\n\n\tRootCmd.PersistentFlags().StringVar(&cfgFile, \"config\", \"\", \"Configuration file path\")\n\tRootCmd.PersistentFlags().BoolVar(&verbose, \"verbose\", false, \"When verbose is true, the engine will print all logs.\")\n\tRootCmd.PersistentFlags().BoolVar(×tamp, \"timestamp\", false, \"Show logs with timestamp. \")\n\n\tviper.BindPFlag(\"config\", RootCmd.Flags().Lookup(\"config\"))\n\tviper.BindPFlag(\"verbose\", RootCmd.Flags().Lookup(\"verbose\"))\n\tviper.BindPFlag(\"timestamp\", RootCmd.Flags().Lookup(\"timestamp\"))\n}"} {"input": "package model\n\nimport (\n\t\"fmt\"\n\tnative_time \"time\"\n)\n\n\n\n\n\n\n\n\ntype Timestamp int64\n\nconst (\n\tMinimumTick = native_time.Second\n\tsecond = int64(native_time.Second / MinimumTick)\n)\n\n\nfunc (t Timestamp) Equal(o Timestamp) bool {\n\treturn t == o\n}\n\n\nfunc (t Timestamp) Before(o Timestamp) bool {\n\treturn t < o\n}\n\n\n\n\n\nfunc (t Timestamp) Add(d native_time.Duration) Timestamp {\n\treturn t + Timestamp(d/MinimumTick)\n}\n\n\nfunc (t Timestamp) Sub(o Timestamp) native_time.Duration {\n\treturn native_time.Duration(t-o) * MinimumTick\n}\n\n\nfunc (t Timestamp) Time() native_time.Time {\n\treturn native_time.Unix(int64(t)/second, (int64(t) % second))\n}\n\n\n\nfunc (t Timestamp) Unix() int64 {\n\treturn int64(t) / second\n}\n\n\nfunc (t Timestamp) String() string {\n\treturn fmt.Sprint(int64(t))\n}\n\n\nfunc Now() Timestamp {\n\treturn TimestampFromTime(native_time.Now())\n}\n\n\nfunc TimestampFromTime(t native_time.Time) Timestamp {\n\treturn TimestampFromUnix(t.Unix())\n}\n\n\nfunc TimestampFromUnix(t int64) Timestamp {\n\treturn Timestamp(t * second)\n}\n\nfunc (t Timestamp) After(o Timestamp) bool ", "output": "{\n\treturn t > o\n}"} {"input": "package kintone\n\nimport (\n\t\"encoding/json\"\n)\n\n\ntype Cursor struct {\n\tId string `json:\"id\"`\n\tTotalCount string `json:\"totalCount\"`\n}\ntype GetRecordsCursorResponse struct {\n\tRecords []*Record `json:\"records\"`\n\tNext bool `json:\"next\"`\n}\n\n\n\nfunc DecodeGetRecordsCursorResponse(b []byte) (rc *GetRecordsCursorResponse, err error) {\n\tvar t struct {\n\t\tNext bool `json:\"next\"`\n\t}\n\terr = json.Unmarshal(b, &t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlistRecord, err := DecodeRecords(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgetRecordsCursorResponse := &GetRecordsCursorResponse{Records: listRecord, Next: t.Next}\n\treturn getRecordsCursorResponse, nil\n}\n\nfunc decodeCursor(b []byte) (c *Cursor, err error) ", "output": "{\n\terr = json.Unmarshal(b, &c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c, nil\n}"} {"input": "package lease\n\n\n\ntype block struct {\n\tleaseName string\n\tunblock chan struct{}\n\tabort <-chan struct{}\n}\n\n\n\n\n\n\n\ntype blocks map[string][]chan struct{}\n\n\nfunc (b blocks) add(block block) {\n\tb[block.leaseName] = append(b[block.leaseName], block.unblock)\n}\n\n\n\nfunc (b blocks) unblock(leaseName string) {\n\tunblocks := b[leaseName]\n\tdelete(b, leaseName)\n\tfor _, unblock := range unblocks {\n\t\tclose(unblock)\n\t}\n}\n\nfunc (b block) invoke(ch chan<- block) error ", "output": "{\n\tfor {\n\t\tselect {\n\t\tcase <-b.abort:\n\t\t\treturn errStopped\n\t\tcase ch <- b:\n\t\t\tch = nil\n\t\tcase <-b.unblock:\n\t\t\treturn nil\n\t\t}\n\t}\n}"} {"input": "package v1\n\nimport (\n\tv1 \"k8s.io/api/networking/v1\"\n\t\"k8s.io/client-go/deprecated/scheme\"\n\trest \"k8s.io/client-go/rest\"\n)\n\ntype NetworkingV1Interface interface {\n\tRESTClient() rest.Interface\n\tNetworkPoliciesGetter\n}\n\n\ntype NetworkingV1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *NetworkingV1Client) NetworkPolicies(namespace string) NetworkPolicyInterface {\n\treturn newNetworkPolicies(c, namespace)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*NetworkingV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &NetworkingV1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *NetworkingV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *NetworkingV1Client {\n\treturn &NetworkingV1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\n\n\nfunc (c *NetworkingV1Client) RESTClient() rest.Interface ", "output": "{\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}"} {"input": "package envstruct_test\n\ntype mockUnmarshaller struct {\n\tUnmarshalEnvCalled chan bool\n\tUnmarshalEnvInput struct {\n\t\tV chan string\n\t}\n\tUnmarshalEnvOutput struct {\n\t\tRet0 chan error\n\t}\n}\n\n\nfunc (m *mockUnmarshaller) UnmarshalEnv(v string) error {\n\tm.UnmarshalEnvCalled <- true\n\tm.UnmarshalEnvInput.V <- v\n\treturn <-m.UnmarshalEnvOutput.Ret0\n}\n\nfunc newMockUnmarshaller() *mockUnmarshaller ", "output": "{\n\tm := &mockUnmarshaller{}\n\tm.UnmarshalEnvCalled = make(chan bool, 100)\n\tm.UnmarshalEnvInput.V = make(chan string, 100)\n\tm.UnmarshalEnvOutput.Ret0 = make(chan error, 100)\n\treturn m\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/gogo/protobuf/proto\"\n\tpeer \"github.com/libp2p/go-libp2p-core/peer\"\n\tpubsub \"github.com/libp2p/go-libp2p-pubsub\"\n)\n\nvar handles = map[string]string{}\n\nconst pubsubTopic = \"/libp2p/example/chat/1.0.0\"\n\n\n\nfunc pubsubUpdateHandler(id peer.ID, msg *UpdatePeer) {\n\toldHandle, ok := handles[id.String()]\n\tif !ok {\n\t\toldHandle = id.ShortString()\n\t}\n\thandles[id.String()] = string(msg.UserHandle)\n\tfmt.Printf(\"%s -> %s\\n\", oldHandle, msg.UserHandle)\n}\n\nfunc pubsubHandler(ctx context.Context, sub *pubsub.Subscription) {\n\tdefer sub.Cancel()\n\tfor {\n\t\tmsg, err := sub.Next(ctx)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tcontinue\n\t\t}\n\n\t\treq := &Request{}\n\t\terr = proto.Unmarshal(msg.Data, req)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch *req.Type {\n\t\tcase Request_SEND_MESSAGE:\n\t\t\tpubsubMessageHandler(msg.GetFrom(), req.SendMessage)\n\t\tcase Request_UPDATE_PEER:\n\t\t\tpubsubUpdateHandler(msg.GetFrom(), req.UpdatePeer)\n\t\t}\n\t}\n}\n\nfunc pubsubMessageHandler(id peer.ID, msg *SendMessage) ", "output": "{\n\thandle, ok := handles[id.String()]\n\tif !ok {\n\t\thandle = id.ShortString()\n\t}\n\tfmt.Printf(\"%s: %s\\n\", handle, msg.Data)\n}"} {"input": "package realtime\n\nimport (\n\t\"io\"\n)\n\n\n\ntype Reader interface {\n\tio.Reader\n\trealtime()\n}\n\n\n\n\nfunc NewReader(input io.Reader, rthandler func(Message)) Reader {\n\tif rthandler == nil {\n\t\treturn &discardReader{input}\n\t}\n\treturn &reader{input, rthandler}\n}\n\nfunc (r *reader) Read(target []byte) (n int, err error) {\n\tvar bf = make([]byte, 1)\n\n\tfor {\n\t\tif n == len(target) {\n\t\t\treturn\n\n\t\t}\n\n\t\t_, err = r.input.Read(bf)\n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif bf[0] < 0xF8 {\n\t\t\ttarget[n] = bf[0]\n\t\t\tn++\n\t\t\tcontinue\n\t\t}\n\n\t\tif m := dispatch(bf[0]); m != nil {\n\t\t\tr.handler(m)\n\t\t}\n\t}\n}\n\n\n\n\n\ntype reader struct {\n\tinput io.Reader\n\thandler func(Message)\n}\n\nfunc (r *reader) realtime() {}\n\n\ntype discardReader struct {\n\tinput io.Reader\n}\n\nfunc (r *discardReader) realtime() {}\n\n\n\nfunc dispatch(b byte) Message {\n\tm := msg(b)\n\tif _, has := msg2String[m]; !has {\n\t\treturn nil\n\t}\n\treturn m\n}\n\nfunc (r *discardReader) Read(target []byte) (n int, err error) ", "output": "{\n\tvar bf []byte\n\n\tfor {\n\t\tif n == len(target) {\n\t\t\treturn\n\n\t\t}\n\t\tbf = make([]byte, 1)\n\n\t\t_, err = r.input.Read(bf)\n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif bf[0] < 0xF8 {\n\t\t\ttarget[n] = bf[0]\n\t\t\tn++\n\t\t\tcontinue\n\t\t}\n\n\n\t}\n\n}"} {"input": "package reaperlog\n\nimport (\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"github.com/rifflock/lfshook\"\n\t\"go.mozilla.org/mozlogrus\"\n)\n\nvar config LogConfig\n\ntype LogConfig struct {\n\tExtras bool\n}\n\nfunc EnableExtras() {\n\tconfig.Extras = true\n}\n\n\n\nfunc Extras() bool {\n\treturn config.Extras\n}\n\nfunc SetConfig(c *LogConfig) {\n\tconfig = *c\n}\n\nfunc AddLogFile(filename string) {\n\tlog.AddHook(lfshook.NewHook(lfshook.PathMap{\n\t\tlog.DebugLevel: filename,\n\t\tlog.InfoLevel: filename,\n\t\tlog.WarnLevel: filename,\n\t\tlog.ErrorLevel: filename,\n\t\tlog.FatalLevel: filename,\n\t\tlog.PanicLevel: filename,\n\t}))\n}\n\nfunc Debug(format string, args ...interface{}) {\n\tlog.Debugf(format, args...)\n}\n\nfunc Info(format string, args ...interface{}) {\n\tlog.Infof(format, args...)\n}\n\nfunc Warning(format string, args ...interface{}) {\n\tlog.Warningf(format, args...)\n}\n\nfunc Fatal(format string, args ...interface{}) {\n\tlog.Fatalf(format, args...)\n}\n\nfunc Panic(format string, args ...interface{}) {\n\tlog.Panicf(format, args...)\n}\n\nfunc Error(format string, args ...interface{}) {\n\tlog.Errorf(format, args...)\n}\n\nfunc EnableMozlog() ", "output": "{\n\tmozlogrus.Enable(\"Reaper\")\n}"} {"input": "package reboot\n\nimport (\n\t\"github.com/juju/errors\"\n\t\"github.com/juju/utils/clock\"\n\n\t\"github.com/juju/juju/agent\"\n\t\"github.com/juju/juju/api\"\n\t\"github.com/juju/juju/api/base\"\n\t\"github.com/juju/juju/worker\"\n\t\"github.com/juju/juju/worker/dependency\"\n)\n\n\ntype ManifoldConfig struct {\n\tAgentName string\n\tAPICallerName string\n\tMachineLockName string\n\tClock clock.Clock\n}\n\n\n\n\n\n\n\n\n\nfunc newWorker(a agent.Agent, apiCaller base.APICaller, machineLockName string, clock clock.Clock) (worker.Worker, error) {\n\tapiConn, ok := apiCaller.(api.Connection)\n\tif !ok {\n\t\treturn nil, errors.New(\"unable to obtain api.Connection\")\n\t}\n\trebootState, err := apiConn.Reboot()\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tw, err := NewReboot(rebootState, a.CurrentConfig(), machineLockName, clock)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"cannot start reboot worker\")\n\t}\n\treturn w, nil\n}\n\nfunc Manifold(config ManifoldConfig) dependency.Manifold ", "output": "{\n\treturn dependency.Manifold{\n\t\tInputs: []string{\n\t\t\tconfig.AgentName,\n\t\t\tconfig.APICallerName,\n\t\t},\n\t\tStart: func(context dependency.Context) (worker.Worker, error) {\n\t\t\tvar agent agent.Agent\n\t\t\tif err := context.Get(config.AgentName, &agent); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tvar apiCaller base.APICaller\n\t\t\tif err := context.Get(config.APICallerName, &apiCaller); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif config.Clock == nil {\n\t\t\t\treturn nil, errors.NotValidf(\"missing Clock\")\n\t\t\t}\n\t\t\tif config.MachineLockName == \"\" {\n\t\t\t\treturn nil, errors.NotValidf(\"missing MachineLockName\")\n\t\t\t}\n\t\t\treturn newWorker(agent, apiCaller, config.MachineLockName, config.Clock)\n\t\t},\n\t}\n}"} {"input": "package api\n\nimport (\n\t\"sort\"\n\t\"time\"\n)\n\n\ntype Evaluations struct {\n\tclient *Client\n}\n\n\nfunc (c *Client) Evaluations() *Evaluations {\n\treturn &Evaluations{client: c}\n}\n\n\nfunc (e *Evaluations) List(q *QueryOptions) ([]*Evaluation, *QueryMeta, error) {\n\tvar resp []*Evaluation\n\tqm, err := e.client.query(\"/v1/evaluations\", &resp, q)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tsort.Sort(EvalIndexSort(resp))\n\treturn resp, qm, nil\n}\n\n\nfunc (e *Evaluations) Info(evalID string, q *QueryOptions) (*Evaluation, *QueryMeta, error) {\n\tvar resp Evaluation\n\tqm, err := e.client.query(\"/v1/evaluation/\"+evalID, &resp, q)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn &resp, qm, nil\n}\n\n\n\n\n\n\ntype Evaluation struct {\n\tID string\n\tPriority int\n\tType string\n\tTriggeredBy string\n\tJobID string\n\tJobModifyIndex uint64\n\tNodeID string\n\tNodeModifyIndex uint64\n\tStatus string\n\tStatusDescription string\n\tWait time.Duration\n\tNextEval string\n\tPreviousEval string\n\tCreateIndex uint64\n\tModifyIndex uint64\n}\n\n\n\ntype EvalIndexSort []*Evaluation\n\nfunc (e EvalIndexSort) Len() int {\n\treturn len(e)\n}\n\nfunc (e EvalIndexSort) Less(i, j int) bool {\n\treturn e[i].CreateIndex > e[j].CreateIndex\n}\n\nfunc (e EvalIndexSort) Swap(i, j int) {\n\te[i], e[j] = e[j], e[i]\n}\n\nfunc (e *Evaluations) Allocations(evalID string, q *QueryOptions) ([]*AllocationListStub, *QueryMeta, error) ", "output": "{\n\tvar resp []*AllocationListStub\n\tqm, err := e.client.query(\"/v1/evaluation/\"+evalID+\"/allocations\", &resp, q)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tsort.Sort(AllocIndexSort(resp))\n\treturn resp, qm, nil\n}"} {"input": "package routing\n\nimport \"net/http\"\n\n\nfunc Method(method string, handler http.Handler) Matcher {\n\treturn func(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {\n\t\tif req.Method == method {\n\t\t\thandler.ServeHTTP(resp, req)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n}\n\n\nfunc GET(handler http.Handler) Matcher {\n\treturn Method(\"GET\", handler)\n}\n\n\nfunc GETFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn GET(http.HandlerFunc(handler))\n}\n\n\nfunc POST(handler http.Handler) Matcher {\n\treturn Method(\"POST\", handler)\n}\n\n\nfunc POSTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn POST(http.HandlerFunc(handler))\n}\n\n\nfunc PUT(handler http.Handler) Matcher {\n\treturn Method(\"PUT\", handler)\n}\n\n\n\n\n\nfunc PATCH(handler http.Handler) Matcher {\n\treturn Method(\"PATCH\", handler)\n}\n\n\nfunc PATCHFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn PATCH(http.HandlerFunc(handler))\n}\n\n\nfunc DELETE(handler http.Handler) Matcher {\n\treturn Method(\"DELETE\", handler)\n}\n\n\nfunc DELETEFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn DELETE(http.HandlerFunc(handler))\n}\n\n\n\nfunc MethodNotAllowed(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {\n\tresp.WriteHeader(405)\n\treturn true\n}\n\nfunc PUTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher ", "output": "{\n\treturn PUT(http.HandlerFunc(handler))\n}"} {"input": "package lib_gc_metrics_endpoint\n\nimport(\n\t\"expvar\"\n\t\"net/http\"\n\t\"net\"\n)\n\nvar (\n\tDummy dummy\n)\n\ntype dummy struct{}\n\nfunc init(){\n\tz:=expvar.NewString(\"METRICS\")\n\tz.Set(\"OK\")\n}\n\n\n\nfunc Start(_net,host,port string) error", "output": "{\n\tsock, err := net.Listen(_net, host+\":\"+port)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo func() {\n\n\t\thttp.Serve(sock, nil)\n\t}()\n\treturn nil\n}"} {"input": "package logical\n\ntype HTTPCodedError interface {\n\tError() string\n\tCode() int\n}\n\n\n\ntype codedError struct {\n\tStatus int\n\tMessage string\n}\n\nfunc (e *codedError) Error() string {\n\treturn e.Message\n}\n\nfunc (e *codedError) Code() int {\n\treturn e.Status\n}\n\n\n\ntype StatusBadRequest struct {\n\tErr string\n}\n\n\nfunc (s *StatusBadRequest) Error() string {\n\treturn s.Err\n}\n\n\n\n\n\ntype ReplicationCodedError struct {\n\tMsg string\n\tCode int\n}\n\nfunc (r *ReplicationCodedError) Error() string {\n\treturn r.Msg\n}\n\nfunc CodedError(status int, msg string) HTTPCodedError ", "output": "{\n\treturn &codedError{\n\t\tStatus: status,\n\t\tMessage: msg,\n\t}\n}"} {"input": "package externalversions\n\nimport (\n\t\"fmt\"\n\n\tschema \"k8s.io/apimachinery/pkg/runtime/schema\"\n\tcache \"k8s.io/client-go/tools/cache\"\n\tv1alpha1 \"knative.dev/eventing-kafka-broker/control-plane/pkg/apis/eventing/v1alpha1\"\n)\n\n\n\ntype GenericInformer interface {\n\tInformer() cache.SharedIndexInformer\n\tLister() cache.GenericLister\n}\n\ntype genericInformer struct {\n\tinformer cache.SharedIndexInformer\n\tresource schema.GroupResource\n}\n\n\nfunc (f *genericInformer) Informer() cache.SharedIndexInformer {\n\treturn f.informer\n}\n\n\n\n\n\n\nfunc (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) {\n\tswitch resource {\n\tcase v1alpha1.SchemeGroupVersion.WithResource(\"kafkasinks\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Eventing().V1alpha1().KafkaSinks().Informer()}, nil\n\n\t}\n\n\treturn nil, fmt.Errorf(\"no informer found for %v\", resource)\n}\n\nfunc (f *genericInformer) Lister() cache.GenericLister ", "output": "{\n\treturn cache.NewGenericLister(f.Informer().GetIndexer(), f.resource)\n}"} {"input": "package net\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\n\ntype PortRange struct {\n\tBase int\n\tSize int\n}\n\n\nfunc (pr *PortRange) Contains(p int) bool {\n\treturn (p >= pr.Base) && ((p - pr.Base) < pr.Size)\n}\n\n\n\nfunc (pr PortRange) String() string {\n\tif pr.Size == 0 {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\"%d-%d\", pr.Base, pr.Base+pr.Size-1)\n}\n\n\n\n\n\n\n\n\nfunc (*PortRange) Type() string {\n\treturn \"portRange\"\n}\n\n\n\nfunc ParsePortRange(value string) (*PortRange, error) {\n\tpr := &PortRange{}\n\terr := pr.Set(value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pr, nil\n}\n\nfunc ParsePortRangeOrDie(value string) *PortRange {\n\tpr, err := ParsePortRange(value)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"couldn't parse port range %q: %v\", value, err))\n\t}\n\treturn pr\n}\n\nfunc (pr *PortRange) Set(value string) error ", "output": "{\n\tvalue = strings.TrimSpace(value)\n\n\n\tif value == \"\" {\n\t\tpr.Base = 0\n\t\tpr.Size = 0\n\t\treturn nil\n\t}\n\n\thyphenIndex := strings.Index(value, \"-\")\n\tif hyphenIndex == -1 {\n\t\treturn fmt.Errorf(\"expected hyphen in port range\")\n\t}\n\n\tvar err error\n\tvar low int\n\tvar high int\n\tlow, err = strconv.Atoi(value[:hyphenIndex])\n\tif err == nil {\n\t\thigh, err = strconv.Atoi(value[hyphenIndex+1:])\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to parse port range: %s\", value)\n\t}\n\n\tif high < low {\n\t\treturn fmt.Errorf(\"end port cannot be less than start port: %s\", value)\n\t}\n\tpr.Base = low\n\tpr.Size = 1 + high - low\n\treturn nil\n}"} {"input": "package qemu\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n\t\"syscall\"\n\t\"unsafe\"\n\n\t\"github.com/golang/glog\"\n\t\"github.com/hyperhq/runv/hypervisor/network\"\n)\n\nconst (\n\tIFNAMSIZ = 16\n\tCIFF_TAP = 0x0002\n\tCIFF_NO_PI = 0x1000\n\tCIFF_ONE_QUEUE = 0x2000\n)\n\ntype ifReq struct {\n\tName [IFNAMSIZ]byte\n\tFlags uint16\n\tpad [0x28 - 0x10 - 2]byte\n}\n\nfunc GetTapFd(device, bridge, options string) (int, error) {\n\tvar (\n\t\treq ifReq\n\t\terrno syscall.Errno\n\t)\n\n\ttapFile, err := os.OpenFile(\"/dev/net/tun\", os.O_RDWR, 0)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\treq.Flags = CIFF_TAP | CIFF_NO_PI | CIFF_ONE_QUEUE\n\tcopy(req.Name[:len(req.Name)-1], []byte(device))\n\t_, _, errno = syscall.Syscall(syscall.SYS_IOCTL, tapFile.Fd(),\n\t\tuintptr(syscall.TUNSETIFF),\n\t\tuintptr(unsafe.Pointer(&req)))\n\tif errno != 0 {\n\t\ttapFile.Close()\n\t\treturn -1, fmt.Errorf(\"create tap device failed\\n\")\n\t}\n\n\terr = network.UpAndAddToBridge(device, bridge, options)\n\tif err != nil {\n\t\tglog.Errorf(\"Add to bridge failed %s %s\", bridge, device)\n\t\ttapFile.Close()\n\t\treturn -1, err\n\t}\n\n\treturn int(tapFile.Fd()), nil\n}\n\n\n\nfunc GetVhostUserPort(device, bridge, sockPath, option string) error ", "output": "{\n\tglog.V(3).Infof(\"Found ovs bridge %s, attaching tap %s to it\\n\", bridge, device)\n\toptions := fmt.Sprintf(\"vhost-server-path=%s/%s\", sockPath, device)\n\tif option != \"\" {\n\t\toptions = options + \",\" + option\n\t}\n\n\tout, err := exec.Command(\"ovs-vsctl\", \"--may-exist\", \"add-port\", bridge, device, \"--\", \"set\", \"Interface\", device, \"type=dpdkvhostuserclient\", \"options:\"+options).CombinedOutput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Ovs failed to add port: %s, error :%v\", strings.TrimSpace(string(out)), err)\n\t}\n\n\treturn nil\n}"} {"input": "package api\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"testing\"\n)\n\n\n\nfunc BenchmarkShort(b *testing.B) ", "output": "{\n\tb.StopTimer()\n\tshortReq, _ := json.Marshal(shortReq{LongURL: \"http://www.google.com\"})\n\tb.StartTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\treq, err := http.NewRequest(\n\t\t\t\"POST\",\n\t\t\t\"http://127.0.0.1:3030/short\",\n\t\t\tbytes.NewBuffer(shortReq))\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\t\tclient := &http.Client{}\n\t\tresp, err := client.Do(req)\n\t\tif err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t\tif resp.StatusCode != http.StatusOK {\n\t\t\tb.Fatalf(\"http response status: %v\", resp.StatusCode)\n\t\t}\n\n\t\tresp.Body.Close()\n\t}\n}"} {"input": "package types\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestGetMarker(t *testing.T) {\n\tu := Universe{}\n\tn := Name{\"path/to/package\", \"Foo\"}\n\tf := u.Get(n)\n\tif f == nil || f.Name != n {\n\t\tt.Errorf(\"Expected marker type.\")\n\t}\n}\n\nfunc TestGetBuiltin(t *testing.T) ", "output": "{\n\tu := Universe{}\n\tif builtinPkg := u.Package(\"\"); builtinPkg.Has(\"string\") {\n\t\tt.Errorf(\"Expected builtin package to not have builtins until they're asked for explicitly. %#v\", builtinPkg)\n\t}\n\ts := u.Get(Name{\"\", \"string\"})\n\tif s != String {\n\t\tt.Errorf(\"Expected canonical string type.\")\n\t}\n\tif builtinPkg := u.Package(\"\"); !builtinPkg.Has(\"string\") {\n\t\tt.Errorf(\"Expected builtin package to exist and have builtins by default. %#v\", builtinPkg)\n\t}\n\tif builtinPkg := u.Package(\"\"); len(builtinPkg.Types) != 1 {\n\t\tt.Errorf(\"Expected builtin package to not have builtins until they're asked for explicitly. %#v\", builtinPkg)\n\t}\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/kataras/iris/v12/_examples/mvc/vuejs-todo-mvc/src/todo\"\n\n\t\"github.com/kataras/iris/v12\"\n\t\"github.com/kataras/iris/v12/mvc\"\n\t\"github.com/kataras/iris/v12/sessions\"\n\t\"github.com/kataras/iris/v12/websocket\"\n)\n\n\ntype TodoController struct {\n\tService todo.Service\n\n\tSession *sessions.Session\n\n\tNS *websocket.NSConn\n}\n\n\n\n\n\nfunc (c *TodoController) BeforeActivation(b mvc.BeforeActivation) {\n\tb.Dependencies().Register(func(ctx iris.Context) (items []todo.Item) {\n\t\tctx.ReadJSON(&items)\n\t\treturn\n\t}) \n}\n\n\nfunc (c *TodoController) Get() []todo.Item {\n\treturn c.Service.Get(c.Session.ID())\n}\n\n\n\ntype PostItemResponse struct {\n\tSuccess bool `json:\"success\"`\n}\n\nvar emptyResponse = PostItemResponse{Success: false}\n\n\nfunc (c *TodoController) Post(newItems []todo.Item) PostItemResponse {\n\tif err := c.Service.Save(c.Session.ID(), newItems); err != nil {\n\t\treturn emptyResponse\n\t}\n\n\treturn PostItemResponse{Success: true}\n}\n\n\n\nfunc (c *TodoController) Save(msg websocket.Message) error ", "output": "{\n\tid := c.Session.ID()\n\tc.NS.Conn.Server().Broadcast(nil, websocket.Message{\n\t\tNamespace: msg.Namespace,\n\t\tEvent: \"saved\",\n\t\tTo: id,\n\t\tBody: websocket.Marshal(c.Service.Get(id)),\n\t})\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"time\"\n)\n\ntype Player struct {\n\tlog *os.File\n\tlogTime time.Time\n\tdecoder *json.Decoder\n\tdir string\n\toffset time.Duration\n}\n\nfunc NewPlayer(dir string) *Player {\n\tvar p Player\n\tp.dir = dir\n\treturn &p\n}\n\nfunc (p *Player) Reset() error {\n\tn := p.Then()\n\tp.logTime = logTime(n)\n\tfilename := logFileName(n)\n\tif p.log != nil {\n\t\tp.log.Close()\n\t}\n\tlog.Printf(\"Playing file %s\\n\", filename)\n\tvar err error\n\tp.log, err = os.Open(filepath.Join(p.dir, filename))\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.decoder = json.NewDecoder(p.log)\n\treturn nil\n}\n\n\nfunc (p *Player) Playback(t time.Time) error {\n\tlog.Printf(\"Playing back starting at %s\\n\", t)\n\tp.offset = time.Now().Sub(t)\n\terr := p.Reset()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor {\n\t\tvar m Msg\n\t\terr := p.decoder.Decode(&m)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\td := m.Timestamp.Time.Sub(p.Then())\n\t\tdebugf(\"difference is %f seconds\", d.Seconds())\n\t\tif d > 0 {\n\t\t\ttime.Sleep(d)\n\t\t}\n\t\tm.Print()\n\t}\n}\n\n\n\nfunc (p *Player) Close() error {\n\tp.decoder = nil\n\treturn p.log.Close()\n}\n\nfunc (p *Player) Then() time.Time ", "output": "{\n\treturn time.Now().Add(-p.offset)\n}"} {"input": "package unibyte\n\nimport \"unicode\"\n\n\nfunc IsLower(b byte) bool {\n\treturn b >= 'a' && b <= 'z'\n}\n\n\nfunc IsUpper(b byte) bool {\n\treturn b >= 'A' && b <= 'Z'\n}\n\n\n\n\n\nfunc IsSpaceQuote(b byte) bool {\n\treturn IsSpace(b) || b == '\"' || b == '\\''\n}\n\n\nfunc IsSpace(b byte) bool {\n\treturn unicode.IsSpace(rune(b))\n}\n\n\nfunc ToLower(b byte) byte {\n\tif IsUpper(b) {\n\t\tb = b - 'A' + 'a'\n\t}\n\n\treturn b\n}\n\n\nfunc ToUpper(b byte) byte {\n\tif IsLower(b) {\n\t\tb = b - 'a' + 'A'\n\t}\n\n\treturn b\n}\n\n\nfunc ToLowerString(b byte) string {\n\tif IsUpper(b) {\n\t\tb = b - 'A' + 'a'\n\t}\n\n\treturn string(b)\n}\n\n\nfunc ToUpperString(b byte) string {\n\tif IsLower(b) {\n\t\tb = b - 'a' + 'A'\n\t}\n\n\treturn string(b)\n}\n\nfunc IsLetter(b byte) bool ", "output": "{\n\treturn IsLower(b) || IsUpper(b)\n}"} {"input": "package isbn\n\nimport (\n\t\"errors\"\n\t\"math\"\n\t\"strconv\"\n\t\"unicode\"\n)\n\n\n\nfunc dropHyphen(isbn string) string {\n\tvar result string\n\tfor _, char := range isbn {\n\t\tif char == '-' {\n\t\t\tcontinue\n\t\t}\n\t\tresult += string(char)\n\t}\n\treturn result\n}\n\nfunc strToSlice(isbn string) (result []int, err error) {\n\n\tfor pos, char := range isbn {\n\t\tif unicode.IsLetter(char) && (char != 'X' || pos != 9) {\n\t\t\terr = errors.New(\"invalid character\")\n\t\t\treturn\n\t\t} else if char == 'X' {\n\t\t\tresult = append(result, 10)\n\t\t} else {\n\t\t\ti, _ := strconv.Atoi(string(char))\n\t\t\tresult = append(result, i)\n\t\t}\n\t}\n\treturn\n}\n\nfunc calcCheckDigit(isbn []int) bool {\n\tvar pool int\n\tfor idx, value := range isbn {\n\t\tpool += int(math.Abs(float64(idx)-10)) * value\n\t}\n\tresult := pool % 11\n\n\treturn result == 0\n}\n\nfunc IsValidISBN(isbn string) bool ", "output": "{\n\n\tisbn = dropHyphen(isbn)\n\n\tary, err := strToSlice(isbn)\n\tif len(ary) != 10 || err != nil {\n\t\treturn false\n\t}\n\n\treturn calcCheckDigit(ary)\n}"} {"input": "package problemdetector\n\nimport (\n\t\"github.com/golang/glog\"\n\n\tkubeutil \"k8s.io/kubernetes/pkg/util\"\n\n\t\"k8s.io/node-problem-detector/pkg/condition\"\n\t\"k8s.io/node-problem-detector/pkg/kernelmonitor\"\n\t\"k8s.io/node-problem-detector/pkg/problemclient\"\n\t\"k8s.io/node-problem-detector/pkg/util\"\n)\n\n\ntype ProblemDetector interface {\n\tRun() error\n}\n\ntype problemDetector struct {\n\tclient problemclient.Client\n\tconditionManager condition.ConditionManager\n\tmonitor kernelmonitor.KernelMonitor\n}\n\n\n\n\n\n\nfunc (p *problemDetector) Run() error {\n\tp.conditionManager.Start()\n\tch, err := p.monitor.Start()\n\tif err != nil {\n\t\treturn err\n\t}\n\tglog.Info(\"Problem detector started\")\n\tfor {\n\t\tselect {\n\t\tcase status := <-ch:\n\t\t\tfor _, event := range status.Events {\n\t\t\t\tp.client.Eventf(util.ConvertToAPIEventType(event.Severity), status.Source, event.Reason, event.Message)\n\t\t\t}\n\t\t\tfor _, condition := range status.Conditions {\n\t\t\t\tp.conditionManager.UpdateCondition(condition)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc NewProblemDetector(monitor kernelmonitor.KernelMonitor) ProblemDetector ", "output": "{\n\tclient := problemclient.NewClientOrDie()\n\treturn &problemDetector{\n\t\tclient: client,\n\t\tconditionManager: condition.NewConditionManager(client, kubeutil.RealClock{}),\n\t\tmonitor: monitor,\n\t}\n}"} {"input": "package conversation\n\nimport \"github.com/nlefler/elmo/apiai\"\n\ntype sugarAfter struct {\n\tstateContainer\n}\n\n\n\nfunc (c *sugarAfter) step() (state, bool) ", "output": "{\n\tr := commandRouter{}\n\tr.inherit(c)\n\tr.currentAction = apiai.ActionCall{}\n\treturn &r, false\n}"} {"input": "package handlers\n\nimport (\n \"encoding/json\"\n \"github.com/sescobb27/proyecto2-travisci/models\"\n \"net/http\"\n)\n\nfunc GetCategories(res http.ResponseWriter, req *http.Request) {\n res.Header().Set(\"Content-Type\", \"application/json\")\n categories := models.GetCategories()\n json_categories, err := json.Marshal(categories)\n\n if err != nil {\n panic(err)\n }\n\n res.Write(json_categories)\n}\n\n\n\nfunc GetLocations(res http.ResponseWriter, req *http.Request) ", "output": "{\n res.Header().Set(\"Content-Type\", \"application/json\")\n locations := models.GetLocations()\n json_locations, err := json.Marshal(locations)\n\n if err != nil {\n panic(err)\n }\n\n res.Write(json_locations)\n}"} {"input": "package utils\n\nimport (\n\t\"github.com/labstack/gommon/log\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n\n\nfunc CreateDirIfReqd(dir string) (string, error) {\n\tdirAbsPath, err := filepath.Abs(dir)\n\tif err != nil {\n\t\treturn dirAbsPath, err\n\t}\n\tif _, err := os.Stat(dirAbsPath); err == nil {\n\t\treturn dirAbsPath, nil\n\t}\n\terr = os.MkdirAll(dirAbsPath, 0777)\n\treturn dirAbsPath, err\n}\n\nfunc UpdateFile(file, val string) error ", "output": "{\n\tdir := filepath.Dir(file)\n\tlog.Info(\"creating dir %s\", dir)\n\tdir, err := CreateDirIfReqd(dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tioutil.WriteFile(filepath.Join(dir, filepath.Base(file)), []byte(val), 0777)\n\treturn nil\n}"} {"input": "package controller\n\nimport (\n\t\"github.com/tmacychen/UFG/framework\"\n\t\"github.com/tmacychen/UFG/framework/outer\"\n)\n\ntype AttachableOuter interface {\n\touter.Relayouter\n}\n\ntype Attachable struct {\n\touter AttachableOuter\n\tonAttach framework.Event\n\tonDetach framework.Event\n\tattached bool\n}\n\n\n\nfunc (a *Attachable) Attached() bool {\n\treturn a.attached\n}\n\nfunc (a *Attachable) Attach() {\n\tif a.attached {\n\t\tpanic(\"Control already attached\")\n\t}\n\ta.attached = true\n\tif a.onAttach != nil {\n\t\ta.onAttach.Fire()\n\t}\n}\n\nfunc (a *Attachable) Detach() {\n\tif !a.attached {\n\t\tpanic(\"Control already detached\")\n\t}\n\ta.attached = false\n\tif a.onDetach != nil {\n\t\ta.onDetach.Fire()\n\t}\n}\n\nfunc (a *Attachable) OnAttach(f func()) framework.EventSubscription {\n\tif a.onAttach == nil {\n\t\ta.onAttach = CreateEvent(func() {})\n\t}\n\treturn a.onAttach.Listen(f)\n}\n\nfunc (a *Attachable) OnDetach(f func()) framework.EventSubscription {\n\tif a.onDetach == nil {\n\t\ta.onDetach = CreateEvent(func() {})\n\t}\n\treturn a.onDetach.Listen(f)\n}\n\nfunc (a *Attachable) Init(outer AttachableOuter) ", "output": "{\n\ta.outer = outer\n}"} {"input": "package billing\n\nimport original \"github.com/Azure/azure-sdk-for-go/services/billing/mgmt/2017-04-24-preview/billing\"\n\nconst (\n\tDefaultBaseURI = original.DefaultBaseURI\n)\n\ntype ManagementClient = original.ManagementClient\ntype InvoicesClient = original.InvoicesClient\ntype DownloadURL = original.DownloadURL\ntype ErrorDetails = original.ErrorDetails\ntype ErrorResponse = original.ErrorResponse\ntype Invoice = original.Invoice\ntype InvoiceProperties = original.InvoiceProperties\ntype InvoicesListResult = original.InvoicesListResult\ntype Operation = original.Operation\ntype OperationDisplay = original.OperationDisplay\ntype OperationListResult = original.OperationListResult\ntype Period = original.Period\ntype PeriodProperties = original.PeriodProperties\ntype PeriodsListResult = original.PeriodsListResult\ntype Resource = original.Resource\ntype OperationsClient = original.OperationsClient\ntype PeriodsClient = original.PeriodsClient\n\nfunc NewOperationsClient(subscriptionID string) OperationsClient {\n\treturn original.NewOperationsClient(subscriptionID)\n}\nfunc NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient {\n\treturn original.NewOperationsClientWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewPeriodsClient(subscriptionID string) PeriodsClient {\n\treturn original.NewPeriodsClient(subscriptionID)\n}\nfunc NewPeriodsClientWithBaseURI(baseURI string, subscriptionID string) PeriodsClient {\n\treturn original.NewPeriodsClientWithBaseURI(baseURI, subscriptionID)\n}\n\nfunc Version() string {\n\treturn original.Version()\n}\nfunc New(subscriptionID string) ManagementClient {\n\treturn original.New(subscriptionID)\n}\nfunc NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient {\n\treturn original.NewWithBaseURI(baseURI, subscriptionID)\n}\nfunc NewInvoicesClient(subscriptionID string) InvoicesClient {\n\treturn original.NewInvoicesClient(subscriptionID)\n}\nfunc NewInvoicesClientWithBaseURI(baseURI string, subscriptionID string) InvoicesClient {\n\treturn original.NewInvoicesClientWithBaseURI(baseURI, subscriptionID)\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn original.UserAgent() + \" profiles/preview\"\n}"} {"input": "package agent\n\n\n\nimport (\n\t\"fmt\"\n\n\t\"launchpad.net/juju-core/state/api/common\"\n\t\"launchpad.net/juju-core/state/api/params\"\n)\n\n\ntype State struct {\n\tcaller common.Caller\n}\n\n\n\nfunc NewState(caller common.Caller) *State {\n\treturn &State{caller}\n}\n\n\n\ntype Entity struct {\n\tst *State\n\ttag string\n\tdoc params.AgentGetEntitiesResult\n}\n\nfunc (st *State) Entity(tag string) (*Entity, error) {\n\tdoc, err := st.getEntity(tag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Entity{\n\t\tst: st,\n\t\ttag: tag,\n\t\tdoc: *doc,\n\t}, nil\n}\n\n\nfunc (m *Entity) Tag() string {\n\treturn m.tag\n}\n\n\nfunc (m *Entity) Life() params.Life {\n\treturn m.doc.Life\n}\n\n\n\n\n\nfunc (m *Entity) Jobs() []params.MachineJob {\n\treturn m.doc.Jobs\n}\n\n\nfunc (m *Entity) SetPassword(password string) error {\n\tvar results params.ErrorResults\n\targs := params.PasswordChanges{\n\t\tChanges: []params.PasswordChange{{\n\t\t\tTag: m.tag,\n\t\t\tPassword: password,\n\t\t}},\n\t}\n\terr := m.st.caller.Call(\"Agent\", \"\", \"SetPasswords\", args, &results)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn results.OneError()\n}\n\nfunc (st *State) getEntity(tag string) (*params.AgentGetEntitiesResult, error) ", "output": "{\n\tvar results params.AgentGetEntitiesResults\n\targs := params.Entities{\n\t\tEntities: []params.Entity{{Tag: tag}},\n\t}\n\terr := st.caller.Call(\"Agent\", \"\", \"GetEntities\", args, &results)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(results.Entities) != 1 {\n\t\treturn nil, fmt.Errorf(\"expected one result, got %d\", len(results.Entities))\n\t}\n\tif err := results.Entities[0].Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn &results.Entities[0], nil\n}"} {"input": "package responsewriter\n\n\n\n\ntype ErrBodyFlushedBeforeCode struct{}\n\n\n\n\n\n\n\ntype ErrCodeFlushedBeforeHeaders struct{}\n\n\nfunc (e ErrCodeFlushedBeforeHeaders) Error() string {\n\treturn \"code flushed before headers\"\n}\n\nfunc (e ErrBodyFlushedBeforeCode) Error() string ", "output": "{\n\treturn \"body flushed before code\"\n}"} {"input": "package task\n\nimport (\n\t\"github.com/c4s4/neon/neon/build\"\n\t\"reflect\"\n\tt \"time\"\n)\n\n\n\ntype timeArgs struct {\n\tTime build.Steps `neon:\"steps\"`\n\tTo string `neon:\"optional\"`\n}\n\nfunc time(context *build.Context, args interface{}) error {\n\tparams := args.(timeArgs)\n\tstart := t.Now()\n\terr := params.Time.Run(context)\n\tif err != nil {\n\t\treturn err\n\t}\n\tduration := t.Now().Sub(start).Seconds()\n\tif params.To != \"\" {\n\t\tcontext.SetProperty(params.To, duration)\n\t} else {\n\t\tcontext.Message(\"Duration: %gs\", duration)\n\t}\n\treturn nil\n}\n\nfunc init() ", "output": "{\n\tbuild.AddTask(build.TaskDesc{\n\t\tName: \"time\",\n\t\tFunc: time,\n\t\tArgs: reflect.TypeOf(timeArgs{}),\n\t\tHelp: `Record duration to run a block of steps.\n\nArguments:\n\n- time: steps we want to measure execution duration (steps).\n- to: property to store duration in seconds as a float, if not set, duration is\n printed on the console (string, optional).\n\nExamples:\n\n # print duration to say hello\n - time:\n - print: 'Hello World!'\n to: duration\n - print: 'duration: ={duration}s'`,\n\t})\n}"} {"input": "package template\n\nimport (\n\t\"github.com/dpb587/metalink\"\n)\n\ntype templateFile metalink.File\n\nfunc (tf templateFile) MD5() string {\n\tfor _, hash := range tf.Hashes {\n\t\tif hash.Type == \"md5\" {\n\t\t\treturn hash.Hash\n\t\t}\n\t}\n\n\treturn \"\"\n}\n\n\n\nfunc (tf templateFile) SHA256() string {\n\tfor _, hash := range tf.Hashes {\n\t\tif hash.Type == \"sha-256\" {\n\t\t\treturn hash.Hash\n\t\t}\n\t}\n\n\treturn \"\"\n}\n\nfunc (tf templateFile) SHA512() string {\n\tfor _, hash := range tf.Hashes {\n\t\tif hash.Type == \"sha-512\" {\n\t\t\treturn hash.Hash\n\t\t}\n\t}\n\n\treturn \"\"\n}\n\nfunc (tf templateFile) SHA1() string ", "output": "{\n\tfor _, hash := range tf.Hashes {\n\t\tif hash.Type == \"sha-1\" {\n\t\t\treturn hash.Hash\n\t\t}\n\t}\n\n\treturn \"\"\n}"} {"input": "package utils\n\nimport \"syscall\"\n\n\n\nfunc raiseFdLimit(max uint64) error {\n\tvar limit syscall.Rlimit\n\tif err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {\n\t\treturn err\n\t}\n\tlimit.Cur = limit.Max\n\tif limit.Cur > max {\n\t\tlimit.Cur = max\n\t}\n\tif err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc getFdLimit() (int, error) ", "output": "{\n\tvar limit syscall.Rlimit\n\tif err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {\n\t\treturn 0, err\n\t}\n\treturn int(limit.Cur), nil\n}"} {"input": "package state\n\nimport (\n\t\"time\"\n\n\t\"github.com/juju/errors\"\n\t\"gopkg.in/juju/names.v2\"\n\n\t\"github.com/juju/juju/core/lease\"\n)\n\n\n\n\n\n\n\n\n\ntype singularSecretary struct {\n\tuuid string\n}\n\n\nfunc (s singularSecretary) CheckLease(name string) error {\n\tif name != s.uuid {\n\t\treturn errors.New(\"expected environ UUID\")\n\t}\n\treturn nil\n}\n\n\nfunc (s singularSecretary) CheckHolder(name string) error {\n\tif _, err := names.ParseMachineTag(name); err != nil {\n\t\treturn errors.New(\"expected machine tag\")\n\t}\n\treturn nil\n}\n\n\n\n\n\n\nfunc (st *State) SingularClaimer() lease.Claimer {\n\treturn st.workers.singularManager()\n}\n\nfunc (s singularSecretary) CheckDuration(duration time.Duration) error ", "output": "{\n\tif duration <= 0 {\n\t\treturn errors.NewNotValid(nil, \"non-positive\")\n\t}\n\treturn nil\n}"} {"input": "package model\n\nimport (\n\t\"log\"\n\t\"reflect\"\n\n\t\"github.com/go-errors/errors\"\n)\n\ntype ProviderRegistry struct {\n\tproviders []Provider\n}\n\nfunc (registry *ProviderRegistry) RegisterProvider(provider Provider) {\n\tregistry.providers = append(registry.providers, provider)\n}\n\n\n\nfunc (registry *ProviderRegistry) ResolveProvider() (Provider, error) ", "output": "{\n\tfor _, p := range registry.providers {\n\t\tlog.Printf(\"Detect provider: %v\", reflect.TypeOf(p))\n\t\tif p.Detect() {\n\t\t\tlog.Printf(\"Found provider: %v\", reflect.TypeOf(p))\n\t\t\terr := p.Init()\n\t\t\treturn p, err\n\t\t}\n\t}\n\treturn nil, errors.Errorf(\"Could not resolve to any provider.\")\n}"} {"input": "package builtin\n\nconst sshKeysSummary = `allows reading ssh user configuration and keys`\n\nconst sshKeysBaseDeclarationSlots = `\n ssh-keys:\n allow-installation:\n slot-snap-type:\n - core\n deny-auto-connection: true\n`\n\nconst sshKeysConnectedPlugAppArmor = `\n# Description: Can read ssh user configuration as well as public and private\n# keys.\n\n/usr/bin/ssh ixr,\n/etc/ssh/ssh_config r,\nowner @{HOME}/.ssh/{,**} r,\n`\n\n\n\nfunc init() ", "output": "{\n\tregisterIface(&commonInterface{\n\t\tname: \"ssh-keys\",\n\t\tsummary: sshKeysSummary,\n\t\timplicitOnCore: true,\n\t\timplicitOnClassic: true,\n\t\tbaseDeclarationSlots: sshKeysBaseDeclarationSlots,\n\t\tconnectedPlugAppArmor: sshKeysConnectedPlugAppArmor,\n\t})\n}"} {"input": "package main \n\nimport \"fmt\"\n\nfunc main() {\n\tExported()\n}\n\n\n\ntype Shaper interface {\n}\n\ntype Rectangle struct {\n}\n\ntype square struct {\n}\n\ntype circle interface {\n}\n\ntype Oval struct {\n}\n\nfunc Exported() ", "output": "{\n\tfmt.Println(\"Hello, Go\")\n}"} {"input": "package server\n\nimport (\n\t\"sync\"\n)\n\ntype ID uint32\n\ntype IDGenerator struct {\n\tlastID ID\n\tids []ID\n\tlocker *sync.Mutex\n\tthreadSafe bool\n}\n\nfunc NewIDGenerator(buffer int, threadSafe bool) *IDGenerator {\n\tgen := &IDGenerator{0, make([]ID, 0, buffer), &sync.Mutex{}, threadSafe}\n\tif threadSafe {\n\t\tgen.locker.Lock()\n\t\tdefer gen.locker.Unlock()\n\t}\n\n\tgen.genIDs()\n\treturn gen\n}\n\nfunc (gen *IDGenerator) genIDs() {\n\tgen.lastID += ID(cap(gen.ids) / 2)\n\tid := gen.lastID - 1\n\tfor i := 0; i < cap(gen.ids)/2; i++ {\n\t\tgen.ids = append(gen.ids, id)\n\t\tid--\n\t}\n}\n\n\n\nfunc (gen *IDGenerator) PutID(id ID) {\n\tif gen.threadSafe {\n\t\tgen.locker.Lock()\n\t\tdefer gen.locker.Unlock()\n\t}\n\tgen.ids = append(gen.ids, id)\n}\n\nfunc (gen *IDGenerator) NextID() ID ", "output": "{\n\tid := ID(0)\n\n\tif gen.threadSafe {\n\t\tgen.locker.Lock()\n\t\tdefer gen.locker.Unlock()\n\t}\n\tid, gen.ids = gen.ids[len(gen.ids)-1], gen.ids[:len(gen.ids)-1]\n\tif len(gen.ids) == 0 {\n\t\tgen.genIDs()\n\t}\n\n\treturn id\n}"} {"input": "package cli\n\nimport \"errors\"\nimport \"fmt\"\nimport \"strconv\"\n\nfunc IsArgExist(args []string, s string)(bool) {\n pos, err := getArgPos(args, s)\n if nil == err && pos > 0 {\n return true\n }\n\n return false\n}\n\nfunc GetArgBool(args []string, s string)(bool) {\n pos, err := getArgPos(args, s)\n if nil == err && pos > 0 {\n return true\n }\n\n return false\n}\n\nfunc GetArgInt(args []string, s string)(int, error) {\n \n pos, err := getArgPos(args, s)\n if nil != err || pos <= 0{\n return pos, err\n }\n\n \n if pos + 1 >= len(args) {\n return 0, errors.New(fmt.Sprintf(\"no number fallows '%s'\", s))\n }\n\n \n a := args[pos + 1]\n if regd == true && On != RegArgsStat(a) {\n return 0, errors.New(fmt.Sprintf(\"no number fallows '%s'\", s))\n }\n\n return strconv.Atoi(a)\n}\n\n\n\nfunc GetArgInts(args []string, s string)([]int, error) ", "output": "{\n pos, err := getArgPos(args, s)\n if err != nil || pos <= 0{\n return nil, err\n }\n if pos + 1 >= len(args) {\n return nil, errors.New(fmt.Sprintf(\"no number fllows '%s'\", s))\n }\n var list []int\n for i := pos + 1; i < len(args); i++ {\n if On == argmp[args[i]] {\n break\n }\n n, err := strconv.Atoi(args[i])\n if nil == err {\n list = append(list, n)\n } else {\n break\n }\n }\n if len(list) < 1 {\n return nil, errors.New(fmt.Sprintf(\"no number fllows '%s'\", s))\n }\n\n return list, nil\n}"} {"input": "package trafficmanager\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\n\n\n\nfunc Version() string {\n\treturn version.Number\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn \"Azure-SDK-For-Go/\" + Version() + \" trafficmanager/2018-02-01-preview\"\n}"} {"input": "package util\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestMakeRequest(t *testing.T) ", "output": "{\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintln(w, \"done\")\n\t}))\n\tdefer ts.Close()\n\n\thttpClient := new(HTTPAlive)\n\thttpClient.Configure(time.Duration(10)*time.Second, time.Minute, 10)\n\tassert.Equal(t, 10, httpClient.transport.MaxIdleConnsPerHost)\n\n\tcustomHeader := map[string]string{\n\t\t\"foo\": \"bar\",\n\t}\n\n\tresp, err := httpClient.MakeRequest(\n\t\t\"GET\",\n\t\tts.URL,\n\t\tbytes.NewBufferString(\"fullerite\"),\n\t\tcustomHeader)\n\n\tassert.Nil(t, err)\n\tassert.Equal(t, string(resp.Body), \"done\\n\")\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"text/tabwriter\"\n\n\t\"github.com/skriptble/froxy/cmd/froxy/Godeps/_workspace/src/github.com/BurntSushi/toml\"\n)\n\nvar (\n\tflagTypes = false\n)\n\nfunc init() {\n\tlog.SetFlags(0)\n\n\tflag.BoolVar(&flagTypes, \"types\", flagTypes,\n\t\t\"When set, the types of every defined key will be shown.\")\n\n\tflag.Usage = usage\n\tflag.Parse()\n}\n\n\n\nfunc main() {\n\tif flag.NArg() < 1 {\n\t\tflag.Usage()\n\t}\n\tfor _, f := range flag.Args() {\n\t\tvar tmp interface{}\n\t\tmd, err := toml.DecodeFile(f, &tmp)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error in '%s': %s\", f, err)\n\t\t}\n\t\tif flagTypes {\n\t\t\tprintTypes(md)\n\t\t}\n\t}\n}\n\nfunc printTypes(md toml.MetaData) {\n\ttabw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)\n\tfor _, key := range md.Keys() {\n\t\tfmt.Fprintf(tabw, \"%s%s\\t%s\\n\",\n\t\t\tstrings.Repeat(\" \", len(key)-1), key, md.Type(key...))\n\t}\n\ttabw.Flush()\n}\n\nfunc usage() ", "output": "{\n\tlog.Printf(\"Usage: %s toml-file [ toml-file ... ]\\n\",\n\t\tpath.Base(os.Args[0]))\n\tflag.PrintDefaults()\n\n\tos.Exit(1)\n}"} {"input": "package guest_file_read\n\nimport (\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\n\t\"github.com/vtolstov/cloudagent/qga\"\n)\n\n\n\nfunc fnGuestFileRead(req *qga.Request) *qga.Response {\n\tres := &qga.Response{ID: req.ID}\n\n\treqData := struct {\n\t\tHandle int `json:\"handle\"`\n\t\tCount int `json:\"count,omitempty\"`\n\t}{}\n\n\tresData := struct {\n\t\tCount int `json:\"count\"`\n\t\tBufB64 string `json:\"buf-b64\"`\n\t\tEOF bool `json:\"eof\"`\n\t}{}\n\n\terr := json.Unmarshal(req.RawArgs, &reqData)\n\tif err != nil {\n\t\tres.Error = &qga.Error{Code: -1, Desc: err.Error()}\n\t} else {\n\t\tif iface, ok := qga.StoreGet(\"guest-file\", reqData.Handle); ok {\n\t\t\tf := iface.(*os.File)\n\t\t\tvar buffer []byte\n\t\t\tvar n int\n\t\t\tn, err = f.Read(buffer)\n\t\t\tswitch err {\n\t\t\tcase nil:\n\t\t\t\tresData.Count = n\n\t\t\t\tresData.BufB64 = base64.StdEncoding.EncodeToString(buffer)\n\t\t\t\tres.Return = resData\n\t\t\tcase io.EOF:\n\t\t\t\tresData.Count = n\n\t\t\t\tresData.BufB64 = base64.StdEncoding.EncodeToString(buffer)\n\t\t\t\tresData.EOF = true\n\t\t\t\tres.Return = resData\n\t\t\tdefault:\n\t\t\t\tres.Error = &qga.Error{Code: -1, Desc: err.Error()}\n\t\t\t}\n\t\t} else {\n\t\t\tres.Error = &qga.Error{Code: -1, Desc: fmt.Sprintf(\"file handle not found\")}\n\t\t}\n\t}\n\n\treturn res\n}\n\nfunc init() ", "output": "{\n\tqga.RegisterCommand(&qga.Command{\n\t\tName: \"guest-file-read\",\n\t\tFunc: fnGuestFileRead,\n\t\tEnabled: true,\n\t\tReturns: true,\n\t\tArguments: true,\n\t})\n}"} {"input": "package concurrent\n\nimport (\n\t\"context\"\n)\n\nfunc (w *workflowRuntime) spawnWorker(ctx context.Context) {\n\tgo func() {\n\t\tvar job int64\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase <-w.idQueue.GetTaskChan():\n\t\t\t\tjob = w.idQueue.GetTask()\n\t\t\t\tw.executeFlow(job)\n\t\t\t}\n\t\t}\n\t}()\n}\n\n\n\nfunc (w *workflowRuntime) executeDependentFlow(jobId int64, job *flowTask) {\n\tgo func() {\n\t\tvar results []interface{}\n\t\tfor _, dependentId := range job.dependentIds {\n\t\t\tresults = append(results, w.getResult(dependentId.(int64)))\n\t\t}\n\n\t\tw.executionSlots <- struct{}{}\n\t\tresult := w.handlers[job.funcname](job.args, w, results)\n\t\tw.setResult(jobId, result)\n\t\t<-w.executionSlots\n\t}()\n}\n\nfunc (w *workflowRuntime) executeFlow(jobId int64) ", "output": "{\n\tw.mutex.Lock()\n\tjob := w.tasks[jobId]\n\tw.mutex.Unlock()\n\n\tif len(job.dependentIds) > 0 {\n\t\tw.executeDependentFlow(jobId, job)\n\t\treturn\n\t}\n\n\tw.executionSlots <- struct{}{}\n\tresult := w.handlers[job.funcname](job.args, w, nil)\n\tw.setResult(jobId, result)\n\t<-w.executionSlots\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/mexisme/go-config/settings\"\n)\n\n\n\n\n\nfunc AddConfigItemsWithPFlags(configKeys []string) error {\n\treturn settings.AddConfigItemsWithPFlags(configKeys)\n}\n\n\nfunc ApplyWith(key string, f func(interface{})) {\n\tsettings.ApplyWith(key, f)\n}\n\n\nfunc Get(key string) interface{} {\n\treturn settings.Get(key)\n}\n\n\nfunc GetBool(key string) bool {\n\treturn settings.GetBool(key)\n}\n\n\nfunc GetFloat64(key string) float64 {\n\treturn settings.GetFloat64(key)\n}\n\n\nfunc GetInt(key string) int {\n\treturn settings.GetInt(key)\n}\n\n\nfunc GetString(key string) string {\n\treturn settings.GetString(key)\n}\n\n\nfunc GetStringMap(key string) map[string]interface{} {\n\treturn settings.GetStringMap(key)\n}\n\n\nfunc GetStringMapString(key string) map[string]string {\n\treturn settings.GetStringMapString(key)\n}\n\n\nfunc GetStringSlice(key string) []string {\n\treturn settings.GetStringSlice(key)\n}\n\n\nfunc GetTime(key string) time.Time {\n\treturn settings.GetTime(key)\n}\n\n\nfunc GetDuration(key string) time.Duration {\n\treturn settings.GetDuration(key)\n}\n\n\nfunc IsSet(key string) bool {\n\treturn settings.IsSet(key)\n}\n\n\nfunc AllSettings() map[string]interface{} {\n\treturn settings.AllSettings()\n}\n\nfunc AddConfigItems(configKeys []string) ", "output": "{\n\tsettings.AddConfigItems(configKeys)\n}"} {"input": "package routing\n\nimport \"net/http\"\n\n\nfunc Method(method string, handler http.Handler) Matcher {\n\treturn func(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {\n\t\tif req.Method == method {\n\t\t\thandler.ServeHTTP(resp, req)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n}\n\n\nfunc GET(handler http.Handler) Matcher {\n\treturn Method(\"GET\", handler)\n}\n\n\nfunc GETFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn GET(http.HandlerFunc(handler))\n}\n\n\nfunc POST(handler http.Handler) Matcher {\n\treturn Method(\"POST\", handler)\n}\n\n\nfunc POSTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn POST(http.HandlerFunc(handler))\n}\n\n\nfunc PUT(handler http.Handler) Matcher {\n\treturn Method(\"PUT\", handler)\n}\n\n\nfunc PUTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn PUT(http.HandlerFunc(handler))\n}\n\n\nfunc PATCH(handler http.Handler) Matcher {\n\treturn Method(\"PATCH\", handler)\n}\n\n\nfunc PATCHFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn PATCH(http.HandlerFunc(handler))\n}\n\n\nfunc DELETE(handler http.Handler) Matcher {\n\treturn Method(\"DELETE\", handler)\n}\n\n\n\n\n\n\nfunc MethodNotAllowed(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {\n\tresp.WriteHeader(405)\n\treturn true\n}\n\nfunc DELETEFunc(handler func(http.ResponseWriter, *http.Request)) Matcher ", "output": "{\n\treturn DELETE(http.HandlerFunc(handler))\n}"} {"input": "package gopnsconfig\n\nimport (\n\t\"log\"\n)\n\ntype BaseConfigStruct struct {\n\tPortValue string\n\tMetricsServerValue string\n\tMetricsAPIKeyValue string\n\tMetricsPrefixValue string\n}\n\nfunc (this *BaseConfigStruct) Port() string {\n\treturn this.PortValue\n}\n\n\n\nfunc (this *BaseConfigStruct) MetricsServer() string {\n\treturn this.MetricsServerValue\n}\n\nfunc (this *BaseConfigStruct) MetricsPrefix() string {\n\treturn this.MetricsPrefixValue\n}\n\ntype BaseConfig interface {\n\tPort() string\n\tMetricsServer() string\n\tMetricsAPIKey() string\n\tMetricsPrefix() string\n}\n\nfunc parseBaseConfig(baseConfig *ConfigFile) BaseConfig {\n\tport, err := baseConfig.GetString(\"default\", \"port\")\n\tcheckError(\"Unable to find Server Port\", err)\n\n\tmetricsServer, err := baseConfig.GetString(\"default\", \"metrics-server\")\n\tcheckError(\"Unable to find metrics server\", err)\n\n\tmetricsKey, err := baseConfig.GetString(\"default\", \"metrics-api-key\")\n\tif err != nil {\n\t\tlog.Println(\"Unable to find metrics-api-key using empty string\")\n\t\tmetricsKey = \"\"\n\t}\n\n\tmetricsPrefix, err := baseConfig.GetString(\"default\", \"metrics-prefix\")\n\tif err != nil {\n\t\tlog.Println(\"Unable to find metrics prefix using empty string\")\n\t\tmetricsPrefix = \"\"\n\t}\n\n\tbaseConfigInstance := &BaseConfigStruct{port, metricsServer, metricsKey, metricsPrefix}\n\treturn baseConfigInstance\n\n}\n\nfunc (this *BaseConfigStruct) MetricsAPIKey() string ", "output": "{\n\treturn this.MetricsAPIKeyValue\n}"} {"input": "package integration_test\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\n\n\nfunc TestApi(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Api Suite\")\n}"} {"input": "package env\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/golang/glog\"\n)\n\nvar (\n\tAuthBearerToken string\n\tSlackToken string\n\n\tServerHost string\n\n\tK8sServiceHost string\n\n\tK8sServicePort string\n\n\tK8sNamespace string\n\n\tEtcdHost string\n\n\tEtcdPath string\n\n\tSlackWebhook string\n\n\tManifestsPath string\n\n\tPlaybooksPath string\n)\n\nvar (\n\tcwd string\n\tdefaultManifestsPath string\n\tdefaultPlaybooksPath string\n)\n\n\n\n\nfunc loadw(key string) string {\n\tval, ok := os.LookupEnv(key)\n\tif !ok {\n\t\tglog.Warningf(\"Environment variable %s unset; defaulting to empty string\\n\", key)\n\t}\n\treturn val\n}\n\nfunc loadf(key string) string {\n\tval, ok := os.LookupEnv(key)\n\tif !ok {\n\t\tglog.Fatalf(\"Environment variable %s unset; Exiting.n\", key)\n\t}\n\treturn val\n}\n\nfunc init() {\n\tif d, err := os.Getwd(); err == nil {\n\t\tcwd = d\n\t}\n\tdefaultManifestsPath = filepath.Join(cwd, \"manifests\")\n\tdefaultPlaybooksPath = filepath.Join(cwd, \"playbooks\")\n\tLoadEnvs()\n}\n\nfunc LoadEnvs() ", "output": "{\n\tManifestsPath = loadw(\"BROADWAY_MANIFESTS_PATH\")\n\tif ManifestsPath == \"\" {\n\t\tManifestsPath = defaultManifestsPath\n\t}\n\tPlaybooksPath = loadw(\"BROADWAY_PLAYBOOKS_PATH\")\n\tif PlaybooksPath == \"\" {\n\t\tPlaybooksPath = defaultPlaybooksPath\n\t}\n\tAuthBearerToken = loadw(\"BROADWAY_AUTH_TOKEN\")\n\n\tServerHost = loadw(\"HOST\")\n\n\tSlackWebhook = loadw(\"SLACK_WEBHOOK\")\n\tSlackToken = loadw(\"SLACK_VERIFICATION_TOKEN\")\n\n\tK8sServiceHost = loadw(\"KUBERNETES_SERVICE_HOST\")\n\tK8sServicePort = loadw(\"KUBERNETES_PORT_443_TCP_PORT\")\n\tK8sNamespace = loadf(\"KUBERNETES_NAMESPACE\")\n\n\tEtcdHost = loadw(\"ETCD_HOST\")\n\tEtcdPath = loadw(\"ETCD_PATH\")\n}"} {"input": "package render\n\nimport (\n\t\"runtime\"\n\t\"sync\"\n)\n\nvar (\n\trender_funcs chan func()\n\tpurge chan bool\n\tinit_once sync.Once\n)\n\nfunc init() {\n\trender_funcs = make(chan func(), 1000)\n\tpurge = make(chan bool)\n}\n\n\n\n\n\nfunc Purge() {\n\tpurge <- true\n\t<-purge\n}\n\nfunc Init() {\n\tinit_once.Do(func() {\n\t\tgo func() {\n\t\t\truntime.LockOSThread()\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase f := <-render_funcs:\n\t\t\t\t\tf()\n\t\t\t\tcase <-purge:\n\t\t\t\t\tfor {\n\t\t\t\t\t\tselect {\n\t\t\t\t\t\tcase f := <-render_funcs:\n\t\t\t\t\t\t\tf()\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tgoto purged\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tpurged:\n\t\t\t\t\tpurge <- true\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t})\n}\n\nfunc Queue(f func()) ", "output": "{\n\trender_funcs <- f\n}"} {"input": "package joltDB\n\nimport (\n\t\"github.com/boltdb/bolt\"\n)\n\nvar boltdbr *bolt.DB\nvar dbr = apiConn(boltdbr)\n\nfunc OpenReadOnly(dir string) error {\n\treturn dbr.apiOpenReadOnly(dir)\n}\n\nfunc CloseReadOnly() {\n\tdbr.apiClose()\n}\n\nfunc ListReadOnly(bucket string) ([]byte, error) {\n\treturn dbr.apiList(bucket)\n}\n\n\n\nfunc ListRangeReadOnly(bucket, start, stop string) ([]byte, error) {\n\treturn dbrw.apiListRange(bucket, start, stop)\n}\n\nfunc GetOneReadOnly(bucket, key string) ([]byte, error) {\n\treturn dbr.apiGetOne(bucket, key)\n}\n\nfunc ListPrefixReadOnly(bucket, prefix string) ([]byte, error) ", "output": "{\n\treturn dbrw.apiListPrefix(bucket, prefix)\n}"} {"input": "package subscribe\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"testing\"\n\n\t\"github.com/drausin/libri/libri/librarian/api\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestFromAPI_err(t *testing.T) {\n\tf, err := FromAPI(&api.BloomFilter{Encoded: []byte{}})\n\tassert.NotNil(t, err)\n\tassert.Nil(t, f)\n}\n\n\n\nfunc TestNewFPFilter(t *testing.T) {\n\trng := rand.New(rand.NewSource(0))\n\tnTrials := 100000\n\n\ttolerance := 0.05\n\tfor _, targetFP := range []float64{0.3, 0.5, 0.75, 0.9, 1.0} {\n\t\tfilter := newFilter([][]byte{}, targetFP, rng)\n\n\t\tfpCount := 0\n\t\tfor c := 0; c < nTrials; c++ {\n\t\t\tif filter.Test(api.RandBytes(rng, api.ECPubKeyLength)) {\n\t\t\t\tfpCount++\n\t\t\t}\n\t\t}\n\t\tmeasuredFP := float64(fpCount) / float64(nTrials)\n\t\tinfo := fmt.Sprintf(\"target fp: %f, measured fp: %f\", targetFP, measuredFP)\n\t\tassert.True(t, measuredFP >= targetFP-tolerance, info)\n\t}\n\n}\n\nfunc TestAlwaysInFilter(t *testing.T) {\n\trng := rand.New(rand.NewSource(0))\n\tf := alwaysInFilter()\n\tfor c := 0; c < 10000; c++ {\n\t\tin := f.Test(api.RandBytes(rng, api.ECPubKeyLength))\n\t\tassert.True(t, in)\n\t}\n}\n\nfunc TestToFromAPI(t *testing.T) ", "output": "{\n\trng := rand.New(rand.NewSource(0))\n\tf1 := newFilter([][]byte{}, 0.75, rng)\n\ta, err := ToAPI(f1)\n\tassert.Nil(t, err)\n\tf2, err := FromAPI(a)\n\tassert.Nil(t, err)\n\tassert.Equal(t, f1, f2)\n}"} {"input": "package model\n\nimport (\n\t\"github.com/Konstantin8105/GoFea/input/element\"\n\t\"github.com/Konstantin8105/GoFea/input/material\"\n)\n\ntype materialLinearGroup struct {\n\tmaterial material.Linear\n\telementIndex element.Index\n}\n\n\ntype materialByElement []materialLinearGroup\n\nfunc (a materialByElement) Len() int { return len(a) }\nfunc (a materialByElement) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a materialByElement) Less(i, j int) bool { return a[i].elementIndex < a[j].elementIndex }\n\nfunc (a materialByElement) Name(i int) int { return int(a[i].elementIndex) }\n\nfunc (a materialByElement) Equal(i, j int) bool ", "output": "{ return a[i].elementIndex == a[j].elementIndex }"} {"input": "package b\n\nimport \"a\"\n\nvar N n\n\ntype n struct{}\n\nfunc (r n) M1() int { return a.G1 }\n\nfunc (r n) M3() int { return a.G3 }\nfunc (r n) M4() int { return a.G4 }\nfunc (r n) M5() int { return a.G5 }\nfunc (r n) M6() int { return a.G6 }\nfunc (r n) M7() int { return a.G7 }\nfunc (r n) M8() int { return a.G8 }\nfunc (r n) M9() int { return a.G9 }\nfunc (r n) M10() int { return a.G10 }\n\nfunc (r n) M2() int ", "output": "{ return a.G2 }"} {"input": "package system\n\nimport \"strings\"\n\n\n\n\n\n\ntype Args []string\n\n\n\n\nfunc (a Args) Get(n int) string {\n\tif n >= 0 && n < len(a) {\n\t\treturn a[n]\n\t}\n\treturn \"\"\n}\n\n\nfunc (a Args) After() string {\n\treturn a.AfterN(0)\n}\n\n\n\n\n\nfunc (a Args) AfterN(n int) string ", "output": "{\n\tif n >= 0 && n < len(a) {\n\t\treturn strings.Join(a[n:], \" \")\n\t}\n\treturn \"\"\n}"} {"input": "package horenso\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\n\nfunc TestLoadConfig(t *testing.T) ", "output": "{\n\tc, err := loadConfig(\"testdata/config.yaml\")\n\tif err != nil {\n\t\tt.Errorf(\"failed to load config: %s\", err)\n\t}\n\texpect := config{\n\t\tReporter: []string{\"hoge\", \"fuga\"},\n\t\tNoticer: []string{\"bar\"},\n\t}\n\tif !reflect.DeepEqual(expect, *c) {\n\t\tt.Errorf(\"something went wrong\\n got: %#v\\nexpect: %#v\", *c, expect)\n\t}\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ListLocalPeeringGatewaysRequest struct {\n\n\tCompartmentId *string `mandatory:\"true\" contributesTo:\"query\" name:\"compartmentId\"`\n\n\tLimit *int `mandatory:\"false\" contributesTo:\"query\" name:\"limit\"`\n\n\tPage *string `mandatory:\"false\" contributesTo:\"query\" name:\"page\"`\n\n\tVcnId *string `mandatory:\"false\" contributesTo:\"query\" name:\"vcnId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ListLocalPeeringGatewaysRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request ListLocalPeeringGatewaysRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ListLocalPeeringGatewaysRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ListLocalPeeringGatewaysResponse struct {\n\n\tRawResponse *http.Response\n\n\tItems []LocalPeeringGateway `presentIn:\"body\"`\n\n\tOpcNextPage *string `presentIn:\"header\" name:\"opc-next-page\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ListLocalPeeringGatewaysResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ListLocalPeeringGatewaysResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ListLocalPeeringGatewaysRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}"} {"input": "package iso20022\n\n\ntype AutomatedTellerMachine6 struct {\n\n\tIdentification *Max35Text `xml:\"Id\"`\n\n\tAdditionalIdentification *Max35Text `xml:\"AddtlId,omitempty\"`\n\n\tSequenceNumber *Max35Text `xml:\"SeqNb,omitempty\"`\n\n\tLocation *PostalAddress17 `xml:\"Lctn,omitempty\"`\n\n\tLocationCategory *TransactionEnvironment2Code `xml:\"LctnCtgy,omitempty\"`\n\n\tEquipment *ATMEquipment1 `xml:\"Eqpmnt,omitempty\"`\n}\n\nfunc (a *AutomatedTellerMachine6) SetIdentification(value string) {\n\ta.Identification = (*Max35Text)(&value)\n}\n\nfunc (a *AutomatedTellerMachine6) SetAdditionalIdentification(value string) {\n\ta.AdditionalIdentification = (*Max35Text)(&value)\n}\n\nfunc (a *AutomatedTellerMachine6) SetSequenceNumber(value string) {\n\ta.SequenceNumber = (*Max35Text)(&value)\n}\n\nfunc (a *AutomatedTellerMachine6) AddLocation() *PostalAddress17 {\n\ta.Location = new(PostalAddress17)\n\treturn a.Location\n}\n\n\n\nfunc (a *AutomatedTellerMachine6) AddEquipment() *ATMEquipment1 {\n\ta.Equipment = new(ATMEquipment1)\n\treturn a.Equipment\n}\n\nfunc (a *AutomatedTellerMachine6) SetLocationCategory(value string) ", "output": "{\n\ta.LocationCategory = (*TransactionEnvironment2Code)(&value)\n}"} {"input": "package main\n\nimport (\n\t\"math\"\n\t\"sort\"\n)\n\ntype NaiveSieve struct {\n\tsieve map[int]bool\n}\n\nfunc NewNaiveSieve(limit int) NaiveSieve {\n\n\tprimes := make(map[int]bool)\n\n\tprimes[2] = true\n\n\tfor n := 3; n < limit; n += 2 {\n\t\tif IsNaivePrime(n) {\n\t\t\tprimes[n] = true\n\t\t}\n\t}\n\n\treturn NaiveSieve{primes}\n}\n\n\n\nfunc (self *NaiveSieve) Primes() []int {\n\tprimes := make([]int, 0, len(self.sieve))\n\tfor n, _ := range self.sieve {\n\t\tprimes = append(primes, n)\n\t}\n\tsort.Ints(primes)\n\treturn primes\n}\n\nfunc IsNaivePrime(n int) bool {\n\tswitch {\n\tcase n == 1:\n\t\treturn false\n\tcase n == 2:\n\t\treturn true\n\tcase n%2 == 0:\n\t\treturn false\n\t}\n\n\tlimit := int(math.Sqrt(float64(n)))\n\n\tfor i := 3; i <= limit; i += 2 {\n\t\tif n%i == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (self *NaiveSieve) Contains(n int) bool ", "output": "{\n\t_, ok := self.sieve[n]\n\treturn ok\n}"} {"input": "package dfa\n\nimport (\n\t\"fmt\"\n\t\"unicode\"\n)\n\nfunc charClass(name string) (m *M, err error) {\n\tms := []*M{}\n\terr = eachRangeInCharClass(name, func(lo, hi rune) {\n\t\tms = append(ms, Between(lo, hi))\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tm, err = orMany(ms)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn m.minimize()\n}\n\nfunc eachRangeInCharClass(name string, visit func(lo, hi rune)) error {\n\ttable := unicode.Categories[name]\n\tif table == nil {\n\t\ttable = unicode.Scripts[name]\n\t\tif table == nil {\n\t\t\treturn fmt.Errorf(\"character class %s not exists\", name)\n\t\t}\n\t}\n\n\tfor _, xr := range table.R16 {\n\t\teachRangeWithStride(rune(xr.Lo), rune(xr.Hi), rune(xr.Stride), visit)\n\t}\n\tfor _, xr := range table.R32 {\n\t\teachRangeWithStride(rune(xr.Lo), rune(xr.Hi), rune(xr.Stride), visit)\n\t}\n\treturn nil\n}\n\n\nfunc eachRangeWithStride(lo, hi, stride rune, visit func(lo, hi rune)) ", "output": "{\n\tif stride == 1 {\n\t\tvisit(lo, hi)\n\t} else {\n\t\tfor c := lo; c <= hi; c += stride {\n\t\t\tvisit(c, c)\n\t\t}\n\t}\n}"} {"input": "package signature\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha256\"\n\t\"log\"\n\n\t\"github.com/cloudfoundry/dropsonde/metrics\"\n)\n\nconst SIGNATURE_LENGTH = 32\n\n\n\ntype Verifier struct {\n\tsharedSecret string\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (v *Verifier) Run(inputChan <-chan []byte, outputChan chan<- []byte) {\n\tfor signedMessage := range inputChan {\n\t\tif len(signedMessage) < SIGNATURE_LENGTH {\n\t\t\tlog.Print(\"signatureVerifier: missing signature\")\n\t\t\tcontinue\n\t\t}\n\n\t\tsignature, message := signedMessage[:SIGNATURE_LENGTH], signedMessage[SIGNATURE_LENGTH:]\n\t\tif v.verifyMessage(message, signature) {\n\t\t\toutputChan <- message\n\t\t\tmetrics.BatchIncrementCounter(\"signatureVerifier.validSignatures\")\n\t\t} else {\n\t\t\tlog.Print(\"signatureVerifier: invalid signature\")\n\t\t}\n\t}\n}\n\nfunc (v *Verifier) verifyMessage(message, signature []byte) bool {\n\texpectedMAC := generateSignature(message, []byte(v.sharedSecret))\n\treturn hmac.Equal(signature, expectedMAC)\n}\n\n\n\nfunc SignMessage(message, secret []byte) []byte {\n\tsignature := generateSignature(message, secret)\n\treturn append(signature, message...)\n}\n\nfunc generateSignature(message, secret []byte) []byte {\n\tmac := hmac.New(sha256.New, secret)\n\tmac.Write(message)\n\treturn mac.Sum(nil)\n}\n\nfunc NewVerifier(sharedSecret string) *Verifier ", "output": "{\n\treturn &Verifier{\n\t\tsharedSecret: sharedSecret,\n\t}\n}"} {"input": "package envstruct_test\n\ntype mockUnmarshaller struct {\n\tUnmarshalEnvCalled chan bool\n\tUnmarshalEnvInput struct {\n\t\tV chan string\n\t}\n\tUnmarshalEnvOutput struct {\n\t\tRet0 chan error\n\t}\n}\n\nfunc newMockUnmarshaller() *mockUnmarshaller {\n\tm := &mockUnmarshaller{}\n\tm.UnmarshalEnvCalled = make(chan bool, 100)\n\tm.UnmarshalEnvInput.V = make(chan string, 100)\n\tm.UnmarshalEnvOutput.Ret0 = make(chan error, 100)\n\treturn m\n}\n\n\nfunc (m *mockUnmarshaller) UnmarshalEnv(v string) error ", "output": "{\n\tm.UnmarshalEnvCalled <- true\n\tm.UnmarshalEnvInput.V <- v\n\treturn <-m.UnmarshalEnvOutput.Ret0\n}"} {"input": "package awstasks\n\nimport (\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/service/ec2\"\n)\n\nfunc mapEC2TagsToMap(tags []*ec2.Tag) map[string]string {\n\tif tags == nil {\n\t\treturn nil\n\t}\n\tm := make(map[string]string)\n\tfor _, t := range tags {\n\t\tm[aws.StringValue(t.Key)] = aws.StringValue(t.Value)\n\t}\n\treturn m\n}\n\nfunc findNameTag(tags []*ec2.Tag) *string {\n\tfor _, tag := range tags {\n\t\tif aws.StringValue(tag.Key) == \"Name\" {\n\t\t\treturn tag.Value\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc intersectTags(tags []*ec2.Tag, desired map[string]string) map[string]string ", "output": "{\n\tif tags == nil {\n\t\treturn nil\n\t}\n\tactual := make(map[string]string)\n\tfor _, t := range tags {\n\t\tk := aws.StringValue(t.Key)\n\t\tv := aws.StringValue(t.Value)\n\n\t\tif _, found := desired[k]; found {\n\t\t\tactual[k] = v\n\t\t}\n\t}\n\tif len(actual) == 0 && desired == nil {\n\t\treturn nil\n\t}\n\treturn actual\n}"} {"input": "package job\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/kubernetes/pkg/api/v1\"\n\tbatch \"k8s.io/kubernetes/pkg/apis/batch/v1\"\n)\n\nfunc IsJobFinished(j *batch.Job) bool {\n\tfor _, c := range j.Status.Conditions {\n\t\tif (c.Type == batch.JobComplete || c.Type == batch.JobFailed) && c.Status == v1.ConditionTrue {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\nfunc newControllerRef(j *batch.Job) *metav1.OwnerReference ", "output": "{\n\tblockOwnerDeletion := true\n\tisController := true\n\treturn &metav1.OwnerReference{\n\t\tAPIVersion: controllerKind.GroupVersion().String(),\n\t\tKind: controllerKind.Kind,\n\t\tName: j.Name,\n\t\tUID: j.UID,\n\t\tBlockOwnerDeletion: &blockOwnerDeletion,\n\t\tController: &isController,\n\t}\n}"} {"input": "package quotedprintable\n\nimport (\n\t\"bytes\"\n\t\"sync\"\n)\n\nvar bufPool = sync.Pool{\n\tNew: func() interface{} {\n\t\treturn new(bytes.Buffer)\n\t},\n}\n\n\n\nfunc putBuffer(buf *bytes.Buffer) {\n\tif buf.Len() > 1024 {\n\t\treturn\n\t}\n\tbuf.Reset()\n\tbufPool.Put(buf)\n}\n\nfunc getBuffer() *bytes.Buffer ", "output": "{\n\treturn bufPool.Get().(*bytes.Buffer)\n}"} {"input": "package lua\n\ntype Metatable struct {\n IndexFunc Function\n NewindexFunc Function\n TostringFunc Function \n GCFunc Function\n}\n\nfunc (this *Metatable) Index() Function {\n return this.IndexFunc\n}\n\n\n\nfunc (this *Metatable) Tostring() Function {\n return this.TostringFunc\n}\n\nfunc (this *Metatable) GC() Function {\n return this.GCFunc\n}\n\nfunc (this *Metatable) Newindex() Function ", "output": "{\n return this.NewindexFunc\n}"} {"input": "package logical\n\ntype HTTPCodedError interface {\n\tError() string\n\tCode() int\n}\n\nfunc CodedError(status int, msg string) HTTPCodedError {\n\treturn &codedError{\n\t\tStatus: status,\n\t\tMessage: msg,\n\t}\n}\n\ntype codedError struct {\n\tStatus int\n\tMessage string\n}\n\nfunc (e *codedError) Error() string {\n\treturn e.Message\n}\n\n\n\n\n\ntype StatusBadRequest struct {\n\tErr string\n}\n\n\nfunc (s *StatusBadRequest) Error() string {\n\treturn s.Err\n}\n\n\n\n\n\ntype ReplicationCodedError struct {\n\tMsg string\n\tCode int\n}\n\nfunc (r *ReplicationCodedError) Error() string {\n\treturn r.Msg\n}\n\nfunc (e *codedError) Code() int ", "output": "{\n\treturn e.Status\n}"} {"input": "package iff\n\nimport (\n\t\"encoding/binary\"\n\t\"io\"\n)\n\ntype Writer struct {\n\tio.Writer\n}\n\ntype writeCallback func(w io.Writer)\n\n\n\nfunc (w *Writer) WriteChunk(chunkID []byte, chunkSize uint32, cb writeCallback) (err error) {\n\t_, err = w.Write(chunkID)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = binary.Write(w, binary.BigEndian, chunkSize)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tcb(w)\n\n\treturn\n}\n\nfunc NewWriter(w io.Writer, fileType []byte, fileSize uint32) *Writer ", "output": "{\n\tw.Write([]byte(\"FORM\"))\n\tbinary.Write(w, binary.BigEndian, fileSize)\n\tw.Write(fileType)\n\n\treturn &Writer{w}\n}"} {"input": "package jobs\n\nimport (\n\t\"github.com/square/spincycle/v2/job\"\n)\n\n\n\nvar Factory job.Factory = empty{}\n\ntype empty struct{}\n\n\n\nfunc (empty) Make(_ job.Id) (job.Job, error) ", "output": "{\n\tpanic(\"replace the spincycle jobs package with your own implementation\")\n}"} {"input": "package scriptbenchmark\n\nimport (\n\t\"github.com/robertkrimen/otto\"\n\t\"testing\"\n)\n\n\n\nfunc BenchmarkOttoCallAddN(b *testing.B) {\n\to := otto.New()\n\t_, err := o.Run(`\n\tfunction add(x, y) {\n\t\treturn x+y;\n\t}\n\n\tfunction addn(n, x, y) {\n\t\tfor (var i = 0; i < n; i++) {\n\t\t\tadd(x, y);\n\t\t}\n\t\treturn n;\n\t}\n\t`)\n\tassert(b, err)\n\n\tb.ResetTimer()\n\n\tvalue, err := o.Call(\"addn\", nil, b.N, 21, 21)\n\tassert(b, err)\n\tfv, err := value.ToFloat()\n\tassert(b, err)\n\tassert(b, isTrue(\"addn(n,...) == n\", fv == float64(b.N)))\n}\n\nfunc BenchmarkOttoCallAdd(b *testing.B) ", "output": "{\n\to := otto.New()\n\t_, err := o.Run(`\n\tfunction add(x, y) {\n\t\treturn x+y;\n\t}\n\t`)\n\tassert(b, err)\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tvalue, err := o.Call(\"add\", nil, 21, 21)\n\t\tassert(b, err)\n\t\tfv, err := value.ToFloat()\n\t\tassert(b, err)\n\t\tassert(b, isTrue(\"add(21,21) == 42\", fv == 42))\n\t}\n}"} {"input": "package bc\n\nimport \"io\"\n\nfunc (VoteOutput) typ() string { return \"voteOutput1\" }\n\n\n\nfunc NewVoteOutput(source *ValueSource, controlProgram *Program, stateData [][]byte, ordinal uint64, vote []byte) *VoteOutput {\n\treturn &VoteOutput{\n\t\tSource: source,\n\t\tControlProgram: controlProgram,\n\t\tOrdinal: ordinal,\n\t\tVote: vote,\n\t\tStateData: stateData,\n\t}\n}\n\nfunc (o *VoteOutput) writeForHash(w io.Writer) ", "output": "{\n\tmustWriteForHash(w, o.Source)\n\tmustWriteForHash(w, o.ControlProgram)\n\tmustWriteForHash(w, o.Vote)\n\tmustWriteForHash(w, o.StateData)\n}"} {"input": "package dashing\n\nimport (\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n\n\ntype Event struct {\n\tID string\n\tBody map[string]interface{}\n\tTarget string\n}\n\n\ntype Dashing struct {\n\tstarted bool\n\tBroker *Broker\n\tWorker *Worker\n\tServer *Server\n\tRouter http.Handler\n}\n\n\nfunc (d *Dashing) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tif !d.started {\n\t\tpanic(\"dashing.Start() has not been called\")\n\t}\n\td.Router.ServeHTTP(w, r)\n}\n\n\n\n\n\nfunc NewDashing() *Dashing {\n\tbroker := NewBroker()\n\tworker := NewWorker(broker)\n\tserver := NewServer(broker)\n\n\tif os.Getenv(\"WEBROOT\") != \"\" {\n\t\tserver.webroot = filepath.Clean(os.Getenv(\"WEBROOT\")) + \"/\"\n\t}\n\tif os.Getenv(\"DEV\") != \"\" {\n\t\tserver.dev = true\n\t}\n\n\treturn &Dashing{\n\t\tstarted: false,\n\t\tBroker: broker,\n\t\tWorker: worker,\n\t\tServer: server,\n\t}\n}\n\nfunc (d *Dashing) Start() *Dashing ", "output": "{\n\tif !d.started {\n\t\tif d.Router == nil {\n\t\t\td.Router = d.Server.NewRouter()\n\t\t}\n\t\td.Broker.Start()\n\t\td.Worker.Start()\n\t\td.started = true\n\t}\n\treturn d\n}"} {"input": "package solid\n\nimport \"github.com/cpmech/gosl/chk\"\n\n\ntype OnedState struct {\n\n\tSig float64 \n\n\tAlp []float64 \n\tDgam float64 \n\tLoading bool \n\n\tPhi []float64 \n\n\tF float64 \n}\n\n\n\n\n\n\n\n\nfunc (o *OnedState) Set(other *OnedState) {\n\to.Sig = other.Sig\n\to.Dgam = other.Dgam\n\to.Loading = other.Loading\n\tchk.IntAssert(len(o.Alp), len(other.Alp))\n\tchk.IntAssert(len(o.Phi), len(other.Phi))\n\tcopy(o.Alp, other.Alp)\n\tcopy(o.Phi, other.Phi)\n\to.F = other.F\n}\n\n\nfunc (o *OnedState) GetCopy() *OnedState {\n\tother := NewOnedState(len(o.Alp), len(o.Phi))\n\tother.Set(o)\n\treturn other\n}\n\nfunc NewOnedState(nalp, nphi int) *OnedState ", "output": "{\n\tvar state OnedState\n\tif nalp > 0 {\n\t\tstate.Alp = make([]float64, nalp)\n\t}\n\tif nphi > 0 {\n\t\tstate.Phi = make([]float64, nphi)\n\t}\n\treturn &state\n}"} {"input": "package datastore\n\nimport \"strconv\"\n\n\n\nconst _PropertyType_name = \"PTNullPTIntPTTimePTBoolPTBytesPTStringPTFloatPTGeoPointPTKeyPTBlobKeyPTPropertyMapPTUnknown\"\n\nvar _PropertyType_index = [...]uint8{0, 6, 11, 17, 23, 30, 38, 45, 55, 60, 69, 82, 91}\n\nfunc (i PropertyType) String() string {\n\tif i >= PropertyType(len(_PropertyType_index)-1) {\n\t\treturn \"PropertyType(\" + strconv.FormatInt(int64(i), 10) + \")\"\n\t}\n\treturn _PropertyType_name[_PropertyType_index[i]:_PropertyType_index[i+1]]\n}\n\nfunc _() ", "output": "{\n\tvar x [1]struct{}\n\t_ = x[PTNull-0]\n\t_ = x[PTInt-1]\n\t_ = x[PTTime-2]\n\t_ = x[PTBool-3]\n\t_ = x[PTBytes-4]\n\t_ = x[PTString-5]\n\t_ = x[PTFloat-6]\n\t_ = x[PTGeoPoint-7]\n\t_ = x[PTKey-8]\n\t_ = x[PTBlobKey-9]\n\t_ = x[PTPropertyMap-10]\n\t_ = x[PTUnknown-11]\n}"} {"input": "package apiv1\n\nimport (\n\t\"encoding/json\"\n)\n\ntype DiskHint struct {\n\tval interface{}\n}\n\nvar _ json.Unmarshaler = &DiskHint{}\nvar _ json.Marshaler = DiskHint{}\n\nfunc NewDiskHintFromString(val string) DiskHint {\n\treturn DiskHint{val}\n}\n\nfunc NewDiskHintFromMap(val map[string]interface{}) DiskHint {\n\treturn DiskHint{val}\n}\n\nfunc (i *DiskHint) UnmarshalJSON(data []byte) error {\n\tvar val interface{}\n\n\terr := json.Unmarshal(data, &val)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*i = DiskHint{val}\n\n\treturn nil\n}\n\n\n\nfunc (i DiskHint) MarshalJSON() ([]byte, error) ", "output": "{\n\treturn json.Marshal(i.val)\n}"} {"input": "package errors\n\nimport (\n\t\"errors\"\n)\n\nconst callStackDepth = 10\n\ntype DetailError interface {\n\terror\n\tErrCoder\n\tCallStacker\n\tGetRoot() error\n}\n\n\n\n\nfunc NewDetailErr(err error,errcode ErrCode,errmsg string) DetailError{\n\tif err == nil {return nil}\n\n\tdnaerr, ok := err.(dnaError)\n\tif !ok {\n\t\tdnaerr.root = err\n\t\tdnaerr.errmsg = err.Error()\n\t\tdnaerr.callstack = getCallStack(0, callStackDepth)\n\t\tdnaerr.code = errcode\n\n\t}\n\tif errmsg != \"\" {\n\t\tdnaerr.errmsg = errmsg + \": \" + dnaerr.errmsg\n\t}\n\n\n\treturn dnaerr\n}\n\nfunc RootErr(err error) error {\n\tif err, ok := err.(DetailError); ok {\n\t\treturn err.GetRoot()\n\t}\n\treturn err\n}\n\nfunc NewErr(errmsg string) error ", "output": "{\n\treturn errors.New(errmsg)\n}"} {"input": "package options\n\n\ntype UpdateOptions struct {\n\tArrayFilters *ArrayFilters\n\n\tBypassDocumentValidation *bool\n\n\tCollation *Collation\n\n\tHint interface{}\n\n\tUpsert *bool\n}\n\n\nfunc Update() *UpdateOptions {\n\treturn &UpdateOptions{}\n}\n\n\n\n\n\nfunc (uo *UpdateOptions) SetBypassDocumentValidation(b bool) *UpdateOptions {\n\tuo.BypassDocumentValidation = &b\n\treturn uo\n}\n\n\nfunc (uo *UpdateOptions) SetCollation(c *Collation) *UpdateOptions {\n\tuo.Collation = c\n\treturn uo\n}\n\n\nfunc (uo *UpdateOptions) SetHint(h interface{}) *UpdateOptions {\n\tuo.Hint = h\n\treturn uo\n}\n\n\nfunc (uo *UpdateOptions) SetUpsert(b bool) *UpdateOptions {\n\tuo.Upsert = &b\n\treturn uo\n}\n\n\nfunc MergeUpdateOptions(opts ...*UpdateOptions) *UpdateOptions {\n\tuOpts := Update()\n\tfor _, uo := range opts {\n\t\tif uo == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif uo.ArrayFilters != nil {\n\t\t\tuOpts.ArrayFilters = uo.ArrayFilters\n\t\t}\n\t\tif uo.BypassDocumentValidation != nil {\n\t\t\tuOpts.BypassDocumentValidation = uo.BypassDocumentValidation\n\t\t}\n\t\tif uo.Collation != nil {\n\t\t\tuOpts.Collation = uo.Collation\n\t\t}\n\t\tif uo.Hint != nil {\n\t\t\tuOpts.Hint = uo.Hint\n\t\t}\n\t\tif uo.Upsert != nil {\n\t\t\tuOpts.Upsert = uo.Upsert\n\t\t}\n\t}\n\n\treturn uOpts\n}\n\nfunc (uo *UpdateOptions) SetArrayFilters(af ArrayFilters) *UpdateOptions ", "output": "{\n\tuo.ArrayFilters = &af\n\treturn uo\n}"} {"input": "package evm\n\nimport (\n\t\"math/big\"\n\t\"DNA/vm/evm/common\"\n)\n\n\n\nfunc memoryMStore(stack *Stack) *big.Int ", "output": "{\n\treturn common.CalcMemSize(stack.Back(0), big.NewInt(32))\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype LockeAble struct {\n\tsync.Mutex\n\treadableInt int\n\treadableString string\n}\n\nfunc main() {\n\tl := &LockeAble{}\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(time.Second * 15)\n\t\t\tl.read(\"one\")\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(time.Second * 10)\n\t\t\tl.write(\"two\", \"hello\", 5)\n\t\t}\n\t}()\n\n\tl.Lock()\n\tl.Unlock()\n\tl.read(\"one\")\n\n\tselect {}\n}\n\nfunc (l *LockeAble) read(st string) {\n\tl.Lock()\n\tfmt.Println(\"just Locked by\", st, \"for reading\")\n\tfmt.Println(l.readableInt, l.readableString)\n\tl.Unlock()\n\tfmt.Println(\"just UnLocked\", st, \"from reading\")\n}\n\n\n\nfunc (l *LockeAble) write(st string, val string, valInt int) ", "output": "{\n\tl.Lock()\n\tfmt.Println(\"just Locked by\", st, \"for writing\")\n\tl.readableString = val\n\tl.readableInt = valInt\n\tl.Unlock()\n\tfmt.Println(\"just UnLocked\", st, \"from writing\")\n}"} {"input": "package gota\n\n\ntype RSI struct {\n\temaUp EMA\n\temaDown EMA\n\tlastV float64\n}\n\n\nfunc NewRSI(inTimePeriod int, warmType WarmupType) *RSI {\n\tema := NewEMA(inTimePeriod+1, warmType)\n\tema.alpha = float64(1) / float64(inTimePeriod)\n\treturn &RSI{\n\t\temaUp: *ema,\n\t\temaDown: *ema,\n\t}\n}\n\n\n\n\n\nfunc (rsi RSI) Warmed() bool {\n\treturn rsi.emaUp.Warmed()\n}\n\n\nfunc (rsi RSI) Last() float64 {\n\treturn 100 - (100 / (1 + rsi.emaUp.Last()/rsi.emaDown.Last()))\n}\n\n\nfunc (rsi *RSI) Add(v float64) float64 {\n\tvar up float64\n\tvar down float64\n\tif v > rsi.lastV {\n\t\tup = v - rsi.lastV\n\t} else if v < rsi.lastV {\n\t\tdown = rsi.lastV - v\n\t}\n\trsi.emaUp.Add(up)\n\trsi.emaDown.Add(down)\n\trsi.lastV = v\n\treturn rsi.Last()\n}\n\nfunc (rsi RSI) WarmCount() int ", "output": "{\n\treturn rsi.emaUp.WarmCount()\n}"} {"input": "package zipkin\n\nimport (\n\t\"github.com/jaegertracing/jaeger/thrift-gen/zipkincore\"\n)\n\n\n\n\n\nfunc IsClientCore(anno string) bool {\n\treturn anno == zipkincore.CLIENT_SEND || anno == zipkincore.CLIENT_RECV\n}\n\n\nfunc IsCore(anno string) bool {\n\treturn IsServerCore(anno) || IsClientCore(anno)\n}\n\n\nfunc FindServiceName(span *zipkincore.Span) string {\n\tfor _, anno := range span.Annotations {\n\t\tendpoint := anno.GetHost()\n\t\tif endpoint == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif IsCore(anno.Value) && endpoint.GetServiceName() != \"\" {\n\t\t\treturn endpoint.GetServiceName()\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc IsServerCore(anno string) bool ", "output": "{\n\treturn anno == zipkincore.SERVER_SEND || anno == zipkincore.SERVER_RECV\n}"} {"input": "package csl\nimport (\n\t\"github.com/abieberbach/goplane/extra/logging\"\n\t\"fmt\"\n)\n\ntype CslPackage struct {\n\tName string\n\tDependencies []string\n\tBaseDirectory string\n\tAircrafts []*CslAircraft\n\tValid bool\n}\n\nfunc (self *CslPackage) validate(allPackages *CslPackages) {\n\tself.checkDependencies(allPackages)\n\tif !self.Valid {\n\t\treturn\n\t}\n\tself.checkAircrafts(allPackages)\n\tif !self.Valid {\n\t\treturn\n\t}\n\tlogging.Infof(\"package \\\"%v\\\" is valid\", self.Name)\n}\n\n\n\nfunc (self *CslPackage) checkAircrafts(allPackages *CslPackages) {\n\tfor _, currentAircraft := range self.Aircrafts {\n\t\tok,validationMessage := currentAircraft.validate(allPackages)\n\t\tif !ok {\n\t\t\tself.invalidate(validationMessage)\n\t\t}\n\t}\n}\n\nfunc (self *CslPackage) invalidate(msg string, params... interface{}) {\n\tlogging.Warningf(\"invalid package \\\"%v\\\", reason: %v [base directory: %v]\", self.Name, fmt.Sprintf(msg, params...),self.BaseDirectory)\n\tself.Valid = false\n}\n\nfunc (self *CslPackage) checkDependencies(allPackages *CslPackages) ", "output": "{\n\tfor _, dep := range self.Dependencies {\n\t\t_, found := allPackages.GetPackage(dep)\n\t\tif !found {\n\t\t\tself.invalidate(\"missing dependency package \\\"%v\\\"\", dep)\n\t\t}\n\t}\n}"} {"input": "package trie\n\nimport \"fmt\"\n\ntype FullNode struct {\n\ttrie *Trie\n\tnodes [17]Node\n}\n\nfunc NewFullNode(t *Trie) *FullNode {\n\treturn &FullNode{trie: t}\n}\n\nfunc (self *FullNode) Dirty() bool { return true }\nfunc (self *FullNode) Value() Node {\n\tself.nodes[16] = self.trie.trans(self.nodes[16])\n\treturn self.nodes[16]\n}\nfunc (self *FullNode) Branches() []Node {\n\treturn self.nodes[:16]\n}\n\nfunc (self *FullNode) Copy(t *Trie) Node {\n\tnnode := NewFullNode(t)\n\tfor i, node := range self.nodes {\n\t\tif node != nil {\n\t\t\tnnode.nodes[i] = node.Copy(t)\n\t\t}\n\t}\n\n\treturn nnode\n}\n\n\nfunc (self *FullNode) Len() (amount int) {\n\tfor _, node := range self.nodes {\n\t\tif node != nil {\n\t\t\tamount++\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (self *FullNode) Hash() interface{} {\n\treturn self.trie.store(self)\n}\n\nfunc (self *FullNode) RlpData() interface{} {\n\tt := make([]interface{}, 17)\n\tfor i, node := range self.nodes {\n\t\tif node != nil {\n\t\t\tt[i] = node.Hash()\n\t\t} else {\n\t\t\tt[i] = \"\"\n\t\t}\n\t}\n\n\treturn t\n}\n\nfunc (self *FullNode) set(k byte, value Node) {\n\tif _, ok := value.(*ValueNode); ok && k != 16 {\n\t\tfmt.Println(value, k)\n\t}\n\n\tself.nodes[int(k)] = value\n}\n\n\n\nfunc (self *FullNode) branch(i byte) Node ", "output": "{\n\tif self.nodes[int(i)] != nil {\n\t\tself.nodes[int(i)] = self.trie.trans(self.nodes[int(i)])\n\n\t\treturn self.nodes[int(i)]\n\t}\n\treturn nil\n}"} {"input": "package cli\n\nimport (\n\t\"os\"\n\t\"fmt\"\n)\n\n\ntype Cmd interface {\n\tKey() string\n\tDescription() string\n\tExecute(args []string) error\n\tPrintUsage()\n}\n\n\n\ntype CmdHandler interface {\n\tRegisterCmd(Cmd)\n\tHandle()\n\tHandleCmd(key string, args []string)\n\tPrintUsage()\n}\n\n\nfunc NewCmdHandler() CmdHandler {\n\th := initCmdHandler()\n\th.RegisterCmd(NewBuildCmd())\n\treturn h\n}\n\nfunc initCmdHandler() *cmdHandler {\n\th := new(cmdHandler)\n\th.cmds = make(map[string]Cmd)\n\treturn h\n}\n\ntype cmdHandler struct {\n\tcmds map[string]Cmd\n}\n\n\n\nfunc (h *cmdHandler) Handle() {\n\targs := os.Args\n\tif args == nil || len(args) < 2 {\n\t\th.handleUsageError(\"Insufficient arguments\")\n\t\treturn\n\t} \n\tkey := args[1]\n\tcmdArgs := args[2:]\n\th.HandleCmd(key, cmdArgs)\n}\n\nfunc (h *cmdHandler) PrintUsage() {\n}\n\nfunc (h *cmdHandler) HandleCmd(key string, args []string) {\n\tcmd := h.cmds[key]\n\tif cmd == nil {\n\t\th.handleUsageError(\"Unrecognized command: \" + key)\n\t\treturn\n\t}\n\terr := cmd.Execute(args)\n\tif err != nil {\n\t\th.handleError(err)\n\t}\n}\n\n\nfunc (h *cmdHandler) handleUsageError(message string) {\n\tfmt.Println(message)\n\th.PrintUsage()\n}\n\n\nfunc (h *cmdHandler) handleError(err error) {\n\tfmt.Println(err)\n}\n\nfunc (h *cmdHandler) RegisterCmd(cmd Cmd) ", "output": "{\n\tkey := cmd.Key()\n\th.cmds[key] = cmd\n}"} {"input": "package commands\n\nimport (\n\t\"fmt\"\n\n\tapi \"github.com/pagodabox/pagodabox-api-client\"\n\t\"github.com/pagodabox/pagodabox-cli/helpers\"\n\t\"github.com/pagodabox/pagodabox-cli/ui\"\n)\n\n\ntype AppListCommand struct{}\n\n\n\n\n\nfunc (c *AppListCommand) Run(fApp string, opts []string) {\n\n\tapps, err := api.GetApps()\n\tif err != nil {\n\t\tui.LogFatal(\"[commands.app_list] api.GetApps() failed\", err)\n\t}\n\n\troles, err := api.GetUserRoles()\n\tif err != nil {\n\t\tui.LogFatal(\"[commands.app_list] api.GetUserRoles() failed\", err)\n\t}\n\n\trolesMap := make(map[string]string)\n\tfor _, role := range roles {\n\t\trolesMap[role.AppID] = role.Permission\n\t}\n\n\tfmt.Println(`\nApps : * tinker app\n--------------------------------------------------------------------------------`)\n\n\tvar appFlation, appType string\n\n\tfor _, app := range apps {\n\n\t\tappFlation = helpers.DetermineAppFlation(app.Flation)\n\t\tappType = helpers.DetermineAppType(app.Free)\n\n\t\tfmt.Printf(\"%-35v %12v %12v %12v\\n\", fmt.Sprintf(\"%v%v\", app.Name, appType), rolesMap[app.ID], appFlation, app.State)\n\t}\n\n\tfmt.Println(\"\")\n}\n\nfunc (c *AppListCommand) Help() ", "output": "{\n\tui.CPrint(`\nDescription:\n Lists all of your applications.\n\n name:\n The name's of your applications.\n\n role:\n Your access level in relation to the app.\n\n owner : Full permissions\n manager : CANNOT delete the app or modify billing info\n developer : CAN push, pull, and deploy code only.\n\n state:\n \tThe current state of the app.\n\n \tcreated - App exists, but has no code deployed\n active - App exists, and has been deployed to\n asleep - A sleeping 'tinker' app\n inactive - App is being/has been deleted\n hibernated - App is disabled due to deliquency\n\nUsage:\n pagoda list\n pagoda app:list\n\n ex. pagoda list\n\t`)\n}"} {"input": "package engine\n\nimport (\n\t\"time\"\n\n\t\"github.com/aws/amazon-ecs-agent/agent/api\"\n)\n\n\n\ntype impossibleTransitionError struct {\n\tstate api.ContainerStatus\n}\n\nfunc (err *impossibleTransitionError) Error() string {\n\treturn \"Cannot transition to \" + err.state.String()\n}\nfunc (err *impossibleTransitionError) ErrorName() string { return \"ImpossibleStateTransitionError\" }\n\ntype DockerTimeoutError struct {\n\tduration time.Duration\n\ttransition string\n}\n\nfunc (err *DockerTimeoutError) Error() string {\n\treturn \"Could not transition to \" + err.transition + \"; timed out after waiting \" + err.duration.String()\n}\n\n\ntype ContainerVanishedError struct{}\n\nfunc (err ContainerVanishedError) Error() string { return \"No container matching saved ID found\" }\nfunc (err ContainerVanishedError) ErrorName() string { return \"ContainerVanishedError\" }\n\ntype CannotXContainerError struct {\n\ttransition string\n\tmsg string\n}\n\nfunc (err CannotXContainerError) Error() string { return err.msg }\nfunc (err CannotXContainerError) ErrorName() string {\n\treturn \"Cannot\" + err.transition + \"ContainerError\"\n}\n\ntype OutOfMemoryError struct{}\n\nfunc (err OutOfMemoryError) Error() string { return \"Container killed due to memory usage\" }\nfunc (err OutOfMemoryError) ErrorName() string { return \"OutOfMemoryError\" }\n\n\ntype DockerStateError struct {\n\tdockerError string\n\tname string\n}\n\nfunc NewDockerStateError(err string) DockerStateError {\n\treturn DockerStateError{\n\t\tdockerError: err,\n\t\tname: \"DockerStateError\",\n\t}\n}\n\nfunc (err DockerStateError) Error() string {\n\treturn err.dockerError\n}\nfunc (err DockerStateError) ErrorName() string {\n\treturn err.name\n}\n\nfunc (err *DockerTimeoutError) ErrorName() string ", "output": "{ return \"DockerTimeoutError\" }"} {"input": "package quit\n\nimport (\n\t\"fmt\"\n\t\"github.com/talpah/cortana/plugins\"\n\t\"regexp\"\n\t\"os\"\n)\n\nvar (\n\tcanonicalCommand = \"quit\"\n\tcommand = `(Q|q)uit`\n\taliases map[string]*regexp.Regexp\n)\n\nfunc isAlias(cmd string) bool {\n\tfor _, alias := range aliases {\n\t\tif alias.MatchString(cmd) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc canHandle(cmd string) bool {\n\tif regexp.MustCompile(command).MatchString(cmd) {\n\t\treturn true\n\t}\n\n\treturn isAlias(cmd)\n}\n\n\n\nfunc Help(cmd string) (string, error) {\n\treturn `Quit command help\n\nQuit will... quit\n\nUsage example:\nquit\nQuit\nexit\nExit\n`, nil\n}\n\nfunc Quit(cmd string) (string, error) {\n\tif !canHandle(cmd) {\n\t\treturn \"\", fmt.Errorf(\"Can't handle command %s\", cmd)\n\t}\n\tos.Exit(0)\n\treturn \"\", nil\n}\n\nfunc Initialize(pins plugins.PluginManager) ", "output": "{\n\taliases = map[string]*regexp.Regexp{\n\t\t\"Exit\": regexp.MustCompile(`(E|e)xit`),\n\n\t}\n\n\tpins.Register(\n\t\tcanonicalCommand,\n\t\tcommand,\n\t\tQuit,\n\t\tHelp,\n\t\taliases,\n\t)\n}"} {"input": "package gremlin\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestQueryBuilder(t *testing.T) ", "output": "{\n\tconst key, val = \"Type\", \"host\"\n\texpected := fmt.Sprintf(`G.V().Has(\"%s\", Regex(\"%s\"), \"%s\", Regex(\"%s.*\"), \"%s\", Regex(\".*%s\")).Flows().Sort()`,\n\t\tkey, val, key, val, key, val)\n\tactual := G.V().Has(Quote(key), Regex(val), Quote(key), Regex(\"%s.*\", val), Quote(key), Regex(\".*%s\", val)).Flows().Sort()\n\tif actual.String() != expected {\n\t\tt.Errorf(\"Wrong query,\\nexpected: \\\"%s\\\",\\nactual: \\\"%s\\\"\", expected, actual)\n\t}\n}"} {"input": "package registry\n\nimport (\n \"github.com/twitchyliquid64/CNC/plugin/exec\"\n)\n\n\nvar dispatchMethod func(string, interface{})bool = nil\nvar deregisterPluginMethod func (plugin *exec.Plugin) = nil\n\nfunc SetupDispatchMethod(in func(string, interface{})bool) {\n dispatchMethod = in\n}\n\nfunc SetupDeregisterMethod(in func (plugin *exec.Plugin)){\n deregisterPluginMethod = in\n}\n\n\n\nfunc DispatchEvent(typ string, data interface{})bool{\n if dispatchMethod != nil {\n return dispatchMethod(typ, data)\n }\n return false\n}\n\nfunc DeregisterPluginMethod(plugin *exec.Plugin)", "output": "{\n if deregisterPluginMethod == nil{\n panic(\"deregisterPluginMethod == nil\")\n }\n deregisterPluginMethod(plugin)\n}"} {"input": "package api\n\nimport (\n\t\"debug/gosym\"\n\t\"github.com/derekparker/delve/proc\"\n)\n\n\nfunc ConvertBreakpoint(bp *proc.Breakpoint) *Breakpoint {\n\treturn &Breakpoint{\n\t\tID: bp.ID,\n\t\tFunctionName: bp.FunctionName,\n\t\tFile: bp.File,\n\t\tLine: bp.Line,\n\t\tAddr: bp.Addr,\n\t}\n}\n\n\n\n\n\nfunc ConvertVar(v *proc.Variable) Variable {\n\treturn Variable{\n\t\tName: v.Name,\n\t\tValue: v.Value,\n\t\tType: v.Type,\n\t}\n}\n\nfunc ConvertFunction(fn *gosym.Func) *Function {\n\tif fn == nil {\n\t\treturn nil\n\t}\n\n\treturn &Function{\n\t\tName: fn.Name,\n\t\tType: fn.Type,\n\t\tValue: fn.Value,\n\t\tGoType: fn.GoType,\n\t}\n}\n\n\nfunc ConvertGoroutine(g *proc.G) *Goroutine {\n\treturn &Goroutine{\n\t\tID: g.Id,\n\t\tPC: g.PC,\n\t\tFile: g.File,\n\t\tLine: g.Line,\n\t\tFunction: ConvertFunction(g.Func),\n\t}\n}\n\nfunc ConvertLocation(loc proc.Location) Location {\n\treturn Location{\n\t\tPC: loc.PC,\n\t\tFile: loc.File,\n\t\tLine: loc.Line,\n\t\tFunction: ConvertFunction(loc.Fn),\n\t}\n}\n\nfunc ConvertThread(th *proc.Thread) *Thread ", "output": "{\n\tvar (\n\t\tfunction *Function\n\t\tfile string\n\t\tline int\n\t\tpc uint64\n\t)\n\n\tloc, err := th.Location()\n\tif err == nil {\n\t\tpc = loc.PC\n\t\tfile = loc.File\n\t\tline = loc.Line\n\t\tfunction = ConvertFunction(loc.Fn)\n\t}\n\n\treturn &Thread{\n\t\tID: th.Id,\n\t\tPC: pc,\n\t\tFile: file,\n\t\tLine: line,\n\t\tFunction: function,\n\t}\n}"} {"input": "package classReader\n\nimport \"math\"\n\ntype ConstantIntegerInfo struct {\n\tval int32\n}\n\n\n\nfunc (self *ConstantIntegerInfo) Value() int32 {\n\treturn self.val\n}\n\ntype ConstantFloatInfo struct {\n\tval float32\n}\n\nfunc (self *ConstantFloatInfo) readInfo(reader *ClassReader) {\n\tbytes := reader.readUint32()\n\tself.val = math.Float32frombits(bytes)\n}\n\nfunc (self *ConstantFloatInfo) Value() float32 {\n\treturn self.val\n}\n\ntype ConstantLongInfo struct {\n\tval int64\n}\n\nfunc (self *ConstantLongInfo) readInfo(reader *ClassReader) {\n\tbytes := reader.readUint64()\n\tself.val = int64(bytes)\n}\n\nfunc (self *ConstantLongInfo) Value() int64 {\n\treturn self.val\n}\n\ntype ConstantDoubleInfo struct {\n\tval float64\n}\n\nfunc (self *ConstantDoubleInfo) readInfo(reader *ClassReader) {\n\tbytes := reader.readUint64()\n\tself.val = math.Float64frombits(bytes)\n}\n\nfunc (self *ConstantDoubleInfo) Value() float64 {\n\treturn self.val\n}\n\nfunc (self *ConstantIntegerInfo) readInfo(reader *ClassReader) ", "output": "{\n\tbytes := reader.readUint32()\n\tself.val = int32(bytes)\n}"} {"input": "package logging\n\nimport (\n\t\"time\"\n\n\t\"github.com/urandom/readeef/content\"\n\t\"github.com/urandom/readeef/content/repo\"\n\t\"github.com/urandom/readeef/log\"\n)\n\ntype tagRepo struct {\n\trepo.Tag\n\n\tlog log.Log\n}\n\nfunc (r tagRepo) Get(id content.TagID, user content.User) (content.Tag, error) {\n\tstart := time.Now()\n\n\ttag, err := r.Tag.Get(id, user)\n\n\tr.log.Infof(\"repo.Tag.Get took %s\", time.Now().Sub(start))\n\n\treturn tag, err\n}\n\n\n\nfunc (r tagRepo) ForFeed(feed content.Feed, user content.User) ([]content.Tag, error) {\n\tstart := time.Now()\n\n\ttags, err := r.Tag.ForFeed(feed, user)\n\n\tr.log.Infof(\"repo.Tag.ForFeed took %s\", time.Now().Sub(start))\n\n\treturn tags, err\n}\n\nfunc (r tagRepo) FeedIDs(tag content.Tag, user content.User) ([]content.FeedID, error) {\n\tstart := time.Now()\n\n\tids, err := r.Tag.FeedIDs(tag, user)\n\n\tr.log.Infof(\"repo.Tag.FeedIDs took %s\", time.Now().Sub(start))\n\n\treturn ids, err\n}\n\nfunc (r tagRepo) ForUser(user content.User) ([]content.Tag, error) ", "output": "{\n\tstart := time.Now()\n\n\ttags, err := r.Tag.ForUser(user)\n\n\tr.log.Infof(\"repo.Tag.ForUser took %s\", time.Now().Sub(start))\n\n\treturn tags, err\n}"} {"input": "package grep\n\nimport (\n\t\"golang.org/x/net/html\"\n\t\"net/http\"\n\t\"log\"\n)\n\n\n\n\nfunc findImages(node *html.Node, options *Options) ([]string, error){\n\n\treturn visit(nil, node, options), nil\n}\n\nfunc fetchHtml(options Options) bool {\n\tresp, err := http.Get(options.URL)\n\tif (err != nil) {\n\t\tlog.Printf(\"error fetching url %s\", options.URL)\n\t\treturn false\n\t}\n\tif (resp.StatusCode != http.StatusOK) {\n\t\tlog.Printf(\"error fetching url %s because http status is %d\", options.URL, resp.StatusCode)\n\t\treturn false\n\t}\n\n\tdoc, err := html.Parse(resp.Body)\n\tresp.Body.Close()\n\tif (err != nil) {\n\t\treturn false\n\t}\n\n\timageURLS, err := findImages(doc, &options)\n\tif (err != nil) {\n\t\tlog.Printf(\"finding images failed for url %s\", options.URL)\n\t}\n\tfor _, imageURL:= range imageURLS {\n\t\tabsImageURL, err := createURL(imageURL, resp)\n\t\tif (err == nil) {\n\t\t\tlog.Printf(\"find image url %s\", absImageURL)\n\t\t\tfetchAndStoreImage(absImageURL, options.Folder, getFileName(imageURL))\n\t\t}\n\n\t}\n\treturn true\n}\n\nfunc visit(images []string, node *html.Node, options *Options) []string ", "output": "{\n\tif node.Type == html.ElementNode && node.Data == \"img\" {\n\t\tfor _, attribuut := range node.Attr {\n\t\t\tif attribuut.Key == \"src\" {\n\t\t\t\tif (options.Verbose) {\n\t\t\t\t\tlog.Printf(\"find image src %s\", attribuut.Val)\n\t\t\t\t}\n\t\t\t\timages = append(images, attribuut.Val)\n\t\t\t}\n\t\t}\n\t}\n\tfor childNode := node.FirstChild; childNode != nil; childNode = childNode.NextSibling {\n\t\timages = visit(images, childNode, options)\n\t}\n\treturn images\n}"} {"input": "package ambition\n\nimport (\n\tcrand \"crypto/rand\"\n\t\"encoding/base64\"\n\t\"golang.org/x/crypto/bcrypt\"\n\t\"math/rand\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\n\n\n\n\n\n\nfunc CompareSaltAndPasswordToHash(salt, hashedPassword, password []byte) bool {\n\tsaltedPassword := []byte(string(password) + string(salt))\n\n\terr := bcrypt.CompareHashAndPassword(hashedPassword, saltedPassword)\n\treturn err == nil\n}\n\n\n\n\n\nfunc GenerateRandomBytes(n int) ([]byte, error) {\n\tb := make([]byte, n)\n\t_, err := crand.Read(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b, nil\n}\n\n\n\n\n\n\nfunc GenerateRandomString(s int) (string, error) {\n\tb, err := GenerateRandomBytes(s)\n\treturn base64.URLEncoding.EncodeToString(b), err\n}\n\nfunc HashToken(token string) string {\n\thash, _ := bcrypt.GenerateFromPassword([]byte(token), 10)\n\treturn string(hash)\n}\n\nfunc CompareHashAndToken(hash string, token string) bool {\n\n\terr := bcrypt.CompareHashAndPassword([]byte(hash), []byte(token))\n\treturn err == nil\n}\n\nfunc LoginUser(username string, password string) {}\n\nfunc CreateSaltAndHashedPassword(password []byte) ([]byte, []byte, error) ", "output": "{\n\tnano := time.Now().UnixNano()\n\trand.Seed(nano)\n\trandom := rand.Int31()\n\tsalt := strconv.Itoa(int(nano)) + strconv.Itoa(int(random))\n\n\thash, err := bcrypt.GenerateFromPassword([]byte(string(password)+salt), 10)\n\n\treturn []byte(salt), hash, err\n}"} {"input": "package server\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc TestSaveMess(t *testing.T) ", "output": "{\n\tfmt.Println(\"file test...\")\n\n\tm := Mess{\"test4\", \"test save mess\", \"com.binecy.gobiu\", \"test\", \"img\", time.Now().Unix()}\n\tfmt.Println(m)\n\n\tfmt.Printf(\"-------\\n\\n\")\n\n\tlist, err := Read(\"\", \"web\")\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tfmt.Println(string(GetListStr(list)))\n\n}"} {"input": "package pai\n\nimport \"testing\"\n\n\n\nfunc TestNum(t *testing.T) ", "output": "{\n\n\ttype TestCase struct {\n\t\tin MJP\n\t\tout int\n\t}\n\n\ttestCases := []TestCase{\n\t\tTestCase{S1, 1},\n\t\tTestCase{S9, 9},\n\t\tTestCase{M1, 1},\n\t\tTestCase{M9, 9},\n\t\tTestCase{P1, 1},\n\t\tTestCase{P9, 9},\n\t\tTestCase{TON, 0},\n\t\tTestCase{PEI, 0},\n\t\tTestCase{HAK, 0},\n\t\tTestCase{CHN, 0},\n\t}\n\n\tfor _, testCase := range testCases {\n\t\tif testCase.in.Num() != testCase.out {\n\t\t\tt.Errorf(\"%s Num 不一致 %d != %d\", testCase.in, testCase.in.Num(), testCase.out)\n\t\t}\n\t}\n}"} {"input": "package flagutil\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"net/url\"\n\n\t\"github.com/sirupsen/logrus\"\n\n\t\"k8s.io/test-infra/prow/bugzilla\"\n\t\"k8s.io/test-infra/prow/config/secret\"\n)\n\n\ntype BugzillaOptions struct {\n\tendpoint string\n\tgithubExternalTrackerId uint\n\tApiKeyPath string\n}\n\n\nfunc (o *BugzillaOptions) AddFlags(fs *flag.FlagSet) {\n\tfs.StringVar(&o.endpoint, \"bugzilla-endpoint\", \"\", \"Bugzilla's API endpoint.\")\n\tfs.UintVar(&o.githubExternalTrackerId, \"bugzilla-github-external-tracker-id\", 0, \"The ext_type_id for GitHub external bugs, optional.\")\n\tfs.StringVar(&o.ApiKeyPath, \"bugzilla-api-key-path\", \"\", \"Path to the file containing the Bugzilla API key.\")\n}\n\n\n\n\n\nfunc (o *BugzillaOptions) BugzillaClient(secretAgent *secret.Agent) (bugzilla.Client, error) {\n\tif o.endpoint == \"\" {\n\t\treturn nil, fmt.Errorf(\"empty -bugzilla-endpoint, cannot create Bugzilla client\")\n\t}\n\n\tvar generator *func() []byte\n\tif o.ApiKeyPath == \"\" {\n\t\tgeneratorFunc := func() []byte {\n\t\t\treturn []byte{}\n\t\t}\n\t\tgenerator = &generatorFunc\n\t} else {\n\t\tif secretAgent == nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot store token from %q without a secret agent\", o.ApiKeyPath)\n\t\t}\n\t\tgeneratorFunc := secretAgent.GetTokenGenerator(o.ApiKeyPath)\n\t\tgenerator = &generatorFunc\n\t}\n\n\treturn bugzilla.NewClient(*generator, o.endpoint, o.githubExternalTrackerId), nil\n}\n\nfunc (o *BugzillaOptions) Validate(dryRun bool) error ", "output": "{\n\tif o.endpoint == \"\" {\n\t\tlogrus.Info(\"empty -bugzilla-endpoint, will not create Bugzilla client\")\n\t\treturn nil\n\t}\n\n\tif _, err := url.ParseRequestURI(o.endpoint); err != nil {\n\t\treturn fmt.Errorf(\"invalid -bugzilla-endpoint URI: %q\", o.endpoint)\n\t}\n\n\tif o.ApiKeyPath == \"\" {\n\t\tlogrus.Info(\"empty -bugzilla-api-key-path, will use anonymous Bugzilla client\")\n\t}\n\n\treturn nil\n}"} {"input": "package datatype\n\nimport \"fmt\"\n\n\ntype OctetString string\n\n\nfunc DecodeOctetString(b []byte) (Type, error) {\n\treturn OctetString(b), nil\n}\n\n\nfunc (s OctetString) Serialize() []byte {\n\treturn []byte(s)\n}\n\n\n\n\n\nfunc (s OctetString) Padding() int {\n\tl := len(s)\n\treturn pad4(l) - l\n}\n\n\nfunc (s OctetString) Type() TypeID {\n\treturn OctetStringType\n}\n\n\nfunc (s OctetString) String() string {\n\treturn fmt.Sprintf(\"OctetString{%#x},Padding:%d\", string(s), s.Padding())\n}\n\nfunc (s OctetString) Len() int ", "output": "{\n\treturn len(s)\n}"} {"input": "package stats\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io/kubernetes/pkg/volume\"\n)\n\ntype fakeLogMetrics struct {\n\tfakeStats map[string]*volume.Metrics\n}\n\n\n\nfunc (l *fakeLogMetrics) createLogMetricsProvider(path string) volume.MetricsProvider {\n\treturn NewFakeMetricsDu(path, l.fakeStats[path])\n}\n\ntype fakeMetricsDu struct {\n\tfakeStats *volume.Metrics\n}\n\nfunc NewFakeMetricsDu(path string, stats *volume.Metrics) volume.MetricsProvider {\n\treturn &fakeMetricsDu{fakeStats: stats}\n}\n\nfunc (f *fakeMetricsDu) GetMetrics() (*volume.Metrics, error) {\n\tif f.fakeStats == nil {\n\t\treturn nil, fmt.Errorf(\"no stats provided\")\n\t}\n\treturn f.fakeStats, nil\n}\n\nfunc NewFakeLogMetricsService(stats map[string]*volume.Metrics) LogMetricsService ", "output": "{\n\treturn &fakeLogMetrics{fakeStats: stats}\n}"} {"input": "package core\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stellar/horizon/test\"\n)\n\n\n\nfunc TestTransactionFeesByLedger(t *testing.T) ", "output": "{\n\ttt := test.Start(t).Scenario(\"base\")\n\tdefer tt.Finish()\n\tq := &Q{tt.CoreRepo()}\n\n\tvar fees []TransactionFee\n\terr := q.TransactionFeesByLedger(&fees, 2)\n\n\tif tt.Assert.NoError(err) {\n\t\ttt.Assert.Len(fees, 3)\n\t}\n}"} {"input": "package memory\n\nimport (\n\t\"io\"\n\t\"sync\"\n\n\t\"github.com/Cloud-Foundations/Dominator/lib/hash\"\n\t\"github.com/Cloud-Foundations/Dominator/lib/objectserver\"\n)\n\ntype ObjectServer struct {\n\trwLock sync.RWMutex \n\tobjectMap map[hash.Hash][]byte\n}\n\nfunc NewObjectServer() *ObjectServer {\n\treturn newObjectServer()\n}\n\nfunc (objSrv *ObjectServer) AddObject(reader io.Reader, length uint64,\n\texpectedHash *hash.Hash) (hash.Hash, bool, error) {\n\treturn objSrv.addObject(reader, length, expectedHash)\n}\n\nfunc (objSrv *ObjectServer) CheckObjects(hashes []hash.Hash) ([]uint64, error) {\n\treturn objSrv.checkObjects(hashes)\n}\n\nfunc (objSrv *ObjectServer) GetObject(hashVal hash.Hash) (\n\tuint64, io.ReadCloser, error) {\n\treturn objSrv.getObject(hashVal)\n}\n\nfunc (objSrv *ObjectServer) GetObjects(hashes []hash.Hash) (\n\tobjectserver.ObjectsReader, error) {\n\treturn objSrv.getObjects(hashes)\n}\n\nfunc (objSrv *ObjectServer) ListObjectSizes() map[hash.Hash]uint64 {\n\treturn objSrv.listObjectSizes()\n}\n\nfunc (objSrv *ObjectServer) ListObjects() []hash.Hash {\n\treturn objSrv.listObjects()\n}\n\n\n\ntype ObjectsReader struct {\n\tobjectServer *ObjectServer\n\thashes []hash.Hash\n\tnextIndex int64\n\tsizes []uint64\n}\n\nfunc (or *ObjectsReader) Close() error {\n\treturn nil\n}\n\nfunc (or *ObjectsReader) NextObject() (uint64, io.ReadCloser, error) {\n\treturn or.nextObject()\n}\n\nfunc (or *ObjectsReader) ObjectSizes() []uint64 {\n\treturn or.sizes\n}\n\nfunc (objSrv *ObjectServer) NumObjects() uint64 ", "output": "{\n\tobjSrv.rwLock.RLock()\n\tdefer objSrv.rwLock.RUnlock()\n\treturn uint64(len(objSrv.objectMap))\n}"} {"input": "package command\n\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/bitrise-io/go-utils/pathutil\"\n)\n\n\nfunc CopyFile(src, dst string) error {\n\tisDir, err := pathutil.IsDirExists(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif isDir {\n\t\treturn errors.New(\"Source is a directory: \" + src)\n\t}\n\targs := []string{src, dst}\n\treturn RunCommand(\"rsync\", args...)\n}\n\n\nfunc CopyDir(src, dst string, isOnlyContent bool) error {\n\tif isOnlyContent && !strings.HasSuffix(src, \"/\") {\n\t\tsrc = src + \"/\"\n\t}\n\targs := []string{\"-ar\", src, dst}\n\treturn RunCommand(\"rsync\", args...)\n}\n\n\n\n\n\nfunc RemoveFile(pth string) error {\n\tif exist, err := pathutil.IsPathExists(pth); err != nil {\n\t\treturn err\n\t} else if exist {\n\t\tif err := os.Remove(pth); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc RemoveDir(dirPth string) error ", "output": "{\n\tif exist, err := pathutil.IsPathExists(dirPth); err != nil {\n\t\treturn err\n\t} else if exist {\n\t\tif err := os.RemoveAll(dirPth); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package messenger\n\nimport (\n\t. \"github.com/andrew-suprun/envoy\"\n\t\"log\"\n\t\"testing\"\n)\n\nfunc TestPanic(t *testing.T) {\n\tlog.Println(\"---------------- TestPanic ----------------\")\n\n\tserver, err := NewMessenger(\"localhost:50000\")\n\tif err != nil {\n\t\tt.FailNow()\n\t}\n\tdefer server.Leave()\n\tserver.Subscribe(\"job\", panicingHandler)\n\tserver.Join()\n\n\tclient, err := NewMessenger(\"localhost:40000\")\n\tif err != nil {\n\t\tt.FailNow()\n\t}\n\tdefer client.Leave()\n\tclient.Join(\"localhost:50000\")\n\n\treply, _, err := client.Request(\"job\", []byte(\"Hello\"))\n\tlog.Printf(\"TestPanic: reply = %s; err = %v\", string(reply), err)\n\tif err != PanicError {\n\t\tt.Fatalf(\"Server didn't panic\")\n\t}\n}\n\n\n\nfunc panicingHandler(topic string, body []byte, _ MessageId) []byte ", "output": "{\n\tpanic(\"foo\")\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestRepoFileCompletion(t *testing.T) ", "output": "{\n\tcheckFileCompletion(t, \"repo\", false)\n}"} {"input": "package chart\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n)\n\ntype CT_Thickness struct {\n\tValAttr ST_Thickness\n}\n\nfunc NewCT_Thickness() *CT_Thickness {\n\tret := &CT_Thickness{}\n\treturn ret\n}\n\nfunc (m *CT_Thickness) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tstart.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: \"val\"},\n\t\tValue: fmt.Sprintf(\"%v\", m.ValAttr)})\n\te.EncodeToken(start)\n\te.EncodeToken(xml.EndElement{Name: start.Name})\n\treturn nil\n}\n\nfunc (m *CT_Thickness) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tfor _, attr := range start.Attr {\n\t\tif attr.Name.Local == \"val\" {\n\t\t\tparsed, err := ParseUnionST_Thickness(attr.Value)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tm.ValAttr = parsed\n\t\t}\n\t}\n\tfor {\n\t\ttok, err := d.Token()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"parsing CT_Thickness: %s\", err)\n\t\t}\n\t\tif el, ok := tok.(xml.EndElement); ok && el.Name == start.Name {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc (m *CT_Thickness) ValidateWithPath(path string) error {\n\tif err := m.ValAttr.ValidateWithPath(path + \"/ValAttr\"); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (m *CT_Thickness) Validate() error ", "output": "{\n\treturn m.ValidateWithPath(\"CT_Thickness\")\n}"} {"input": "package tfinstall\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/hashicorp/go-checkpoint\"\n)\n\ntype LatestVersionOption struct {\n\tforceCheckpoint bool\n\tinstallDir string\n\n\tUserAgent string\n}\n\nvar _ ExecPathFinder = &LatestVersionOption{}\n\nfunc LatestVersion(installDir string, forceCheckpoint bool) *LatestVersionOption {\n\topt := &LatestVersionOption{\n\t\tforceCheckpoint: forceCheckpoint,\n\t\tinstallDir: installDir,\n\t}\n\n\treturn opt\n}\n\n\n\nfunc latestVersion(forceCheckpoint bool) (string, error) {\n\tresp, err := checkpoint.Check(&checkpoint.CheckParams{\n\t\tProduct: \"terraform\",\n\t\tForce: forceCheckpoint,\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif resp.CurrentVersion == \"\" {\n\t\treturn \"\", fmt.Errorf(\"could not determine latest version of terraform using checkpoint: CHECKPOINT_DISABLE may be set\")\n\t}\n\n\treturn resp.CurrentVersion, nil\n}\n\nfunc (opt *LatestVersionOption) ExecPath(ctx context.Context) (string, error) ", "output": "{\n\tv, err := latestVersion(opt.forceCheckpoint)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn downloadWithVerification(ctx, v, opt.installDir, opt.UserAgent)\n}"} {"input": "package tests\n\nimport (\n log \"github.com/janekolszak/revfluent\"\n \"github.com/revel/revel/testing\"\n)\n\ntype AppTest struct {\n testing.TestSuite\n}\n\nfunc (t *AppTest) TestError() {\n data := map[string]string{\"message\": \"Error\"}\n log.Error(data)\n}\n\nfunc (t *AppTest) TestDebug() {\n data := map[string]string{\"message\": \"Debug\"}\n log.Debug(data)\n}\n\nfunc (t *AppTest) TestInfo() {\n data := map[string]string{\"message\": \"Info\"}\n log.Info(data)\n}\n\n\n\nfunc (t *AppTest) TestLogger() {\n data := map[string]string{\"message\": \"Logger\"}\n log.Logger.Post(\"tag\", data)\n}\n\nfunc (t *AppTest) TestLog() ", "output": "{\n data := map[string]string{\"message\": \"Log\"}\n log.Log(\"tag\", data)\n}"} {"input": "package wait\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\n\n\n\n\nfunc Predicate(pred func() bool, timeout time.Duration) error {\n\tconst pollInterval = 20 * time.Millisecond\n\n\texitTimer := time.After(timeout)\n\tfor {\n\t\t<-time.After(pollInterval)\n\n\t\tselect {\n\t\tcase <-exitTimer:\n\t\t\treturn fmt.Errorf(\"predicate not satisfied after time out\")\n\t\tdefault:\n\t\t}\n\n\t\tif pred() {\n\t\t\treturn nil\n\t\t}\n\t}\n}\n\n\n\n\nfunc NoError(f func() error, timeout time.Duration) error {\n\tvar predErr error\n\tpred := func() bool {\n\t\tif err := f(); err != nil {\n\t\t\tpredErr = err\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t}\n\n\tif err := Predicate(pred, timeout); err != nil {\n\t\treturn predErr\n\t}\n\n\treturn nil\n}\n\n\n\n\n\n\n\nfunc Invariant(statement func() bool, timeout time.Duration) error {\n\tconst pollInterval = 20 * time.Millisecond\n\n\texitTimer := time.After(timeout)\n\tfor {\n\t\t<-time.After(pollInterval)\n\n\t\tif !statement() {\n\t\t\treturn fmt.Errorf(\"invariant broken before time out\")\n\t\t}\n\n\t\tselect {\n\t\tcase <-exitTimer:\n\t\t\treturn nil\n\t\tdefault:\n\t\t}\n\t}\n}\n\n\n\n\n\n\nfunc InvariantNoError(f func() error, timeout time.Duration) error ", "output": "{\n\tvar predErr error\n\tpred := func() bool {\n\t\tif err := f(); err != nil {\n\t\t\tpredErr = err\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t}\n\n\tif err := Invariant(pred, timeout); err != nil {\n\t\treturn predErr\n\t}\n\n\treturn nil\n}"} {"input": "package cleanpath\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"strings\"\n)\n\n\nfunc RemoveGoPath(path string) string {\n\tdirs := filepath.SplitList(os.Getenv(\"GOPATH\"))\n\tsort.Stable(longestFirst(dirs))\n\tfor _, dir := range dirs {\n\t\tsrcdir := filepath.Join(dir, \"src\")\n\t\trel, err := filepath.Rel(srcdir, path)\n\t\tif err == nil && !strings.HasPrefix(rel, \"..\"+string(filepath.Separator)) {\n\t\t\treturn rel\n\t\t}\n\t}\n\treturn path\n}\n\ntype longestFirst []string\n\nfunc (strs longestFirst) Len() int { return len(strs) }\nfunc (strs longestFirst) Less(i, j int) bool { return len(strs[i]) > len(strs[j]) }\n\n\nfunc (strs longestFirst) Swap(i, j int) ", "output": "{ strs[i], strs[j] = strs[j], strs[i] }"} {"input": "package manager\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"sync\"\n\t\"time\"\n\n\tproto \"github.com/Cloud-Foundations/Dominator/proto/hypervisor\"\n)\n\ntype flusher interface {\n\tFlush() error\n}\n\n\n\nfunc (m *Manager) shutdownVMs() {\n\tvar waitGroup sync.WaitGroup\n\tfor _, vm := range m.vms {\n\t\twaitGroup.Add(1)\n\t\tgo func(vm *vmInfoType) {\n\t\t\tdefer waitGroup.Done()\n\t\t\tvm.shutdown()\n\t\t}(vm)\n\t}\n\twaitGroup.Wait()\n\tm.Logger.Println(\"stopping cleanly after shutting down VMs\")\n\tif flusher, ok := m.Logger.(flusher); ok {\n\t\tflusher.Flush()\n\t}\n}\n\nfunc (m *Manager) shutdownVMsAndExit() {\n\tm.mutex.RLock()\n\tdefer m.mutex.RUnlock()\n\tm.shutdownVMs()\n\tos.Exit(0)\n}\n\nfunc (vm *vmInfoType) shutdown() {\n\tvm.mutex.RLock()\n\tswitch vm.State {\n\tcase proto.StateStarting, proto.StateRunning:\n\t\tstoppedNotifier := make(chan struct{}, 1)\n\t\tvm.stoppedNotifier = stoppedNotifier\n\t\tvm.commandChannel <- \"system_powerdown\"\n\t\tvm.mutex.RUnlock()\n\t\ttimer := time.NewTimer(time.Minute)\n\t\tselect {\n\t\tcase <-stoppedNotifier:\n\t\t\tif !timer.Stop() {\n\t\t\t\t<-timer.C\n\t\t\t}\n\t\t\tvm.logger.Println(\"shut down cleanly for system shutdown\")\n\t\tcase <-timer.C:\n\t\t\tvm.logger.Println(\"shutdown timed out: killing VM\")\n\t\t\tvm.commandChannel <- \"quit\"\n\t\t}\n\tdefault:\n\t\tvm.mutex.RUnlock()\n\t}\n}\n\nfunc (m *Manager) powerOff(stopVMs bool) error ", "output": "{\n\tm.mutex.RLock()\n\tdefer m.mutex.RUnlock()\n\tif stopVMs {\n\t\tm.shutdownVMs()\n\t}\n\tfor _, vm := range m.vms {\n\t\tif vm.State != proto.StateStopped {\n\t\t\treturn fmt.Errorf(\"%s is not shut down\", vm.Address.IpAddress)\n\t\t}\n\t}\n\tcmd := exec.Command(\"poweroff\")\n\tif output, err := cmd.CombinedOutput(); err != nil {\n\t\treturn fmt.Errorf(\"%s: %s\", err, string(output))\n\t}\n\treturn nil\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSIoTAnalyticsPipeline_Channel struct {\n\n\tChannelName string `json:\"ChannelName,omitempty\"`\n\n\tName string `json:\"Name,omitempty\"`\n\n\tNext string `json:\"Next,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) AWSCloudFormationType() string {\n\treturn \"AWS::IoTAnalytics::Pipeline.Channel\"\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\n\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) Metadata() map[string]interface{} ", "output": "{\n\treturn r._metadata\n}"} {"input": "package proxmox\n\nimport (\n\t\"context\"\n\n\t\"github.com/hashicorp/packer-plugin-sdk/multistep\"\n)\n\n\n\n\ntype stepSuccess struct{}\n\n\n\nfunc (s *stepSuccess) Cleanup(state multistep.StateBag) {}\n\nfunc (s *stepSuccess) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction ", "output": "{\n\tstate.Put(\"success\", true)\n\n\treturn multistep.ActionContinue\n}"} {"input": "package yaml\n\nimport (\n\t\"fmt\"\n)\n\nfunc (this *Job) Name() JobKey {\n\treturn this.name\n}\n\nfunc (this *Job) Validate(c Context) error {\n\treturn nil\n}\n\n\n\nfunc (this *Job) Prepare(c Context) error {\n\treturn nil\n}\n\nfunc (this *Job) Execute(c Context) error {\n\tc.log(\"Executing Job %s\", this.name)\n\n\treturn nil\n}\n\nfunc (this *Job) Finish(c Context) error {\n\treturn nil\n}\n\nfunc (this *Job) get_task() *task {\n\tif this.task == nil {\n\t\tthis.task = alloc_task(this)\n\t\tthis.task.description = fmt.Sprintf(\"Job[%s]\", this.name)\n\n\t\tfor _, container := range this.container_instances {\n\t\t\tthis.task.DependsOn(container.get_task())\n\t\t}\n\t}\n\treturn this.task\n}\n\nfunc (this *Job) InDesiredState(c Context) (bool, error) ", "output": "{\n\treturn true, nil\n}"} {"input": "package http\n\nimport (\n\t\"context\"\n\t\"github.com/go-kit/kit/endpoint\"\n\t\"github.com/kryptn/modulario/proto\"\n)\n\nfunc MakeLoginEndpoint(svc HttpService) endpoint.Endpoint {\n\treturn func(ctx context.Context, request interface{}) (interface{}, error) {\n\t\treq := request.(proto.LoginRequest)\n\t\tresp, err := svc.Login(ctx, req)\n\t\treturn resp, err\n\t}\n}\n\n\n\nfunc MakeViewPostEndpoint(svc HttpService) endpoint.Endpoint {\n\treturn func(ctx context.Context, request interface{}) (interface{}, error) {\n\t\treq := request.(proto.ViewPostRequest)\n\t\treturn svc.ViewPost(ctx, req)\n\t}\n}\n\nfunc MakeCreatePostEndpoint(svc HttpService) endpoint.Endpoint {\n\treturn func(ctx context.Context, request interface{}) (interface{}, error) {\n\t\treq := request.(proto.CreatePostRequest)\n\t\treturn svc.CreatePost(ctx, req)\n\t}\n}\n\nfunc MakeVisitPostEndpoint(svc HttpService) endpoint.Endpoint ", "output": "{\n\treturn func(ctx context.Context, request interface{}) (interface{}, error) {\n\t\treq := request.(proto.VisitPostRequest)\n\t\treturn svc.VisitPost(ctx, req)\n\t}\n}"} {"input": "package uaa\n\nimport (\n\t\"sort\"\n\n\tbosherr \"github.com/cloudfoundry/bosh-utils/errors\"\n)\n\ntype Prompt struct {\n\tKey string \n\tType string \n\tLabel string \n}\n\ntype PromptAnswer struct {\n\tKey string \n\tValue string\n}\n\nfunc (p Prompt) IsPassword() bool { return p.Type == \"password\" }\n\ntype PromptsResp struct {\n\tPrompts map[string][]string \n}\n\nfunc (u UAAImpl) Prompts() ([]Prompt, error) {\n\tresp, err := u.client.Prompts()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar prompts []Prompt\n\n\tfor key, pair := range resp.Prompts {\n\t\tprompts = append(prompts, Prompt{\n\t\t\tKey: key,\n\t\t\tType: pair[0],\n\t\t\tLabel: pair[1],\n\t\t})\n\t}\n\n\tsort.Sort(PromptSorting(prompts))\n\n\treturn prompts, nil\n}\n\nfunc (c Client) Prompts() (PromptsResp, error) {\n\tvar resp PromptsResp\n\n\terr := c.clientRequest.Get(\"/login\", &resp)\n\tif err != nil {\n\t\treturn resp, bosherr.WrapError(err, \"Requesting UAA prompts\")\n\t}\n\n\treturn resp, nil\n}\n\ntype PromptSorting []Prompt\n\nfunc (s PromptSorting) Len() int { return len(s) }\n\nfunc (s PromptSorting) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (s PromptSorting) Less(i, j int) bool ", "output": "{ return s[i].Type > s[j].Type }"} {"input": "package main\n\nimport (\n \"container/list\"\n \"log\"\n \"sync\"\n \"time\"\n)\n\ntype ThreadPool struct {\n size, running int\n list *list.List\n m sync.Mutex\n}\n\nfunc NewThreadPool(size int) *ThreadPool {\n tp := &ThreadPool{\n size: size,\n list: list.New(),\n }\n return tp\n}\n\nfunc (tp *ThreadPool) onStop() {\n tp.m.Lock()\n tp.running--\n tp.m.Unlock()\n tp.run()\n}\n\nfunc (tp *ThreadPool) run() {\n tp.m.Lock()\n defer tp.m.Unlock()\n if tp.list.Len() > 0 && tp.running < tp.size {\n f := tp.list.Remove(tp.list.Front()).(func())\n tp.running++\n go func() {\n f()\n tp.onStop()\n }()\n }\n}\n\n\n\nfunc main() {\n var wg sync.WaitGroup\n tp := NewThreadPool(4)\n for i := 0; i < 16; i++ {\n wg.Add(1)\n (func(id int) {\n log.Printf(\"Subtmitted job %d\", id)\n tp.Submit(func() {\n time.Sleep(3 * time.Second)\n log.Printf(\"Hello from job %d\", id)\n wg.Done()\n })\n })(i)\n }\n wg.Wait()\n}\n\nfunc (tp *ThreadPool) Submit(f func()) ", "output": "{\n tp.list.PushBack(f)\n tp.run()\n}"} {"input": "package client\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/mesosphere/dcos-commons/cli/config\"\n)\n\n\n\nvar PrintMessage = printMessage\n\n\n\nvar PrintMessageAndExit = printMessageAndExit\n\nfunc printMessage(format string, a ...interface{}) (int, error) {\n\treturn fmt.Println(fmt.Sprintf(format, a...))\n}\n\nfunc printMessageAndExit(format string, a ...interface{}) (int, error) {\n\tPrintMessage(format, a...)\n\tos.Exit(1)\n\treturn 0, nil\n}\n\n\nfunc PrintVerbose(format string, a ...interface{}) (int, error) {\n\tif config.Verbose {\n\t\treturn PrintMessage(format, a...)\n\t}\n\treturn 0, nil\n}\n\n\n\n\n\n\n\nfunc PrintResponseText(body []byte) {\n\tPrintMessage(\"%s\\n\", string(body))\n}\n\nfunc PrintJSONBytes(responseBytes []byte) ", "output": "{\n\tvar outBuf bytes.Buffer\n\terr := json.Indent(&outBuf, responseBytes, \"\", \" \")\n\tif err != nil {\n\t\tPrintMessage(\"Failed to prettify JSON response data: %s\", err)\n\t\tPrintMessage(\"Original data follows:\")\n\t\toutBuf = *bytes.NewBuffer(responseBytes)\n\t}\n\tPrintMessage(\"%s\", outBuf.String())\n}"} {"input": "package logo\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc fail(t *testing.T, msg string) {\n\tt.Errorf(msg)\n}\n\nfunc assertEqual(t *testing.T, actual, expected interface{}, args ...interface{}) {\n\tif actual != expected {\n\t\tmsg := fmt.Sprint(args...)\n\t\tmsg = fmt.Sprintf(\"Not equal(%s)! autual: %#v expected: %#v\", msg, actual, expected)\n\t\tfail(t, msg)\n\t}\n}\n\nfunc assertTrue(t *testing.T, val bool, args ...interface{}) {\n\tif !val {\n\t\tmsg := fmt.Sprint(args...)\n\t\tmsg = fmt.Sprintf(\"Not true(%s)!\", msg)\n\t\tfail(t, msg)\n\t}\n}\n\n\n\nfunc benchmarkTask(b *testing.B, task func(int)) {\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\ttask(i)\n\t}\n}\n\nfunc assertNotNil(t *testing.T, val interface{}, args ...interface{}) ", "output": "{\n\tif val == nil {\n\t\tmsg := fmt.Sprint(args...)\n\t\tmsg = fmt.Sprintf(\"Nil(%s)!\", msg)\n\t\tfail(t, msg)\n\t}\n}"} {"input": "package readline\n\nimport (\n\t\"io\"\n\t\"syscall\"\n)\n\n\ntype State struct {\n\ttermios Termios\n}\n\n\nfunc IsTerminal(fd int) bool {\n\t_, err := getTermios(fd)\n\treturn err == nil\n}\n\n\n\n\n\n\n\n\nfunc GetState(fd int) (*State, error) {\n\ttermios, err := getTermios(fd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &State{termios: *termios}, nil\n}\n\n\n\nfunc restoreTerm(fd int, state *State) error {\n\treturn setTermios(fd, &state.termios)\n}\n\n\n\n\nfunc ReadPassword(fd int) ([]byte, error) {\n\toldState, err := getTermios(fd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnewState := oldState\n\tnewState.Lflag &^= syscall.ECHO\n\tnewState.Lflag |= syscall.ICANON | syscall.ISIG\n\tnewState.Iflag |= syscall.ICRNL\n\tif err := setTermios(fd, newState); err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer func() {\n\t\tsetTermios(fd, oldState)\n\t}()\n\n\tvar buf [16]byte\n\tvar ret []byte\n\tfor {\n\t\tn, err := syscall.Read(fd, buf[:])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif n == 0 {\n\t\t\tif len(ret) == 0 {\n\t\t\t\treturn nil, io.EOF\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tif buf[n-1] == '\\n' {\n\t\t\tn--\n\t\t}\n\t\tret = append(ret, buf[:n]...)\n\t\tif n < len(buf) {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn ret, nil\n}\n\nfunc MakeRaw(fd int) (*State, error) ", "output": "{\n\tvar oldState State\n\n\tif termios, err := getTermios(fd); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\toldState.termios = *termios\n\t}\n\n\tnewState := oldState.termios\n\tnewState.Iflag &^= syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK | syscall.ISTRIP | syscall.INLCR | syscall.IGNCR | syscall.ICRNL | syscall.IXON\n\tnewState.Lflag &^= syscall.ECHO | syscall.ECHONL | syscall.ICANON | syscall.ISIG | syscall.IEXTEN\n\tnewState.Cflag &^= syscall.CSIZE | syscall.PARENB\n\tnewState.Cflag |= syscall.CS8\n\n\tnewState.Cc[syscall.VMIN] = 1\n\tnewState.Cc[syscall.VTIME] = 0\n\n\treturn &oldState, setTermios(fd, &newState)\n}"} {"input": "package payload\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/hyperledger/burrow/acm/acmstate\"\n\t\"github.com/hyperledger/burrow/crypto\"\n)\n\nfunc NewBondTx(address crypto.Address, amount uint64) *BondTx {\n\treturn &BondTx{\n\t\tInput: &TxInput{\n\t\t\tAddress: address,\n\t\t\tAmount: amount,\n\t\t},\n\t}\n}\n\nfunc (tx *BondTx) Type() Type {\n\treturn TypeBond\n}\n\nfunc (tx *BondTx) GetInputs() []*TxInput {\n\treturn []*TxInput{tx.Input}\n}\n\nfunc (tx *BondTx) String() string {\n\treturn fmt.Sprintf(\"BondTx{%v}\", tx.Input)\n}\n\nfunc (tx *BondTx) AddInput(st acmstate.AccountGetter, pubkey *crypto.PublicKey, amt uint64) error {\n\taddr := pubkey.GetAddress()\n\tacc, err := st.GetAccount(addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif acc == nil {\n\t\treturn fmt.Errorf(\"invalid address %s from pubkey %s\", addr, pubkey)\n\t}\n\treturn tx.AddInputWithSequence(pubkey, amt, acc.Sequence+uint64(1))\n}\n\n\n\nfunc (tx *BondTx) Any() *Any {\n\treturn &Any{\n\t\tBondTx: tx,\n\t}\n}\n\nfunc (tx *BondTx) AddInputWithSequence(pubkey *crypto.PublicKey, amt uint64, sequence uint64) error ", "output": "{\n\ttx.Input = &TxInput{\n\t\tAddress: pubkey.GetAddress(),\n\t\tAmount: amt,\n\t\tSequence: sequence,\n\t}\n\treturn nil\n}"} {"input": "package goDB\n\nimport (\n \"encoding/json\"\n \"os\"\n)\n\n\ntype BlockMetadata struct {\n Timestamp int64 `json:\"timestamp\"`\n PcapPacketsReceived int `json:\"pcap_packets_received\"`\n PcapPacketsDropped int `json:\"pcap_packets_dropped\"`\n PcapPacketsIfDropped int `json:\"pcap_packets_if_dropped\"`\n PacketsLogged int `json:\"packets_logged\"`\n\n \n FlowCount uint64 `json:\"flowcount\"`\n Traffic uint64 `json:\"traffic\"`\n}\n\n\n\ntype Metadata struct {\n Blocks []BlockMetadata `json:\"blocks\"`\n}\n\nfunc NewMetadata() *Metadata {\n return &Metadata{}\n}\n\n\nfunc ReadMetadata(path string) (*Metadata, error) {\n var result Metadata\n\n f, err := os.Open(path)\n if err != nil {\n return nil, err\n }\n defer f.Close()\n\n if err := json.NewDecoder(f).Decode(&result); err != nil {\n return nil, err\n }\n\n return &result, nil\n}\n\n\n\nfunc TryReadMetadata(path string) *Metadata {\n meta, err := ReadMetadata(path)\n if err != nil {\n return NewMetadata()\n }\n return meta\n}\n\n\n\nfunc WriteMetadata(path string, meta *Metadata) error ", "output": "{\n f, err := os.Create(path)\n if err != nil {\n return err\n }\n defer f.Close()\n\n return json.NewEncoder(f).Encode(meta)\n}"} {"input": "package memcachep\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"strconv\"\n)\n\ntype Stats map[string]fmt.Stringer\n\n\ntype FuncStat struct {\n\tCallable func() string\n}\n\nfunc (f *FuncStat) String() string {\n\treturn f.Callable()\n}\n\n\ntype StaticStat struct {\n\tValue string\n}\n\nfunc (s *StaticStat) String() string {\n\treturn s.Value\n}\n\n\ntype CounterStat struct {\n\tCount int\n\tcalculations chan int\n}\n\nfunc (c *CounterStat) Increment(num int) {\n\tc.calculations <- num\n}\n\n\n\nfunc (c *CounterStat) Decrement(num int) {\n\tc.calculations <- -num\n}\n\nfunc (c *CounterStat) String() string {\n\treturn strconv.Itoa(c.Count)\n}\n\nfunc (c *CounterStat) work() {\n\tfor num := range c.calculations {\n\t\tc.Count = c.Count + num\n\t}\n}\n\nfunc NewCounterStat() *CounterStat {\n\tc := &CounterStat{}\n\tc.calculations = make(chan int, 100)\n\tgo c.work()\n\treturn c\n}\n\nfunc NewStats() Stats {\n\ts := make(Stats)\n\ts[\"pid\"] = &StaticStat{strconv.Itoa(os.Getpid())}\n\ts[\"version\"] = &StaticStat{VERSION}\n\ts[\"golang\"] = &StaticStat{runtime.Version()}\n\ts[\"goroutines\"] = &FuncStat{func() string { return strconv.Itoa(runtime.NumGoroutine()) }}\n\ts[\"cpu_num\"] = &StaticStat{strconv.Itoa(runtime.NumCPU())}\n\ts[\"total_connections\"] = NewCounterStat()\n\ts[\"curr_connections\"] = NewCounterStat()\n\ts[\"cmd_get\"] = NewCounterStat()\n\treturn s\n}\n\nfunc (c *CounterStat) SetCount(num int) ", "output": "{\n\tc.Count = num\n}"} {"input": "package process\n\nimport (\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc toHash(input []byte) string {\n\thasher := sha256.New()\n\thasher.Write(input)\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}\n\nfunc getRandomData() []byte {\n\tsize := 64\n\trb := make([]byte, size)\n\t_, _ = rand.Read(rb)\n\treturn rb\n}\n\n\n\n\ntype Token struct {\n\tHash string\n}\n\nvar ProcessToken *Token = NewToken()\n\nfunc NewToken() *Token {\n\treturn &Token{\n\t\tHash: RandomHash(),\n\t}\n}\n\nfunc PrettyUniqueToken() string {\n\treturn fmt.Sprintf(\"%d:%s\", time.Now().UnixNano(), NewToken().Hash)\n}\n\nfunc RandomHash() string ", "output": "{\n\treturn toHash(getRandomData())\n}"} {"input": "package model\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/converter\"\n\t\"strings\"\n)\n\n\ntype CreateScalingTagsRequestBody struct {\n\tTags *[]TagsSingleValue `json:\"tags,omitempty\"`\n\tAction *CreateScalingTagsRequestBodyAction `json:\"action,omitempty\"`\n}\n\nfunc (o CreateScalingTagsRequestBody) String() string {\n\tdata, _ := json.Marshal(o)\n\treturn strings.Join([]string{\"CreateScalingTagsRequestBody\", string(data)}, \" \")\n}\n\ntype CreateScalingTagsRequestBodyAction struct {\n\tvalue string\n}\n\ntype CreateScalingTagsRequestBodyActionEnum struct {\n\tCREATE CreateScalingTagsRequestBodyAction\n}\n\n\n\nfunc (c CreateScalingTagsRequestBodyAction) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(c.value)\n}\n\nfunc (c *CreateScalingTagsRequestBodyAction) UnmarshalJSON(b []byte) error {\n\tmyConverter := converter.StringConverterFactory(\"string\")\n\tif myConverter != nil {\n\t\tval, err := myConverter.CovertStringToInterface(strings.Trim(string(b[:]), \"\\\"\"))\n\t\tif err == nil {\n\t\t\tc.value = val.(string)\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t} else {\n\t\treturn errors.New(\"convert enum data to string error\")\n\t}\n}\n\nfunc GetCreateScalingTagsRequestBodyActionEnum() CreateScalingTagsRequestBodyActionEnum ", "output": "{\n\treturn CreateScalingTagsRequestBodyActionEnum{\n\t\tCREATE: CreateScalingTagsRequestBodyAction{\n\t\t\tvalue: \"create\",\n\t\t},\n\t}\n}"} {"input": "package arrow\n\nimport (\n\t\"sort\"\n\n\t\"github.com/catorpilor/leetcode/utils\"\n)\n\nfunc minArrows(points [][]int) int {\n\treturn useTwoPointers(points)\n}\n\n\n\n\n\nfunc useBoundary(points [][]int) int {\n\tn := len(points)\n\tif n <= 1 {\n\t\treturn n\n\t}\n\tsort.Slice(points, func(i, j int) bool {\n\t\treturn points[i][1] < points[j][1]\n\t})\n\tcurB := points[0]\n\tans := 1\n\tfor i := 1; i < n; i++ {\n\t\tif points[i][0] > curB[1] {\n\t\t\tans++\n\t\t\tcurB = points[i]\n\t\t}\n\t}\n\treturn ans\n}\n\nfunc useTwoPointers(points [][]int) int ", "output": "{\n\tn := len(points)\n\tif n <= 1 {\n\t\treturn n\n\t}\n\tsort.Slice(points, func(i, j int) bool {\n\t\tif points[i][0] == points[j][0] {\n\t\t\treturn points[i][1] < points[j][1]\n\t\t}\n\t\treturn points[i][0] < points[j][0]\n\t})\n\tleft, right := points[0][0], points[0][1]\n\tans := 1\n\tfor i := 1; i < n; i++ {\n\t\tif points[i][0] > right {\n\t\t\tright = points[i][1]\n\t\t\tans++\n\t\t} else {\n\t\t\tright = utils.Min(right, points[i][1])\n\t\t}\n\t\t_ = left\n\t\tleft = points[i][0]\n\t}\n\treturn ans\n}"} {"input": "package eav\n\ntype (\n\tAttributeFrontendModeller interface {\n\t\tInputRenderer() FrontendInputRendererIFace\n\t\tGetValue()\n\t\tGetInputType() string\n\n\t\tConfig(...AttributeFrontendConfig) AttributeFrontendModeller\n\t}\n\tFrontendInputRendererIFace interface {\n\t}\n\tAttributeFrontend struct {\n\t\ta *Attribute\n\t\tidx AttributeIndex\n\t}\n\tAttributeFrontendConfig func(*AttributeFrontend)\n)\n\nvar _ AttributeFrontendModeller = (*AttributeFrontend)(nil)\n\n\nfunc NewAttributeFrontend(cfgs ...AttributeFrontendConfig) *AttributeFrontend {\n\tas := &AttributeFrontend{\n\t\ta: nil,\n\t}\n\tas.Config(cfgs...)\n\treturn as\n}\n\n\nfunc AttributeFrontendIdx(i AttributeIndex) AttributeFrontendConfig {\n\treturn func(as *AttributeFrontend) {\n\t\tas.idx = i\n\t}\n}\n\n\n\n\nfunc (af *AttributeFrontend) InputRenderer() FrontendInputRendererIFace { return nil }\nfunc (af *AttributeFrontend) GetValue() {}\nfunc (af *AttributeFrontend) GetInputType() string {\n\treturn af.a.FrontendInput()\n}\n\nfunc (af *AttributeFrontend) Config(configs ...AttributeFrontendConfig) AttributeFrontendModeller ", "output": "{\n\tfor _, cfg := range configs {\n\t\tcfg(af)\n\t}\n\treturn af\n}"} {"input": "package capabilities\n\nimport (\n\t\"testing\"\n\n\tcb \"github.com/hyperledger/fabric/protos/common\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestChannelV10(t *testing.T) {\n\top := NewChannelProvider(map[string]*cb.Capability{})\n\tassert.NoError(t, op.Supported())\n\tassert.True(t, op.MSPVersion() == MSPv1_0)\n}\n\n\n\nfunc TestChannelV11(t *testing.T) ", "output": "{\n\top := NewChannelProvider(map[string]*cb.Capability{\n\t\tChannelV1_1: &cb.Capability{},\n\t})\n\tassert.NoError(t, op.Supported())\n\tassert.True(t, op.MSPVersion() == MSPv1_1)\n}"} {"input": "package hpg\n\nimport \"net/url\"\n\n\ntype CommonParams struct {\n\tKey string\n\tStart int\n\tCount int\n\tCallback string\n}\n\n\nfunc (p *CommonParams) queryBuffer() *queryBuffer {\n\tbf := new(queryBuffer)\n\n\tbf.WriteString(\"?key=\" + url.QueryEscape(p.Key))\n\n\tbf.appendInt(\"start\", p.Start)\n\tbf.appendInt(\"count\", p.Count)\n\n\tif p.Callback == \"\" {\n\t\tbf.append(\"format\", \"json\")\n\t} else {\n\t\tbf.append(\"format\", \"jsonp\")\n\t\tbf.append(\"callback\", p.Callback)\n\t}\n\n\treturn bf\n}\n\n\n\n\nfunc (p *CommonParams) String() string ", "output": "{\n\treturn p.queryBuffer().String()\n}"} {"input": "package externalversions\n\nimport (\n\t\"fmt\"\n\n\tschema \"k8s.io/apimachinery/pkg/runtime/schema\"\n\tcache \"k8s.io/client-go/tools/cache\"\n\tv1alpha1 \"knative.dev/eventing-kafka-broker/control-plane/pkg/apis/eventing/v1alpha1\"\n)\n\n\n\ntype GenericInformer interface {\n\tInformer() cache.SharedIndexInformer\n\tLister() cache.GenericLister\n}\n\ntype genericInformer struct {\n\tinformer cache.SharedIndexInformer\n\tresource schema.GroupResource\n}\n\n\nfunc (f *genericInformer) Informer() cache.SharedIndexInformer {\n\treturn f.informer\n}\n\n\nfunc (f *genericInformer) Lister() cache.GenericLister {\n\treturn cache.NewGenericLister(f.Informer().GetIndexer(), f.resource)\n}\n\n\n\n\n\nfunc (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) ", "output": "{\n\tswitch resource {\n\tcase v1alpha1.SchemeGroupVersion.WithResource(\"kafkasinks\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Eventing().V1alpha1().KafkaSinks().Informer()}, nil\n\n\t}\n\n\treturn nil, fmt.Errorf(\"no informer found for %v\", resource)\n}"} {"input": "package endpoints\n\nimport (\n\t\"github.com/lxc/lxd/lxd/util\"\n\t\"github.com/lxc/lxd/shared\"\n)\n\n\nfunc Unstarted() *Endpoints {\n\treturn &Endpoints{\n\t\tsystemdListenFDsStart: util.SystemdListenFDsStart,\n\t}\n}\n\nfunc (e *Endpoints) Up(config *Config) error {\n\treturn e.up(config)\n}\n\n\nfunc (e *Endpoints) DevLxdSocketPath() string {\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\tlistener := e.listeners[devlxd]\n\treturn listener.Addr().String()\n}\n\nfunc (e *Endpoints) LocalSocketPath() string {\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\tlistener := e.listeners[local]\n\treturn listener.Addr().String()\n}\n\n\n\n\n\n\n\n\n\nfunc (e *Endpoints) SystemdListenFDsStart(start int) {\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\te.systemdListenFDsStart = start\n}\n\nfunc (e *Endpoints) NetworkAddressAndCert() (string, *shared.CertInfo) ", "output": "{\n\treturn e.NetworkAddress(), e.cert\n}"} {"input": "package size\n\nimport (\n\t\"math\"\n\t\"time\"\n)\n\n\n\nfunc Size(bytesPerSecond int64, dur time.Duration) (numBytes int64) {\n\treturn bytesPerSecond * int64(dur/time.Second)\n}\n\n\nfunc Rate(numBytes int64, dur time.Duration) (bytesPerSecond int64) {\n\treturn numBytes / int64(dur/time.Second)\n}\n\n\n\n\n\nfunc Duration(numBytes, bytesPerSecond int64) time.Duration ", "output": "{\n\tr := time.Duration(bytesPerSecond)\n\ts := time.Duration(numBytes)\n\tif s > math.MaxInt64/time.Second {\n\t\treturn s / r * time.Second\n\t}\n\treturn s * time.Second / r\n}"} {"input": "package http\n\nimport (\n\t\"github.com/go-martini/martini\"\n\t\"github.com/martini-contrib/render\"\n\t\"net/http\"\n\t\"sysware.com/ivideo/log\"\n\t\"sysware.com/ivideo/model\"\n\tshttp \"sysware.com/ivideo/server/http\"\n\t\"sysware.com/ivideo/service\"\n\t\"sysware.com/ivideo/utils\"\n)\n\ntype routeServerConfigRoot struct {\n}\n\n\n\nfunc (routeServerConfigRoot *routeServerConfigRoot) Routes(m *martini.ClassicMartini) ", "output": "{\n\tm.Get(\"/serverconfig\", func(w http.ResponseWriter, r *http.Request, re render.Render) string {\n\t\tlog.WriteLog(\"addr: /serverconfig\")\n\t\tshttp.SetResponseJsonHeader(w)\n\t\tr.ParseForm()\n\t\tserverName := r.FormValue(\"servername\")\n\t\tif utils.IsEmptyStr(serverName) {\n\t\t\treturn model.GetErrorDtoJson(\"没有服务器名称\")\n\t\t}\n\t\tserverInfo, serverSetupInfo, err := service.NewGetServerSetupInfo().GetInfo(serverName)\n\t\tif nil != err {\n\t\t\treturn model.GetErrorObjDtoJson(err)\n\t\t}\n\t\treturn model.GetDataDtoJson([]interface{}{serverInfo, serverSetupInfo})\n\t})\n}"} {"input": "package pool\n\nimport (\n\t\"testing\"\n\n\t\"github.com/m3db/m3x/checked\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestCheckedObjectPoolNoOptions(t *testing.T) {\n\tp := NewCheckedObjectPool(nil)\n\tassert.NotNil(t, p)\n}\n\nfunc checkedObjectPoolLen(p CheckedObjectPool) int {\n\treturn len(p.(*checkedObjectPool).pool.(*objectPool).values)\n}\n\nfunc TestCheckedObjectPool(t *testing.T) ", "output": "{\n\ttype obj struct {\n\t\tchecked.RefCount\n\t\tx int\n\t}\n\n\topts := NewObjectPoolOptions().SetSize(1)\n\n\tp := NewCheckedObjectPool(opts)\n\tp.Init(func() checked.ReadWriteRef {\n\t\treturn &obj{}\n\t})\n\n\tassert.Equal(t, 1, checkedObjectPoolLen(p))\n\n\to := p.Get().(*obj)\n\tassert.Equal(t, 0, checkedObjectPoolLen(p))\n\n\to.IncRef()\n\to.IncWrites()\n\to.x = 3\n\to.DecWrites()\n\to.DecRef()\n\to.Finalize()\n\n\tassert.Equal(t, 1, checkedObjectPoolLen(p))\n\n\to = p.Get().(*obj)\n\tassert.Equal(t, 0, checkedObjectPoolLen(p))\n\n\to.IncRef()\n\to.IncReads()\n\tassert.Equal(t, 3, o.x)\n}"} {"input": "package runtime\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/heroku/instruments\"\n)\n\nfunc TestPauses(t *testing.T) {\n\tp := NewPauses(1024)\n\n\tp.Update()\n\tp.Snapshot()\n\n\truntime.GC()\n\tp.Update()\n\tif count := len(p.Snapshot()); count != 1 {\n\t\tt.Fatalf(\"captured %d gc runs, expect 1\", count)\n\t}\n\n\truntime.GC()\n\truntime.GC()\n\tp.Update()\n\tif count := len(p.Snapshot()); count != 2 {\n\t\tt.Fatalf(\"captured %d gc runs, expected 2\", count)\n\t}\n\n\tfor i := 0; i < 257; i++ {\n\t\truntime.GC()\n\t}\n\tp.Update()\n\tif count := len(p.Snapshot()); count != 256 {\n\t\tt.Fatalf(\"captured %d gc runs, expected 256\", count)\n\t}\n}\n\n\n\nfunc ExamplePauses() ", "output": "{\n\tpauses := NewPauses(512)\n\tgo func() {\n\t\tfor {\n\t\t\tpauses.Update()\n\t\t\ttime.Sleep(time.Minute)\n\t\t}\n\t}()\n\tperc95 := instruments.Quantile(pauses.Snapshot(), 0.95)\n\tfmt.Println(perc95)\n}"} {"input": "package datastore\n\nimport (\n\t\"encoding/json\"\n)\n\n\ntype JSONMessage interface {\n\tBytes() json.RawMessage\n\tVersion() map[string]int\n}\n\n\nfunc NewJSONMessage(data []byte, version map[string]int) JSONMessage {\n\treturn &jsonMessage{data, version}\n}\n\ntype jsonMessage struct {\n\tdata json.RawMessage\n\tvEntity map[string]int\n}\n\nfunc (m *jsonMessage) Bytes() json.RawMessage {\n\treturn m.data\n}\n\nfunc (m *jsonMessage) Version() map[string]int {\n\treturn m.vEntity\n}\n\n\nfunc (m *jsonMessage) MarshalJSON() ([]byte, error) {\n\treturn m.data.MarshalJSON()\n}\n\n\n\n\nfunc (m *jsonMessage) UnmarshalJSON(data []byte) error ", "output": "{\n\treturn m.data.UnmarshalJSON(data)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\n\t\"github.com/hyperledger/fabric/core/chaincode/shim\"\n\tpb \"github.com/hyperledger/fabric/protos/peer\"\n)\n\n\ntype SimpleChaincode struct {\n}\n\n\n\n\n\nfunc (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {\n\tfunction, args := stub.GetFunctionAndParameters()\n\tif function == \"query\" {\n\t\treturn t.query(stub, args)\n\t}\n\n\treturn shim.Error(\"Invalid invoke function name. Expecting \\\"query\\\"\")\n}\n\nfunc (t *SimpleChaincode) query(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\tvar A string \n\tvar Aval int \n\tvar err error\n\n\tif len(args) != 2 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 2\")\n\t}\n\n\tA = args[0]\n\tAval, err = strconv.Atoi(args[1])\n\tif err != nil {\n\t\treturn shim.Error(\"Expecting integer value for asset holding\")\n\t}\n\tfmt.Printf(\"Aval = %d\\n\", Aval)\n\n\terr = stub.PutState(A, []byte(strconv.Itoa(Aval)))\n\tif err != nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\"Cannot put state within chaincode query\\\"}\"\n\t\treturn shim.Error(jsonResp)\n\t}\n\n\treturn shim.Success(nil)\n}\n\nfunc main() {\n\terr := shim.Start(new(SimpleChaincode))\n\tif err != nil {\n\t\tfmt.Printf(\"Error starting chaincode: %s\", err)\n\t}\n}\n\nfunc (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response ", "output": "{\n\tvar A string \n\tvar Aval int \n\tvar err error\n\t_, args := stub.GetFunctionAndParameters()\n\tif len(args) != 2 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 2\")\n\t}\n\n\tA = args[0]\n\tAval, err = strconv.Atoi(args[1])\n\tif err != nil {\n\t\treturn shim.Error(\"Expecting integer value for asset holding\")\n\t}\n\tfmt.Printf(\"Aval = %d\\n\", Aval)\n\n\terr = stub.PutState(A, []byte(strconv.Itoa(Aval)))\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\treturn shim.Success(nil)\n}"} {"input": "package cfn\n\nconst (\n\tCREATE_COMPLETE = \"CREATE_COMPLETE\"\n\tCREATE_FAILED = \"CREATE_FAILED\"\n\tCREATE_IN_PROGRESS = \"CREATE_IN_PROGRESS\"\n\tDELETE_COMPLETE = \"DELETE_COMPLETE\"\n\tDELETE_FAILED = \"DELETE_FAILED\"\n\tDELETE_IN_PROGRESS = \"DELETE_IN_PROGRESS\"\n\tROLLBACK_COMPLETE = \"ROLLBACK_COMPLETE\"\n\tROLLBACK_FAILED = \"ROLLBACK_FAILED\"\n\tROLLBACK_IN_PROGRESS = \"ROLLBACK_IN_PROGRESS\"\n\tUPDATE_COMPLETE = \"UPDATE_COMPLETE\"\n\tUPDATE_COMPLETE_CLEANUP_IN_PROGRESS = \"UPDATE_COMPLETE_CLEANUP_IN_PROGRESS\"\n\tUPDATE_IN_PROGRESS = \"UPDATE_IN_PROGRESS\"\n\tUPDATE_ROLLBACK_COMPLETE = \"UPDATE_ROLLBACK_COMPLETE\"\n\tUPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS = \"UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS\"\n\tUPDATE_ROLLBACK_FAILED = \"UPDATE_ROLLBACK_FAILED\"\n\tUPDATE_ROLLBACK_IN_PROGRESS = \"UPDATE_ROLLBACK_IN_PROGRESS\"\n)\n\nfunc PrunableStatus(status string) bool {\n\tswitch status {\n\tcase CREATE_COMPLETE,\n\t\tCREATE_FAILED,\n\t\tROLLBACK_COMPLETE,\n\t\tROLLBACK_FAILED,\n\t\tROLLBACK_IN_PROGRESS,\n\t\tUPDATE_COMPLETE,\n\t\tUPDATE_COMPLETE_CLEANUP_IN_PROGRESS,\n\t\tUPDATE_IN_PROGRESS,\n\t\tUPDATE_ROLLBACK_COMPLETE,\n\t\tUPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS,\n\t\tUPDATE_ROLLBACK_FAILED,\n\t\tUPDATE_ROLLBACK_IN_PROGRESS:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n\n\n\n\n\n\nfunc AnyStatus(status string) bool {\n\treturn true\n}\n\nfunc CheckHotswapStatus(status string) bool ", "output": "{\n\tswitch status {\n\tcase CREATE_COMPLETE,\n\t\tUPDATE_COMPLETE,\n\t\tUPDATE_COMPLETE_CLEANUP_IN_PROGRESS,\n\t\tUPDATE_IN_PROGRESS,\n\t\tUPDATE_ROLLBACK_COMPLETE,\n\t\tUPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS,\n\t\tUPDATE_ROLLBACK_FAILED,\n\t\tUPDATE_ROLLBACK_IN_PROGRESS:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}"} {"input": "package pinpointemail_test\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/aws/awserr\"\n\t\"github.com/aws/aws-sdk-go/aws/request\"\n\t\"github.com/aws/aws-sdk-go/awstesting/integration\"\n\t\"github.com/aws/aws-sdk-go/service/pinpointemail\"\n)\n\nvar _ aws.Config\nvar _ awserr.Error\nvar _ request.Request\n\n\nfunc TestInteg_01_PutConfigurationSetTrackingOptions(t *testing.T) {\n\tctx, cancelFn := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancelFn()\n\n\tsess := integration.SessionWithDefaultRegion(\"us-west-2\")\n\tsvc := pinpointemail.New(sess)\n\tparams := &pinpointemail.PutConfigurationSetTrackingOptionsInput{\n\t\tConfigurationSetName: aws.String(\"config-set-name-not-exists\"),\n\t}\n\t_, err := svc.PutConfigurationSetTrackingOptionsWithContext(ctx, params, func(r *request.Request) {\n\t\tr.Handlers.Validate.RemoveByName(\"core.ValidateParametersHandler\")\n\t})\n\tif err == nil {\n\t\tt.Fatalf(\"expect request to fail\")\n\t}\n\taerr, ok := err.(awserr.RequestFailure)\n\tif !ok {\n\t\tt.Fatalf(\"expect awserr, was %T\", err)\n\t}\n\tif len(aerr.Code()) == 0 {\n\t\tt.Errorf(\"expect non-empty error code\")\n\t}\n\tif len(aerr.Message()) == 0 {\n\t\tt.Errorf(\"expect non-empty error message\")\n\t}\n\tif v := aerr.Code(); v == request.ErrCodeSerialization {\n\t\tt.Errorf(\"expect API error code got serialization failure\")\n\t}\n}\n\nfunc TestInteg_00_ListConfigurationSets(t *testing.T) ", "output": "{\n\tctx, cancelFn := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancelFn()\n\n\tsess := integration.SessionWithDefaultRegion(\"us-west-2\")\n\tsvc := pinpointemail.New(sess)\n\tparams := &pinpointemail.ListConfigurationSetsInput{}\n\t_, err := svc.ListConfigurationSetsWithContext(ctx, params, func(r *request.Request) {\n\t\tr.Handlers.Validate.RemoveByName(\"core.ValidateParametersHandler\")\n\t})\n\tif err != nil {\n\t\tt.Errorf(\"expect no error, got %v\", err)\n\t}\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSAmazonMQConfiguration_TagsEntry struct {\n\n\tKey string `json:\"Key,omitempty\"`\n\n\tValue string `json:\"Value,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) AWSCloudFormationType() string {\n\treturn \"AWS::AmazonMQ::Configuration.TagsEntry\"\n}\n\n\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\n\n\n\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) SetMetadata(metadata map[string]interface{}) ", "output": "{\n\tr._metadata = metadata\n}"} {"input": "package camelcase\n\nimport (\n\t\"bytes\"\n\t\"unicode/utf8\"\n\n\t\"github.com/blevesearch/bleve/analysis\"\n\t\"github.com/blevesearch/bleve/registry\"\n)\n\nconst Name = \"camelCase\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype CamelCaseFilter struct{}\n\nfunc NewCamelCaseFilter() *CamelCaseFilter {\n\treturn &CamelCaseFilter{}\n}\n\nfunc (f *CamelCaseFilter) Filter(input analysis.TokenStream) analysis.TokenStream {\n\trv := make(analysis.TokenStream, 0, len(input))\n\n\tnextPosition := 1\n\tfor _, token := range input {\n\t\truneCount := utf8.RuneCount(token.Term)\n\t\trunes := bytes.Runes(token.Term)\n\n\t\tp := NewParser(runeCount, nextPosition, token.Start)\n\t\tfor i := 0; i < runeCount; i++ {\n\t\t\tif i+1 >= runeCount {\n\t\t\t\tp.Push(runes[i], nil)\n\t\t\t} else {\n\t\t\t\tp.Push(runes[i], &runes[i+1])\n\t\t\t}\n\t\t}\n\t\trv = append(rv, p.FlushTokens()...)\n\t\tnextPosition = p.NextPosition()\n\t}\n\treturn rv\n}\n\nfunc CamelCaseFilterConstructor(config map[string]interface{}, cache *registry.Cache) (analysis.TokenFilter, error) {\n\treturn NewCamelCaseFilter(), nil\n}\n\n\n\nfunc init() ", "output": "{\n\tregistry.RegisterTokenFilter(Name, CamelCaseFilterConstructor)\n}"} {"input": "package image\n\n\ntype JPG struct {\n\tRaw []byte\n\tname string\n}\n\n\nfunc (j *JPG) Name() string {\n\treturn j.name\n}\n\n\n\n\nfunc (j *JPG) Data(req Request) []byte ", "output": "{\n\treturn j.Raw\n}"} {"input": "package util\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api/registered\"\n\t\"k8s.io/kubernetes/pkg/client\"\n\t\"k8s.io/kubernetes/pkg/client/clientcmd\"\n)\n\nfunc NewClientCache(loader clientcmd.ClientConfig) *clientCache {\n\treturn &clientCache{\n\t\tclients: make(map[string]*client.Client),\n\t\tconfigs: make(map[string]*client.Config),\n\t\tloader: loader,\n\t}\n}\n\n\n\ntype clientCache struct {\n\tloader clientcmd.ClientConfig\n\tclients map[string]*client.Client\n\tconfigs map[string]*client.Config\n\tdefaultConfig *client.Config\n\tdefaultClient *client.Client\n\tmatchVersion bool\n}\n\n\nfunc (c *clientCache) ClientConfigForVersion(version string) (*client.Config, error) {\n\tif c.defaultConfig == nil {\n\t\tconfig, err := c.loader.ClientConfig()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tc.defaultConfig = config\n\t\tif c.matchVersion {\n\t\t\tif err := client.MatchesServerVersion(c.defaultClient, config); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\tif config, ok := c.configs[version]; ok {\n\t\treturn config, nil\n\t}\n\tconfig := *c.defaultConfig\n\tnegotiatedVersion, err := client.NegotiateVersion(c.defaultClient, &config, version, registered.RegisteredVersions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfig.Version = negotiatedVersion\n\tclient.SetKubernetesDefaults(&config)\n\tc.configs[version] = &config\n\n\treturn &config, nil\n}\n\n\n\n\n\nfunc (c *clientCache) ClientForVersion(version string) (*client.Client, error) ", "output": "{\n\tif client, ok := c.clients[version]; ok {\n\t\treturn client, nil\n\t}\n\tconfig, err := c.ClientConfigForVersion(version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := client.New(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.clients[config.Version] = client\n\treturn client, nil\n}"} {"input": "package iso20022\n\n\ntype CorporateActionEventStageFormat15Choice struct {\n\n\tCode *CorporateActionEventStage4Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification47 `xml:\"Prtry\"`\n}\n\nfunc (c *CorporateActionEventStageFormat15Choice) SetCode(value string) {\n\tc.Code = (*CorporateActionEventStage4Code)(&value)\n}\n\n\n\nfunc (c *CorporateActionEventStageFormat15Choice) AddProprietary() *GenericIdentification47 ", "output": "{\n\tc.Proprietary = new(GenericIdentification47)\n\treturn c.Proprietary\n}"} {"input": "package container\n\nvar _ LogEntry = (*logEntry)(nil)\n\n\n\ntype logEntry struct {\n\tline string\n\tcontainer string\n}\n\nfunc (l logEntry) Line() string {\n\treturn l.line\n}\n\nfunc (l logEntry) Container() string {\n\treturn l.container\n}\n\nfunc NewLogEntry(container, line string) logEntry ", "output": "{\n\treturn logEntry{\n\t\tcontainer: container,\n\t\tline: line,\n\t}\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc main() {\n\ts1 := []string{\"a\", \"\", \"b\", \"\", \"c\", \"\"}\n\ts2 := []string{\"a\", \"\", \"b\", \"\", \"c\", \"\"}\n\ts3 := nonempty(s1)\n\ts4 := nonempty2(s2)\n\tfmt.Printf(\"%q\\n\", s3) \n\tfmt.Printf(\"%q\\n\", s4) \n}\n\nfunc nonempty(strings []string) []string {\n\ti := 0\n\tfor _, s := range strings {\n\t\tif s != \"\" {\n\t\t\tstrings[i] = s\n\t\t\ti++\n\t\t}\n\t}\n\treturn strings[:i]\n}\n\n\n\nfunc nonempty2(strings []string) []string ", "output": "{\n\tout := strings[:0]\n\tfor _, s := range strings {\n\t\tif s != \"\" {\n\t\t\tout = append(out, s)\n\t\t}\n\t}\n\treturn out\n}"} {"input": "package awstasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realIAMInstanceProfile IAMInstanceProfile\n\nfunc (o *IAMInstanceProfile) UnmarshalJSON(data []byte) error {\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realIAMInstanceProfile\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = IAMInstanceProfile(r)\n\treturn nil\n}\n\nvar _ fi.HasName = &IAMInstanceProfile{}\n\nfunc (e *IAMInstanceProfile) GetName() *string {\n\treturn e.Name\n}\n\nfunc (e *IAMInstanceProfile) SetName(name string) {\n\te.Name = &name\n}\n\n\n\nfunc (e *IAMInstanceProfile) String() string ", "output": "{\n\treturn fi.TaskAsString(e)\n}"} {"input": "package model\n\ntype RepoSecret struct {\n\tID int64 `json:\"id\" meddler:\"secret_id,pk\"`\n\n\tRepoID int64 `json:\"-\" meddler:\"secret_repo_id\"`\n\n\tName string `json:\"name\" meddler:\"secret_name\"`\n\n\tValue string `json:\"value\" meddler:\"secret_value\"`\n\n\tImages []string `json:\"image,omitempty\" meddler:\"secret_images,json\"`\n\n\tEvents []string `json:\"event,omitempty\" meddler:\"secret_events,json\"`\n\n\tSkipVerify bool `json:\"skip_verify\" meddler:\"secret_skip_verify\"`\n\n\tConceal bool `json:\"conceal\" meddler:\"secret_conceal\"`\n}\n\n\n\n\n\nfunc (s *RepoSecret) Clone() *RepoSecret {\n\treturn &RepoSecret{\n\t\tID: s.ID,\n\t\tName: s.Name,\n\t\tImages: s.Images,\n\t\tEvents: s.Events,\n\t\tSkipVerify: s.SkipVerify,\n\t\tConceal: s.Conceal,\n\t}\n}\n\n\nfunc (s *RepoSecret) Validate() error {\n\treturn nil\n}\n\nfunc (s *RepoSecret) Secret() *Secret ", "output": "{\n\treturn &Secret{\n\t\tName: s.Name,\n\t\tValue: s.Value,\n\t\tImages: s.Images,\n\t\tEvents: s.Events,\n\t\tSkipVerify: s.SkipVerify,\n\t\tConceal: s.Conceal,\n\t}\n}"} {"input": "package drivers\n\n\ntype DriverType int\n\nconst (\n\tFTP DriverType = iota\n\tSSH\n\tSMB\n\tDAV\n\tNFS\n)\n\nvar driverTypes = []string{\n\t\"ftp\",\n\t\"ssh\",\n\t\"smb\",\n\t\"dav\",\n\t\"nfs\",\n}\n\n\n\nfunc (dt DriverType) String() string ", "output": "{\n\treturn driverTypes[dt]\n}"} {"input": "package server\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n)\n\ntype Rest struct {\n\tchannels map[string]*Channel\n}\n\nfunc NewRestServer(server *Server) *Rest {\n\treturn &Rest{server.channels}\n}\n\nfunc (self *Rest) PostOnly(h http.HandlerFunc) http.HandlerFunc {\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method == \"POST\" {\n\t\t\th(w, r)\n\t\t\treturn\n\t\t}\n\t\thttp.Error(w, \"post only\", http.StatusMethodNotAllowed)\n\t}\n}\n\n\n\nfunc (self *Rest) ListenRest() {\n\n\tlog.Println(\"Listening server(REST)...\")\n\n\thttp.HandleFunc(\"/rest\", self.PostOnly(self.restHandler))\n}\n\nfunc (self *Rest) restHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tbody, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif err := r.Body.Close(); err != nil {\n\t\tpanic(err)\n\t}\n\tchannel := r.URL.Query().Get(\"channel\")\n\tsession := r.Header.Get(\"session\");\n\n\tlog.Printf(\"SessionID: %s\", session)\n\n\tmsg := &Message{Channel: channel, Body: string(body), session: session}\n\tif ch, ok := self.channels[channel]; ok {\n\t\tch.sendAll <- msg\n\t}\n\tlog.Printf(\"[REST] body: %s, channel: %s\", body, channel)\n}"} {"input": "package archive\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/smartystreets/goconvey/convey\"\n)\n\nfunc TestArchiveStaff(t *testing.T) {\n\tconvey.Convey(\"Staff\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\tc = context.Background()\n\t\t\tmid = int64(27515258)\n\t\t)\n\t\tctx.Convey(\"When everything gose positive\", func(ctx convey.C) {\n\t\t\taids, err := d.Staff(c, mid)\n\t\t\tctx.Convey(\"Then err should be nil.aids should not be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(err, convey.ShouldBeNil)\n\t\t\t\tctx.So(len(aids), convey.ShouldBeGreaterThanOrEqualTo, 0)\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc TestArchiveStaffs(t *testing.T) {\n\tconvey.Convey(\"Staffs\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\tc = context.Background()\n\t\t\tmids = []int64{27515258}\n\t\t)\n\t\tctx.Convey(\"When everything gose positive\", func(ctx convey.C) {\n\t\t\taidm, err := d.Staffs(c, mids)\n\t\t\tctx.Convey(\"Then err should be nil.aidm should not be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(err, convey.ShouldBeNil)\n\t\t\t\tctx.So(aidm, convey.ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\t})\n}\n\n\n\nfunc TestArchiveStaffAid(t *testing.T) ", "output": "{\n\tconvey.Convey(\"StaffAid\", t, func(ctx convey.C) {\n\t\tvar (\n\t\t\tc = context.Background()\n\t\t\taid = int64(10110188)\n\t\t)\n\t\tctx.Convey(\"When everything gose positive\", func(ctx convey.C) {\n\t\t\tmids, err := d.StaffAid(c, aid)\n\t\t\tctx.Convey(\"Then err should be nil.mids should not be nil.\", func(ctx convey.C) {\n\t\t\t\tctx.So(err, convey.ShouldBeNil)\n\t\t\t\tctx.So(mids, convey.ShouldNotBeNil)\n\t\t\t})\n\t\t})\n\t})\n}"} {"input": "package muc\n\nimport \"strings\"\n\n\ntype RoomConfigFieldTextMultiValue struct {\n\tvalue []string\n}\n\nfunc newRoomConfigFieldTextMultiValue(values []string) *RoomConfigFieldTextMultiValue {\n\treturn &RoomConfigFieldTextMultiValue{values}\n}\n\n\n\n\n\nfunc (v *RoomConfigFieldTextMultiValue) SetText(lines []string) {\n\tv.value = lines\n}\n\n\nfunc (v *RoomConfigFieldTextMultiValue) Text() string {\n\treturn strings.Join(v.Value(), \" \")\n}\n\nfunc (v *RoomConfigFieldTextMultiValue) Value() []string ", "output": "{\n\treturn v.value\n}"} {"input": "package fenwick\n\n\n\ntype Fenwick struct {\n\ttree []int\n}\n\n\nfunc NewFenwick(n int) *Fenwick {\n\tfen := &Fenwick{\n\t\ttree: make([]int, n),\n\t}\n\tfor i := range fen.tree {\n\t\tfen.tree[i] = 1\n\t}\n\treturn fen\n}\n\n\nfunc (fen *Fenwick) Sum(index int) int {\n\tsum := 1\n\tindex++\n\tfor index > 0 {\n\t\tsum *= fen.tree[index-1]\n\t\tindex -= lsb(index)\n\t}\n\treturn sum\n}\n\n\nfunc lsb(x int) int {\n\treturn x & -x\n}\n\n\nfunc (fen *Fenwick) Update(index, value int) {\n\tindex++\n\tfor index <= fen.Size() {\n\t\tfen.tree[index-1] *= value\n\t\tindex += lsb(index)\n\t}\n}\n\n\n\n\nfunc (fen *Fenwick) Size() int ", "output": "{\n\treturn len(fen.tree)\n}"} {"input": "package docker\n\nimport (\n\t\"github.com/fsouza/go-dockerclient\"\n\t. \"github.com/weaveworks/weave/common\"\n)\n\n\ntype ContainerObserver interface {\n\tContainerDied(ident string) error\n}\n\ntype Client struct {\n\t*docker.Client\n}\n\n\nfunc NewClient(apiPath string) (*Client, error) {\n\tdc, err := docker.NewClient(apiPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &Client{dc}\n\n\tenv, err := client.Version()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tLog.Infof(\"[docker] Using Docker API on %s: %v\", apiPath, env)\n\treturn client, nil\n}\n\n\n\n\n\nfunc (c *Client) IsContainerNotRunning(idStr string) bool {\n\tcontainer, err := c.InspectContainer(idStr)\n\tif err == nil {\n\t\treturn !container.State.Running\n\t}\n\tif _, notThere := err.(*docker.NoSuchContainer); notThere {\n\t\treturn true\n\t}\n\tLog.Errorf(\"[docker] Could not check container status: %s\", err)\n\treturn false\n}\n\nfunc (c *Client) AddObserver(ob ContainerObserver) error ", "output": "{\n\tevents := make(chan *docker.APIEvents)\n\tif err := c.AddEventListener(events); err != nil {\n\t\tLog.Errorf(\"[docker] Unable to add listener to Docker API: %s\", err)\n\t\treturn err\n\t}\n\n\tgo func() {\n\t\tfor event := range events {\n\t\t\tswitch event.Status {\n\t\t\tcase \"die\":\n\t\t\t\tid := event.ID\n\t\t\t\tob.ContainerDied(id)\n\t\t\t}\n\t\t}\n\t}()\n\treturn nil\n}"} {"input": "package sliceset\n\nimport (\n\t\"sort\"\n\n\t\"github.com/xtgo/set\"\n)\n\ntype Set []int\n\nfunc (s Set) Len() int { return len(s) }\n\nfunc (s Set) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (s Set) Copy() Set { return append(Set(nil), s...) }\n\nfunc (s Set) Union(t Set) Set { return s.Do(set.Union, t) }\nfunc (s Set) Inter(t Set) Set { return s.Do(set.Inter, t) }\nfunc (s Set) Diff(t Set) Set { return s.Do(set.Diff, t) }\nfunc (s Set) SymDiff(t Set) Set { return s.Do(set.SymDiff, t) }\nfunc (s Set) IsSub(t Set) bool { return s.DoBool(set.IsSub, t) }\nfunc (s Set) IsSuper(t Set) bool { return s.DoBool(set.IsSuper, t) }\nfunc (s Set) IsInter(t Set) bool { return s.DoBool(set.IsInter, t) }\nfunc (s Set) IsEqual(t Set) bool { return s.DoBool(set.IsEqual, t) }\n\nfunc (s Set) Uniq() Set {\n\tn := set.Uniq(s)\n\treturn s[:n]\n}\n\nfunc (s Set) Do(op set.Op, t Set) Set {\n\tdata := append(s, t...)\n\tn := op(data, len(s))\n\treturn data[:n]\n}\n\ntype BoolOp func(sort.Interface, int) bool\n\nfunc (s Set) DoBool(op BoolOp, t Set) bool {\n\tdata := append(s, t...)\n\treturn op(data, len(s))\n}\n\nfunc (s Set) Less(i, j int) bool ", "output": "{ return s[i] < s[j] }"} {"input": "package restic\n\nimport \"syscall\"\n\nfunc (node Node) restoreSymlinkTimestamps(path string, utimes [2]syscall.Timespec) error {\n\treturn nil\n}\n\nfunc (s statUnix) atim() syscall.Timespec { return s.Atim }\n\nfunc (s statUnix) ctim() syscall.Timespec { return s.Ctim }\n\nfunc (s statUnix) mtim() syscall.Timespec ", "output": "{ return s.Mtim }"} {"input": "package sliceset\n\nimport (\n\t\"sort\"\n\n\t\"github.com/xtgo/set\"\n)\n\ntype Set []int\n\nfunc (s Set) Len() int { return len(s) }\nfunc (s Set) Less(i, j int) bool { return s[i] < s[j] }\nfunc (s Set) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\n\n\nfunc (s Set) Union(t Set) Set { return s.Do(set.Union, t) }\nfunc (s Set) Inter(t Set) Set { return s.Do(set.Inter, t) }\nfunc (s Set) Diff(t Set) Set { return s.Do(set.Diff, t) }\nfunc (s Set) SymDiff(t Set) Set { return s.Do(set.SymDiff, t) }\nfunc (s Set) IsSub(t Set) bool { return s.DoBool(set.IsSub, t) }\nfunc (s Set) IsSuper(t Set) bool { return s.DoBool(set.IsSuper, t) }\nfunc (s Set) IsInter(t Set) bool { return s.DoBool(set.IsInter, t) }\nfunc (s Set) IsEqual(t Set) bool { return s.DoBool(set.IsEqual, t) }\n\nfunc (s Set) Uniq() Set {\n\tn := set.Uniq(s)\n\treturn s[:n]\n}\n\nfunc (s Set) Do(op set.Op, t Set) Set {\n\tdata := append(s, t...)\n\tn := op(data, len(s))\n\treturn data[:n]\n}\n\ntype BoolOp func(sort.Interface, int) bool\n\nfunc (s Set) DoBool(op BoolOp, t Set) bool {\n\tdata := append(s, t...)\n\treturn op(data, len(s))\n}\n\nfunc (s Set) Copy() Set ", "output": "{ return append(Set(nil), s...) }"} {"input": "package filters\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"k8s.io/kubernetes/pkg/auth/authorizer\"\n\t\"k8s.io/kubernetes/pkg/util/runtime\"\n)\n\n\nfunc badGatewayError(w http.ResponseWriter, req *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\tw.WriteHeader(http.StatusBadGateway)\n\tfmt.Fprintf(w, \"Bad Gateway: %#v\", req.RequestURI)\n}\n\n\n\n\nfunc forbiddenMessage(attributes authorizer.Attributes) string {\n\tusername := \"\"\n\tif user := attributes.GetUser(); user != nil {\n\t\tusername = user.GetName()\n\t}\n\n\tresource := attributes.GetResource()\n\tif group := attributes.GetAPIGroup(); len(group) > 0 {\n\t\tresource = resource + \".\" + group\n\t}\n\n\tif ns := attributes.GetNamespace(); len(ns) > 0 {\n\t\treturn fmt.Sprintf(\"User %q cannot %s %s in the namespace %q.\", username, attributes.GetVerb(), resource, ns)\n\t}\n\n\treturn fmt.Sprintf(\"User %q cannot %s %s at the cluster scope.\", username, attributes.GetVerb(), resource)\n}\n\n\nfunc internalError(w http.ResponseWriter, req *http.Request, err error) {\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\tw.WriteHeader(http.StatusInternalServerError)\n\tfmt.Fprintf(w, \"Internal Server Error: %#v: %v\", req.RequestURI, err)\n\truntime.HandleError(err)\n}\n\nfunc forbidden(attributes authorizer.Attributes, w http.ResponseWriter, req *http.Request, reason string) ", "output": "{\n\tmsg := forbiddenMessage(attributes)\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\tw.WriteHeader(http.StatusForbidden)\n\tfmt.Fprintf(w, \"%s: %q\", msg, reason)\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com/zenazn/goji/web\"\n)\n\nfunc fileServeHandler(c web.C, w http.ResponseWriter, r *http.Request) {\n\tfileName := c.URLParams[\"name\"]\n\tfilePath := path.Join(Config.filesDir, fileName)\n\n\tif !fileExistsAndNotExpired(fileName) {\n\t\tnotFoundHandler(c, w, r)\n\t\treturn\n\t}\n\n\tif !Config.allowHotlink {\n\t\treferer := r.Header.Get(\"Referer\")\n\t\tif referer != \"\" && !strings.HasPrefix(referer, Config.siteURL) {\n\t\t\tw.WriteHeader(403)\n\t\t\treturn\n\t\t}\n\t}\n\n\tw.Header().Set(\"Content-Security-Policy\", Config.fileContentSecurityPolicy)\n\n\thttp.ServeFile(w, r, filePath)\n}\n\n\n\nfunc fileExistsAndNotExpired(filename string) bool {\n\tfilePath := path.Join(Config.filesDir, filename)\n\n\t_, err := os.Stat(filePath)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tif isFileExpired(filename) {\n\t\tos.Remove(path.Join(Config.filesDir, filename))\n\t\tos.Remove(path.Join(Config.metaDir, filename))\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc staticHandler(c web.C, w http.ResponseWriter, r *http.Request) ", "output": "{\n\tpath := r.URL.Path\n\tif path[len(path)-1:] == \"/\" {\n\t\tnotFoundHandler(c, w, r)\n\t\treturn\n\t} else {\n\t\tif path == \"/favicon.ico\" {\n\t\t\tpath = \"/static/images/favicon.gif\"\n\t\t}\n\n\t\tfilePath := strings.TrimPrefix(path, \"/static/\")\n\t\tfile, err := staticBox.Open(filePath)\n\t\tif err != nil {\n\t\t\tnotFoundHandler(c, w, r)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Etag\", timeStartedStr)\n\t\tw.Header().Set(\"Cache-Control\", \"max-age=86400\")\n\t\thttp.ServeContent(w, r, filePath, timeStarted, file)\n\t\treturn\n\t}\n}"} {"input": "package cache\n\nimport (\n\t\"github.com/drone/drone/cache\"\n\t\"github.com/gin-gonic/gin\"\n)\n\n\n\nfunc Default() gin.HandlerFunc ", "output": "{\n\tcc := cache.Default()\n\treturn func(c *gin.Context) {\n\t\tcache.ToContext(c, cc)\n\t\tc.Next()\n\t}\n}"} {"input": "package views\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/martini-contrib/sessions\"\n)\n\ntype Views struct {\n\tIndex string\n\ts http.Handler\n}\n\n\n\nfunc (v *Views) ServeHTTP(w http.ResponseWriter, r *http.Request, ss sessions.Session) {\n\tif v.Rewrite(w, r, ss) {\n\t\treturn\n\t}\n\tv.s.ServeHTTP(w, r)\n}\n\nfunc New(fallback string) *Views ", "output": "{\n\tv := &Views{\n\t\tIndex: fallback,\n\t\ts: http.FileServer(http.Dir(\"manager/views/assets\")),\n\t}\n\treturn v\n}"} {"input": "package tests\n\nimport (\n log \"github.com/janekolszak/revfluent\"\n \"github.com/revel/revel/testing\"\n)\n\ntype AppTest struct {\n testing.TestSuite\n}\n\nfunc (t *AppTest) TestError() {\n data := map[string]string{\"message\": \"Error\"}\n log.Error(data)\n}\n\n\n\nfunc (t *AppTest) TestInfo() {\n data := map[string]string{\"message\": \"Info\"}\n log.Info(data)\n}\n\nfunc (t *AppTest) TestLog() {\n data := map[string]string{\"message\": \"Log\"}\n log.Log(\"tag\", data)\n}\n\nfunc (t *AppTest) TestLogger() {\n data := map[string]string{\"message\": \"Logger\"}\n log.Logger.Post(\"tag\", data)\n}\n\nfunc (t *AppTest) TestDebug() ", "output": "{\n data := map[string]string{\"message\": \"Debug\"}\n log.Debug(data)\n}"} {"input": "package log\n\n\nfunc (me *Logging) Prefix() string {\n\treturn me.prefix\n}\n\n\nfunc (me *Logging) SetPrefix(value string) {\n\tme.prefix = value\n\tif me.console != nil {\n\t\tme.console.SetPrefix(me.prefix)\n\t}\n\tif me.dailyfile != nil {\n\t\tme.dailyfile.SetPrefix(me.prefix)\n\t}\n}\n\n\nfunc (me *Logging) Priority() int {\n\treturn me.priority\n}\n\n\nfunc (me *Logging) SetPriority(value int) {\n\tme.setPriority = true\n\tme.priority = value\n\tif me.console != nil {\n\t\tme.console.SetPriority(me.priority)\n\t}\n\tif me.dailyfile != nil {\n\t\tme.dailyfile.SetPriority(me.priority)\n\t}\n}\n\n\nfunc (me *Logging) Layouts() int {\n\treturn me.layouts\n}\n\n\n\n\n\nfunc (me *Logging) Outputs() int {\n\treturn me.outputs\n}\n\n\nfunc (me *Logging) SetOutputs(value int) {\n\tme.setOutputs = true\n\tme.outputs = value\n}\n\nfunc (me *Logging) SetLayouts(value int) ", "output": "{\n\tme.setLayouts = true\n\tme.layouts = value\n\tif me.console != nil {\n\t\tme.console.SetLayouts(me.layouts)\n\t}\n\tif me.dailyfile != nil {\n\t\tme.dailyfile.SetLayouts(me.layouts)\n\t}\n}"} {"input": "package datastore\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\"\n)\n\n\ntype Posix struct {\n\tMountPoint string\n}\n\n\n\n\n\nfunc (p *Posix) Delete(ID string) error {\n\timageName := path.Join(p.MountPoint, ID)\n\n\t_, err := os.Stat(imageName)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\terr = nil\n\t\t}\n\t\treturn err\n\t}\n\n\terr = os.Remove(imageName)\n\n\treturn err\n}\n\n\nfunc (p *Posix) GetImageSize(ID string) (uint64, error) {\n\timageName := path.Join(p.MountPoint, ID)\n\n\tfi, err := os.Stat(imageName)\n\timageSize := uint64(fi.Size())\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"Error getting image size: %v\", err)\n\t}\n\treturn imageSize, nil\n}\n\nfunc (p *Posix) Write(ID string, body io.Reader) (err error) ", "output": "{\n\timageName := path.Join(p.MountPoint, ID)\n\tif _, err := os.Stat(imageName); !os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"image already uploaded with that ID\")\n\t}\n\n\timage, err := os.Create(imageName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbuf := make([]byte, 1<<16)\n\n\t_, err = io.CopyBuffer(image, body, buf)\n\tdefer func() {\n\t\terr1 := image.Close()\n\t\tif err == nil {\n\t\t\terr = err1\n\t\t}\n\t}()\n\n\treturn err\n}"} {"input": "package credentials\n\nimport (\n\t\"errors\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n)\n\n\n\nfunc TestChainProviderIsExpired(t *testing.T) {\n\tstubProvider := &stubProvider{expired: true}\n\tp := &ChainProvider{\n\t\tProviders: []Provider{\n\t\t\tstubProvider,\n\t\t},\n\t}\n\n\tassert.True(t, p.IsExpired(), \"Expect expired to be true before any Retrieve\")\n\t_, err := p.Retrieve()\n\tassert.Nil(t, err, \"Expect no error\")\n\tassert.False(t, p.IsExpired(), \"Expect not expired after retrieve\")\n\n\tstubProvider.expired = true\n\tassert.True(t, p.IsExpired(), \"Expect return of expired provider\")\n\n\t_, err = p.Retrieve()\n\tassert.False(t, p.IsExpired(), \"Expect not expired after retrieve\")\n}\n\nfunc TestChainProviderWithNoProvider(t *testing.T) {\n\tp := &ChainProvider{\n\t\tProviders: []Provider{},\n\t}\n\n\tassert.True(t, p.IsExpired(), \"Expect expired with no providers\")\n\t_, err := p.Retrieve()\n\tassert.Equal(t, ErrNoValidProvidersFoundInChain, err, \"Expect no providers error returned\")\n}\n\nfunc TestChainProviderWithNoValidProvider(t *testing.T) {\n\tp := &ChainProvider{\n\t\tProviders: []Provider{\n\t\t\t&stubProvider{err: errors.New(\"first provider error\")},\n\t\t\t&stubProvider{err: errors.New(\"second provider error\")},\n\t\t},\n\t}\n\n\tassert.True(t, p.IsExpired(), \"Expect expired with no providers\")\n\t_, err := p.Retrieve()\n\tassert.Contains(t, \"no valid providers in chain\", err.Error(), \"Expect no providers error returned\")\n}\n\nfunc TestChainProviderGet(t *testing.T) ", "output": "{\n\tp := &ChainProvider{\n\t\tProviders: []Provider{\n\t\t\t&stubProvider{err: errors.New(\"first provider error\")},\n\t\t\t&stubProvider{err: errors.New(\"second provider error\")},\n\t\t\t&stubProvider{\n\t\t\t\tcreds: Value{\n\t\t\t\t\tAccessKeyID: \"AKID\",\n\t\t\t\t\tSecretAccessKey: \"SECRET\",\n\t\t\t\t\tSessionToken: \"\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tcreds, err := p.Retrieve()\n\tassert.Nil(t, err, \"Expect no error\")\n\tassert.Equal(t, \"AKID\", creds.AccessKeyID, \"Expect access key ID to match\")\n\tassert.Equal(t, \"SECRET\", creds.SecretAccessKey, \"Expect secret access key to match\")\n\tassert.Empty(t, creds.SessionToken, \"Expect session token to be empty\")\n}"} {"input": "package sol\n\n\ntype Operator interface {\n\tWrap(string) string \n}\n\n\nfunc Function(name string, col Columnar) ColumnElem {\n\treturn col.Column().AddOperator(FuncClause{Name: name})\n}\n\n\nfunc Avg(col Columnar) ColumnElem {\n\treturn Function(AVG, col)\n}\n\n\nfunc Count(col Columnar) ColumnElem {\n\treturn Function(COUNT, col)\n}\n\n\n\n\n\n\nfunc DatePart(part string, col Columnar) ColumnElem {\n\treturn col.Column().AddOperator(\n\t\tFuncClause{Name: DATEPART},\n\t).AddOperator(\n\t\tArrayClause{clauses: []Clause{String(part)}, post: true, sep: \", \"},\n\t)\n}\n\n\nfunc Max(col Columnar) ColumnElem {\n\treturn Function(MAX, col)\n}\n\n\nfunc Min(col Columnar) ColumnElem {\n\treturn Function(MIN, col)\n}\n\n\nfunc StdDev(col Columnar) ColumnElem {\n\treturn Function(STDDEV, col)\n}\n\n\nfunc Sum(col Columnar) ColumnElem {\n\treturn Function(SUM, col)\n}\n\n\nfunc Variance(col Columnar) ColumnElem {\n\treturn Function(VARIANCE, col)\n}\n\nfunc Date(col Columnar) ColumnElem ", "output": "{\n\treturn Function(DATE, col)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n)\n\n\n\nfunc main() {\n\tconst filename = \"abc.txt\"\n\tif contents, err := ioutil.ReadFile(filename); err != nil {\n\t\tfmt.Println(err)\n\t} else {\n\t\tfmt.Printf(\"%s\\n\", contents)\n\t}\n\n\tfmt.Println(\n\t\tgrade(0),\n\t\tgrade(59),\n\t\tgrade(60),\n\t\tgrade(82),\n\t\tgrade(99),\n\t\tgrade(100),\n\t)\n}\n\nfunc grade(score int) string ", "output": "{\n\tg := \"\"\n\tswitch {\n\tcase score < 0 || score > 100:\n\t\tpanic(fmt.Sprintf(\"Wrong score: %d\", score))\n\tcase score < 60:\n\t\tg = \"F\"\n\tcase score < 80:\n\t\tg = \"C\"\n\tcase score < 90:\n\t\tg = \"B\"\n\tcase score <= 100:\n\t\tg = \"A\"\n\t}\n\treturn g\n}"} {"input": "package wire\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\n\n\n\n\ntype MsgPong struct {\n\tNonce uint64\n}\n\n\n\nfunc (msg *MsgPong) BtcDecode(r io.Reader, pver uint32) error {\n\tif pver <= BIP0031Version {\n\t\tstr := fmt.Sprintf(\"pong message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgPong.BtcDecode\", str)\n\t}\n\n\treturn readElement(r, &msg.Nonce)\n}\n\n\n\nfunc (msg *MsgPong) BtcEncode(w io.Writer, pver uint32) error {\n\tif pver <= BIP0031Version {\n\t\tstr := fmt.Sprintf(\"pong message invalid for protocol \"+\n\t\t\t\"version %d\", pver)\n\t\treturn messageError(\"MsgPong.BtcEncode\", str)\n\t}\n\n\treturn writeElement(w, msg.Nonce)\n}\n\n\n\n\n\n\n\nfunc (msg *MsgPong) MaxPayloadLength(pver uint32) uint32 {\n\tplen := uint32(0)\n\tif pver > BIP0031Version {\n\t\tplen += 8\n\t}\n\n\treturn plen\n}\n\n\n\nfunc NewMsgPong(nonce uint64) *MsgPong {\n\treturn &MsgPong{\n\t\tNonce: nonce,\n\t}\n}\n\nfunc (msg *MsgPong) Command() string ", "output": "{\n\treturn CmdPong\n}"} {"input": "package local\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/apache/beam/sdks/go/pkg/beam/io/textio\"\n)\n\nfunc init() {\n\ttextio.RegisterFileSystem(\"default\", New)\n}\n\ntype fs struct{}\n\n\nfunc New(ctx context.Context) textio.FileSystem {\n\treturn &fs{}\n}\n\nfunc (f *fs) Close() error {\n\treturn nil\n}\n\nfunc (f *fs) List(ctx context.Context, glob string) ([]string, error) {\n\treturn filepath.Glob(glob)\n}\n\n\n\nfunc (f *fs) OpenWrite(ctx context.Context, filename string) (io.WriteCloser, error) {\n\tif err := os.MkdirAll(filepath.Dir(filename), 0755); err != nil {\n\t\treturn nil, err\n\t}\n\treturn os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)\n}\n\nfunc (f *fs) OpenRead(ctx context.Context, filename string) (io.ReadCloser, error) ", "output": "{\n\treturn os.Open(filename)\n}"} {"input": "package spec\n\nimport (\n\t\"encoding/json\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestXmlObject_Serialize(t *testing.T) {\n\tobj1 := XMLObject{}\n\tactual, err := json.Marshal(obj1)\n\tif assert.NoError(t, err) {\n\t\tassert.Equal(t, \"{}\", string(actual))\n\t}\n\n\tobj2 := XMLObject{\n\t\tName: \"the name\",\n\t\tNamespace: \"the namespace\",\n\t\tPrefix: \"the prefix\",\n\t\tAttribute: true,\n\t\tWrapped: true,\n\t}\n\n\tactual, err = json.Marshal(obj2)\n\tif assert.NoError(t, err) {\n\t\tvar ad map[string]interface{}\n\t\tif assert.NoError(t, json.Unmarshal(actual, &ad)) {\n\t\t\tassert.Equal(t, obj2.Name, ad[\"name\"])\n\t\t\tassert.Equal(t, obj2.Namespace, ad[\"namespace\"])\n\t\t\tassert.Equal(t, obj2.Prefix, ad[\"prefix\"])\n\t\t\tassert.True(t, ad[\"attribute\"].(bool))\n\t\t\tassert.True(t, ad[\"wrapped\"].(bool))\n\t\t}\n\t}\n}\n\n\n\nfunc TestXmlObject_Deserialize(t *testing.T) ", "output": "{\n\texpected := XMLObject{}\n\tactual := XMLObject{}\n\tif assert.NoError(t, json.Unmarshal([]byte(\"{}\"), &actual)) {\n\t\tassert.Equal(t, expected, actual)\n\t}\n\n\tcompleted := `{\"name\":\"the name\",\"namespace\":\"the namespace\",\"prefix\":\"the prefix\",\"attribute\":true,\"wrapped\":true}`\n\texpected = XMLObject{\"the name\", \"the namespace\", \"the prefix\", true, true}\n\tactual = XMLObject{}\n\tif assert.NoError(t, json.Unmarshal([]byte(completed), &actual)) {\n\t\tassert.Equal(t, expected, actual)\n\t}\n}"} {"input": "package clang\n\n\n\n\nimport \"C\"\n\n\ntype Version struct {\n\tc C.CXVersion\n}\n\n\nfunc (v Version) Major() int {\n\treturn int(v.c.Major)\n}\n\n\nfunc (v Version) Minor() int {\n\treturn int(v.c.Minor)\n}\n\n\n\n\nfunc (v Version) Subminor() int ", "output": "{\n\treturn int(v.c.Subminor)\n}"} {"input": "package circuitbreaker\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n\n\t\"github.com/mailgun/log\"\n\t\"github.com/mailgun/vulcan/netutils\"\n)\n\ntype SideEffect interface {\n\tExec() error\n}\n\ntype Webhook struct {\n\tURL string\n\tMethod string\n\tHeaders http.Header\n\tForm url.Values\n\tBody []byte\n}\n\ntype WebhookSideEffect struct {\n\tw Webhook\n}\n\nfunc NewWebhookSideEffect(w Webhook) (*WebhookSideEffect, error) {\n\tif w.Method == \"\" {\n\t\treturn nil, fmt.Errorf(\"Supply method\")\n\t}\n\t_, err := netutils.ParseUrl(w.URL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &WebhookSideEffect{w: w}, nil\n}\n\n\n\nfunc (w *WebhookSideEffect) Exec() error {\n\tr, err := http.NewRequest(w.w.Method, w.w.URL, w.getBody())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(w.w.Headers) != 0 {\n\t\tnetutils.CopyHeaders(r.Header, w.w.Headers)\n\t}\n\tif len(w.w.Form) != 0 {\n\t\tr.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\t}\n\tre, err := http.DefaultClient.Do(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif re.Body != nil {\n\t\tdefer re.Body.Close()\n\t}\n\tbody, err := ioutil.ReadAll(re.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Infof(\"%v got response: (%s): %s\", w, re.Status, string(body))\n\treturn nil\n}\n\nfunc (w *WebhookSideEffect) getBody() io.Reader ", "output": "{\n\tif len(w.w.Form) != 0 {\n\t\treturn strings.NewReader(w.w.Form.Encode())\n\t}\n\tif len(w.w.Body) != 0 {\n\t\treturn bytes.NewBuffer(w.w.Body)\n\t}\n\treturn nil\n}"} {"input": "package apm\n\nimport (\n\t\"fmt\"\n)\n\n\ntype KeyTransaction struct {\n\tID int `json:\"id,omitempty\"`\n\tName string `json:\"name,omitempty\"`\n\tTransactionName string `json:\"transaction_name,omitempty\"`\n\tHealthStatus string `json:\"health_status,omitempty\"`\n\tLastReportedAt string `json:\"last_reported_at,omitempty\"`\n\tReporting bool `json:\"reporting\"`\n\tSummary ApplicationSummary `json:\"application_summary,omitempty\"`\n\tEndUserSummary ApplicationEndUserSummary `json:\"end_user_summary,omitempty\"`\n\tLinks KeyTransactionLinks `json:\"links,omitempty\"`\n}\n\n\ntype KeyTransactionLinks struct {\n\tApplication int `json:\"application,omitempty\"`\n}\n\n\n\ntype ListKeyTransactionsParams struct {\n\tName string `url:\"filter[name],omitempty\"`\n\tIDs []int `url:\"filter[ids],omitempty,comma\"`\n}\n\n\nfunc (a *APM) ListKeyTransactions(params *ListKeyTransactionsParams) ([]*KeyTransaction, error) {\n\tresults := []*KeyTransaction{}\n\tnextURL := a.config.Region().RestURL(\"key_transactions.json\")\n\n\tfor nextURL != \"\" {\n\t\tresponse := keyTransactionsResponse{}\n\t\tresp, err := a.client.Get(nextURL, ¶ms, &response)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tresults = append(results, response.KeyTransactions...)\n\n\t\tpaging := a.pager.Parse(resp)\n\t\tnextURL = paging.Next\n\t}\n\n\treturn results, nil\n}\n\n\n\n\ntype keyTransactionsResponse struct {\n\tKeyTransactions []*KeyTransaction `json:\"key_transactions,omitempty\"`\n}\n\ntype keyTransactionResponse struct {\n\tKeyTransaction KeyTransaction `json:\"key_transaction,omitempty\"`\n}\n\nfunc (a *APM) GetKeyTransaction(id int) (*KeyTransaction, error) ", "output": "{\n\tresponse := keyTransactionResponse{}\n\turl := fmt.Sprintf(\"/key_transactions/%d.json\", id)\n\n\t_, err := a.client.Get(a.config.Region().RestURL(url), nil, &response)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &response.KeyTransaction, nil\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"time\"\n \"net/http\"\n \"encoding/json\"\n \"io/ioutil\"\n\n \"github.com/gorilla/mux\"\n)\n\ntype Play struct {\n Key string `json:\"key\" redis:\"-\"`\n SeasonKey string `json:\"season_key\" redis:\"season_key\"`\n QueenKey string `json:\"queen_key\" redis:\"queen_key\"`\n PlayTypeKey string `json:\"play_type_key\" redis:\"play_type_key\"`\n EpisodeKey string `json:\"episode_key\" redis:\"episode_key\"`\n Timestamp int64 `json:\"timestamp\" redis:\"timestamp\"`\n}\n\nfunc PostPlay(w http.ResponseWriter, r *http.Request) {\n fmt.Println(\"PostPlay\")\n\n var new_play Play\n b, _ := ioutil.ReadAll(r.Body)\n fmt.Println(string(b))\n json.Unmarshal(b, &new_play)\n\n\n season_key := mux.Vars(r)[\"season_id\"]\n new_play.SeasonKey = season_key\n new_play.Timestamp = time.Now().Unix()\n\n _, success := AddObject(\"play\", new_play)\n if success {\n fmt.Fprintf(w, \"201 Created\")\n } else {\n \n fmt.Fprintf(w, \"ERR\")\n }\n}\n\n\n\nfunc DeletePlay(w http.ResponseWriter, r *http.Request) ", "output": "{\n season_key := mux.Vars(r)[\"season_id\"]\n play_key := mux.Vars(r)[\"play_key\"]\n\n fmt.Println(\"DELTE play: \", play_key)\n\n var del_play Play\n del_play.Key = play_key\n success := GetObject(play_key, &del_play)\n fmt.Println(\"GOT QUEEN: \", del_play)\n if (season_key != del_play.SeasonKey) {\n fmt.Println(\"Hey, you are trying todelerte a play that doesn't belong here.\")\n success = false\n }\n\n if (success) {\n success = DeleteObject(\"play\", play_key, del_play)\n }\n\n if (success) {\n fmt.Fprintf(w, \"200 OK (deleted)\")\n } else {\n fmt.Fprintf(w, \"KEY DOES NOT EXIST\")\n }\n\n}"} {"input": "package geom\n\nimport \"math\"\n\n\ntype Vertex struct {\n\tX, Y float64\n}\n\n\ntype Vertices []Vertex\n\n\n\n\n\nfunc (c Vertex) SideOfLine(a Vertex, b Vertex) int {\n\n\tcross := float64((b.X-a.X)*(c.Y-a.Y) - (b.Y-a.Y)*(c.X-a.X))\n\n\tif cross == 0 {\n\t\treturn 0\n\t}\n\tif math.Signbit(cross) {\n\t\treturn 1\n\t}\n\treturn -1\n\n}\n\n\ntype Lexographically []Vertex\n\nfunc (a Lexographically) Len() int { return len(a) }\nfunc (a Lexographically) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a Lexographically) Less(i, j int) bool {\n\tif a[i].X == a[j].X {\n\t\treturn a[i].Y < a[j].Y\n\t}\n\treturn a[i].X < a[j].X\n}\n\nfunc (l Vertices) Convert() (data []float32) ", "output": "{\n\n\tdata = make([]float32, len(l)*2)\n\tfor i, v := range l {\n\t\tindex := i * 2\n\t\tdata[index] = float32(v.X)\n\t\tdata[index+1] = float32(v.Y)\n\t}\n\treturn\n}"} {"input": "package httpx\n\nimport (\n\t\"net/http\"\n\n\t\"golang.org/x/net/context\"\n)\n\nvar clientContextKey = 0\nvar defaultClient = &http.Client{}\n\n\n\n\nfunc ClientFromContext(ctx context.Context) *http.Client {\n\tfound := ctx.Value(&clientContextKey)\n\n\tif found == nil {\n\t\treturn defaultClient\n\t}\n\n\treturn found.(*http.Client)\n}\n\n\n\n\n\n\nfunc ClientContext(parent context.Context, client *http.Client) context.Context ", "output": "{\n\tif client == nil {\n\t\tpanic(\"Cannot bind nil *http.Client to context tree\")\n\t}\n\n\treturn context.WithValue(parent, &clientContextKey, client)\n}"} {"input": "package log\n\nimport (\n\t. \"github.com/limetext/lime-backend/lib/util\"\n\t\"github.com/limetext/log4go\"\n\t\"sync\"\n)\n\ntype (\n\tLogWriter interface {\n\t\tlog4go.LogWriter\n\t}\n\n\tlogWriter struct {\n\t\tLogWriter\n\t\tlog chan string\n\t\thandler func(string)\n\t\tlock sync.Mutex\n\t}\n)\n\nfunc NewLogWriter(h func(string)) *logWriter {\n\tret := &logWriter{\n\t\tlog: make(chan string, 100),\n\t\thandler: h,\n\t}\n\tgo ret.handle()\n\treturn ret\n}\n\n\n\n\n\nfunc (l *logWriter) LogWrite(rec *log4go.LogRecord) {\n\tp := Prof.Enter(\"log\")\n\tdefer p.Exit()\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\tfl := log4go.FormatLogRecord(log4go.FORMAT_DEFAULT, rec)\n\tl.log <- fl\n}\n\nfunc (l *logWriter) Close() {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\tclose(l.log)\n}\n\nfunc (l *logWriter) handle() ", "output": "{\n\tfor fl := range l.log {\n\t\tl.handler(fl)\n\t}\n}"} {"input": "package handle\n\nimport (\n \n \"net/http\"\n)\n\n\ntype HTTPErrorPipeline struct {\n Code int\n Message string\n Global GlobalPipeline\n}\n\n\nfunc NewError(code int, message string) HTTPErrorPipeline {\n return HTTPErrorPipeline{\n Code: code,\n Message: message,\n Global: DefaultGlobalPipeline,\n }\n}\n\n\n\n\nfunc ReturnError(w http.ResponseWriter, code int) int ", "output": "{\n w.WriteHeader(code)\n tpl, _ := OpenTemplate(ERROR_TPL)\n tpl.Execute(w, NewError(code, http.StatusText(code)))\n return code\n}"} {"input": "package mock_driver\n\nimport (\n\tnet \"net\"\n\treflect \"reflect\"\n\n\tgomock \"github.com/golang/mock/gomock\"\n)\n\n\ntype MockNetworkAPIs struct {\n\tctrl *gomock.Controller\n\trecorder *MockNetworkAPIsMockRecorder\n}\n\n\ntype MockNetworkAPIsMockRecorder struct {\n\tmock *MockNetworkAPIs\n}\n\n\nfunc NewMockNetworkAPIs(ctrl *gomock.Controller) *MockNetworkAPIs {\n\tmock := &MockNetworkAPIs{ctrl: ctrl}\n\tmock.recorder = &MockNetworkAPIsMockRecorder{mock}\n\treturn mock\n}\n\n\nfunc (m *MockNetworkAPIs) EXPECT() *MockNetworkAPIsMockRecorder {\n\treturn m.recorder\n}\n\n\nfunc (m *MockNetworkAPIs) SetupNS(arg0, arg1, arg2 string, arg3 *net.IPNet, arg4 int, arg5 []string, arg6 bool) error {\n\tret := m.ctrl.Call(m, \"SetupNS\", arg0, arg1, arg2, arg3, arg4, arg5, arg6)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}\n\n\nfunc (mr *MockNetworkAPIsMockRecorder) SetupNS(arg0, arg1, arg2, arg3, arg4, arg5, arg6 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SetupNS\", reflect.TypeOf((*MockNetworkAPIs)(nil).SetupNS), arg0, arg1, arg2, arg3, arg4, arg5, arg6)\n}\n\n\nfunc (m *MockNetworkAPIs) TeardownNS(arg0 *net.IPNet, arg1 int) error {\n\tret := m.ctrl.Call(m, \"TeardownNS\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}\n\n\n\n\nfunc (mr *MockNetworkAPIsMockRecorder) TeardownNS(arg0, arg1 interface{}) *gomock.Call ", "output": "{\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"TeardownNS\", reflect.TypeOf((*MockNetworkAPIs)(nil).TeardownNS), arg0, arg1)\n}"} {"input": "package main\n\nimport (\n\t\"go/ast\"\n\t\"reflect\"\n\t\"strconv\"\n)\n\n\n\n\ntype BadTypeUsedInTests struct {\n\tX int \"hello\" \n}\n\nfunc (f *File) checkCanonicalFieldTag(field *ast.Field) ", "output": "{\n\tif !*vetStructTags && !*vetAll {\n\t\treturn\n\t}\n\tif field.Tag == nil {\n\t\treturn\n\t}\n\n\ttag, err := strconv.Unquote(field.Tag.Value)\n\tif err != nil {\n\t\tf.Warnf(field.Pos(), \"unable to read struct tag %s\", field.Tag.Value)\n\t\treturn\n\t}\n\n\tif reflect.StructTag(tag+` _gofix:\"_magic\"`).Get(\"_gofix\") != \"_magic\" {\n\t\tf.Warnf(field.Pos(), \"struct field tag %s not compatible with reflect.StructTag.Get\", field.Tag.Value)\n\t\treturn\n\t}\n}"} {"input": "package pike\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/stevearc/pike/plog\"\n)\n\nfunc remove(stringArr []string, str string) {\n\tfor i, s := range stringArr {\n\t\tif s == str {\n\t\t\tstringArr[i] = \"\"\n\t\t\tbreak\n\t\t}\n\t}\n}\n\n\n\n\nfunc Glob(root string, patterns ...string) *Node {\n\tsourceFunc := func(in, out []chan File) {\n\t\tpaths := make([]string, 0, 10)\n\t\tfor _, pattern := range patterns {\n\t\t\tif pattern[0] == '!' {\n\t\t\t\tfor _, unmatch := range matchRecursive(root, pattern[1:]) {\n\t\t\t\t\tremove(paths, unmatch)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tpaths = append(paths, matchRecursive(root, pattern)...)\n\t\t\t}\n\t\t}\n\t\tseenPaths := make(map[string]bool)\n\t\tfor _, name := range paths {\n\t\t\tif name == \"\" || seenPaths[name] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tseenPaths[name] = true\n\t\t\tfullpath := filepath.Join(root, name)\n\t\t\tdata, err := ioutil.ReadFile(fullpath)\n\t\t\tif err != nil {\n\t\t\t\tplog.Error(\"Error reading file %q\", fullpath)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tout[0] <- NewFile(root, name, data)\n\t\t}\n\t\tclose(out[0])\n\t}\n\trunner := FxnRunnable(sourceFunc)\n\treturn NewNode(fmt.Sprintf(\"%s -> %s\", root, strings.Join(patterns, \":\")), 0, 0, 1, 1, runner)\n}\n\n\n\nfunc matchRecursive(root, pattern string) []string ", "output": "{\n\tpaths := make([]string, 0, 10)\n\tfullRoot := root\n\tsubRoot, pattern := filepath.Split(pattern)\n\tif subRoot != \"\" {\n\t\tfullRoot = filepath.Join(root, subRoot)\n\t}\n\tfilepath.Walk(fullRoot, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\tplog.Exc(err)\n\t\t\treturn nil\n\t\t}\n\t\tif info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\t\tsubpath := path[len(root)+1:]\n\t\tmatched, err := filepath.Match(pattern, filepath.Base(path))\n\t\tif err != nil {\n\t\t\tplog.Exc(err)\n\t\t\treturn nil\n\t\t}\n\t\tif matched {\n\t\t\tpaths = append(paths, subpath)\n\t\t}\n\t\treturn nil\n\t})\n\treturn paths\n}"} {"input": "package udnssdk\n\nimport (\n\t\"log\"\n\t\"time\"\n)\n\n\ntype AlertsService struct {\n\tclient *Client\n}\n\n\ntype ProbeAlertDataDTO struct {\n\tPoolRecord string `json:\"poolRecord\"`\n\tProbeType string `json:\"probeType\"`\n\tProbeStatus string `json:\"probeStatus\"`\n\tAlertDate time.Time `json:\"alertDate\"`\n\tFailoverOccured bool `json:\"failoverOccured\"`\n\tOwnerName string `json:\"ownerName\"`\n\tStatus string `json:\"status\"`\n}\n\n\ntype ProbeAlertDataListDTO struct {\n\tAlerts []ProbeAlertDataDTO `json:\"alerts\"`\n\tQueryinfo QueryInfo `json:\"queryInfo\"`\n\tResultinfo ResultInfo `json:\"resultInfo\"`\n}\n\n\n\n\n\nfunc (s *AlertsService) SelectWithOffset(k RRSetKey, offset int) ([]ProbeAlertDataDTO, ResultInfo, *Response, error) {\n\tvar ald ProbeAlertDataListDTO\n\n\turi := k.AlertsQueryURI(offset)\n\tres, err := s.client.get(uri, &ald)\n\n\tas := []ProbeAlertDataDTO{}\n\tfor _, a := range ald.Alerts {\n\t\tas = append(as, a)\n\t}\n\treturn as, ald.Resultinfo, res, err\n}\n\nfunc (s *AlertsService) Select(k RRSetKey) ([]ProbeAlertDataDTO, error) ", "output": "{\n\tmaxerrs := 5\n\twaittime := 5 * time.Second\n\n\tas := []ProbeAlertDataDTO{}\n\toffset := 0\n\terrcnt := 0\n\n\tfor {\n\t\treqAlerts, ri, res, err := s.SelectWithOffset(k, offset)\n\t\tif err != nil {\n\t\t\tif res.StatusCode >= 500 {\n\t\t\t\terrcnt = errcnt + 1\n\t\t\t\tif errcnt < maxerrs {\n\t\t\t\t\ttime.Sleep(waittime)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn as, err\n\t\t}\n\n\t\tlog.Printf(\"ResultInfo: %+v\\n\", ri)\n\t\tfor _, a := range reqAlerts {\n\t\t\tas = append(as, a)\n\t\t}\n\t\tif ri.ReturnedCount+ri.Offset >= ri.TotalCount {\n\t\t\treturn as, nil\n\t\t}\n\t\toffset = ri.ReturnedCount + ri.Offset\n\t\tcontinue\n\t}\n}"} {"input": "package client\n\nimport (\n\t\"context\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"time\"\n\n\t\"github.com/remind101/pkg/client/metadata\"\n\t\"github.com/remind101/pkg/client/request\"\n)\n\n\ntype Client struct {\n\tInfo metadata.ClientInfo \n\tHTTPClient *http.Client \n\tHandlers request.Handlers \n}\n\n\ntype ClientOpt func(*Client)\n\n\nfunc Timeout(t time.Duration) ClientOpt {\n\treturn func(c *Client) {\n\t\tc.HTTPClient.Timeout = t\n\t}\n}\n\n\nfunc RoundTripper(r http.RoundTripper) ClientOpt {\n\treturn func(c *Client) {\n\t\tc.HTTPClient.Transport = r\n\t}\n}\n\n\nfunc BasicAuth(username, password string) ClientOpt {\n\treturn func(c *Client) {\n\t\tc.Handlers.Build.Append(request.BasicAuther(username, password))\n\t}\n}\n\n\nfunc RequestSigning(id, key string) ClientOpt {\n\treturn func(c *Client) {\n\t\tc.Handlers.Sign.Append(request.RequestSigner(id, key))\n\t}\n}\n\n\nfunc DebugLogging(c *Client) {\n\tc.Handlers.Send.Prepend(request.RequestLogger)\n\tc.Handlers.Send.Append(request.ResponseLogger)\n}\n\n\n\n\n\n\n\n\nfunc (c *Client) NewRequest(ctx context.Context, method, path string, params interface{}, data interface{}) *request.Request {\n\thttpReq, _ := http.NewRequest(method, path, nil)\n\thttpReq = httpReq.WithContext(ctx)\n\thttpReq.URL, _ = url.Parse(c.Info.Endpoint + path)\n\n\tr := request.New(httpReq, c.Info, c.Handlers.Copy(), params, data)\n\tr.HTTPClient = c.HTTPClient\n\treturn r\n}\n\nfunc New(info metadata.ClientInfo, options ...ClientOpt) *Client ", "output": "{\n\tc := &Client{\n\t\tInfo: info,\n\t\tHandlers: request.DefaultHandlers(),\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: 60 * time.Second,\n\t\t\tTransport: &http.Transport{\n\t\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\t\tDialContext: (&net.Dialer{\n\t\t\t\t\tTimeout: 1 * time.Second,\n\t\t\t\t\tKeepAlive: 90 * time.Second,\n\t\t\t\t}).DialContext,\n\t\t\t\tTLSHandshakeTimeout: 3 * time.Second,\n\t\t\t\tMaxIdleConns: 100,\n\t\t\t\tMaxIdleConnsPerHost: 8,\n\t\t\t\tIdleConnTimeout: 90 * time.Second,\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, option := range options {\n\t\toption(c)\n\t}\n\n\treturn c\n}"} {"input": "package match\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\nfunc Match(t *testing.T, value interface{}) *Matcher {\n\treturn &Matcher{\n\t\tt: t,\n\t\tvalue: value,\n\t}\n}\n\n\n\n\n\nfunc IsNotNil(t *testing.T, value interface{}) *Matcher {\n\treturn Match(t, value).IsNotNil()\n}\n\n\nfunc Equals(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).Equals(other)\n}\n\n\nfunc NotEquals(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).NotEquals(other)\n}\n\n\nfunc LessThan(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).LessThan(other)\n}\n\n\nfunc GreaterThan(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).GreaterThan(other)\n}\n\n\nfunc Contains(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).Contains(other)\n}\n\n\nfunc Matches(t *testing.T, value interface{}, pattern string) *Matcher {\n\treturn Match(t, value).Matches(pattern)\n}\n\n\nfunc KindOf(t *testing.T, value interface{}, kind reflect.Kind) *Matcher {\n\treturn Match(t, value).KindOf(kind)\n}\n\nfunc IsNil(t *testing.T, value interface{}) *Matcher ", "output": "{\n\treturn Match(t, value).IsNil()\n}"} {"input": "package sync2\n\n\n\n\n\nimport (\n\t\"time\"\n)\n\n\n\ntype Semaphore struct {\n\tslots chan struct{}\n\ttimeout time.Duration\n}\n\n\n\nfunc NewSemaphore(count int, timeout time.Duration) *Semaphore {\n\tsem := &Semaphore{\n\t\tslots: make(chan struct{}, count),\n\t\ttimeout: timeout,\n\t}\n\tfor i := 0; i < count; i++ {\n\t\tsem.slots <- struct{}{}\n\t}\n\treturn sem\n}\n\n\n\n\n\n\n\n\nfunc (sem *Semaphore) Release() {\n\tsem.slots <- struct{}{}\n}\n\nfunc (sem *Semaphore) Acquire() bool ", "output": "{\n\tif sem.timeout == 0 {\n\t\t<-sem.slots\n\t\treturn true\n\t}\n\tselect {\n\tcase <-sem.slots:\n\t\treturn true\n\tcase <-time.After(sem.timeout):\n\t\treturn false\n\t}\n}"} {"input": "package gtreap\n\nimport (\n\t\"math/rand\"\n\n\t\"github.com/blevesearch/bleve/index/store\"\n)\n\nfunc (w *Writer) BytesSafeAfterClose() bool {\n\treturn false\n}\n\nfunc (w *Writer) Get(k []byte) (v []byte, err error) {\n\tw.s.m.Lock()\n\tt := w.s.t\n\tw.s.m.Unlock()\n\n\titm := t.Get(&Item{k: k})\n\tif itm != nil {\n\t\treturn itm.(*Item).v, nil\n\t}\n\treturn nil, nil\n}\n\nfunc (w *Writer) Iterator(k []byte) store.KVIterator {\n\tw.s.m.Lock()\n\tt := w.s.t\n\tw.s.m.Unlock()\n\n\treturn newIterator(t).restart(&Item{k: k})\n}\n\nfunc (w *Writer) Close() error {\n\tw.s.availableWriters <- true\n\tw.s = nil\n\n\treturn nil\n}\n\n\n\nfunc (w *Writer) Delete(k []byte) (err error) {\n\tw.s.m.Lock()\n\tw.s.t = w.s.t.Delete(&Item{k: k})\n\tw.s.m.Unlock()\n\n\treturn nil\n}\n\nfunc (w *Writer) NewBatch() store.KVBatch {\n\treturn store.NewEmulatedBatch(w, w.s.mo)\n}\n\nfunc (w *Writer) Set(k, v []byte) (err error) ", "output": "{\n\tw.s.m.Lock()\n\tw.s.t = w.s.t.Upsert(&Item{k: k, v: v}, rand.Int())\n\tw.s.m.Unlock()\n\n\treturn nil\n}"} {"input": "package common\n\ntype mockUploader struct {\n}\n\nfunc (uploader *mockUploader) Upload(destination string, path string) error {\n\treturn nil\n}\n\nfunc (uploader *mockUploader) Url(sourceAssetId, templateId, placeholderSize string, page int32) string {\n\treturn \"mock://\" + sourceAssetId\n}\n\n\n\nfunc newMockUploader() Uploader ", "output": "{\n\treturn new(mockUploader)\n}"} {"input": "package endpoints_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\n\n\nfunc TestEndpoints_ClusterCreateTCPSocket(t *testing.T) {\n\tendpoints, config, cleanup := newEndpoints(t)\n\tdefer cleanup()\n\n\tconfig.NetworkAddress = \"127.0.0.1:12345\"\n\tconfig.ClusterAddress = \"127.0.0.1:54321\"\n\trequire.NoError(t, endpoints.Up(config))\n\n\tassert.NoError(t, httpGetOverTLSSocket(endpoints.NetworkAddressAndCert()))\n\tassert.NoError(t, httpGetOverTLSSocket(endpoints.ClusterAddressAndCert()))\n}\n\n\n\n\n\nfunc TestEndpoints_ClusterUpdateAddressIsCovered(t *testing.T) ", "output": "{\n\tendpoints, config, cleanup := newEndpoints(t)\n\tdefer cleanup()\n\n\tconfig.NetworkAddress = \"[::]:12345\"\n\tconfig.ClusterAddress = \"\"\n\trequire.NoError(t, endpoints.Up(config))\n\n\trequire.NoError(t, endpoints.ClusterUpdateAddress(\"127.0.0.1:12345\"))\n\n\tassert.NoError(t, httpGetOverTLSSocket(endpoints.NetworkAddressAndCert()))\n}"} {"input": "package client\n\nimport (\n\t\"log\"\n\t\"net/http\"\n)\n\n\n\n\nfunc Last(l *log.Logger) Decorator ", "output": "{\n\treturn func(c Client) Client {\n\t\treturn ClientFunc(func(r *http.Request) (*http.Response, error) {\n\t\t\tl.Println(\"last\")\n\t\t\treturn c.Do(r)\n\t\t})\n\t}\n}"} {"input": "package box\n\nimport (\n\t\"golang.org/x/crypto/curve25519\"\n\t\"golang.org/x/crypto/nacl/secretbox\"\n\t\"golang.org/x/crypto/salsa20/salsa\"\n\t\"io\"\n)\n\n\nconst Overhead = secretbox.Overhead\n\n\n\n\n\nvar zeros [16]byte\n\n\n\n\n\nfunc Precompute(sharedKey, peersPublicKey, privateKey *[32]byte) {\n\tcurve25519.ScalarMult(sharedKey, privateKey, peersPublicKey)\n\tsalsa.HSalsa20(sharedKey, &zeros, sharedKey, &salsa.Sigma)\n}\n\n\n\n\nfunc Seal(out, message []byte, nonce *[24]byte, peersPublicKey, privateKey *[32]byte) []byte {\n\tvar sharedKey [32]byte\n\tPrecompute(&sharedKey, peersPublicKey, privateKey)\n\treturn secretbox.Seal(out, message, nonce, &sharedKey)\n}\n\n\n\nfunc SealAfterPrecomputation(out, message []byte, nonce *[24]byte, sharedKey *[32]byte) []byte {\n\treturn secretbox.Seal(out, message, nonce, sharedKey)\n}\n\n\n\n\nfunc Open(out, box []byte, nonce *[24]byte, peersPublicKey, privateKey *[32]byte) ([]byte, bool) {\n\tvar sharedKey [32]byte\n\tPrecompute(&sharedKey, peersPublicKey, privateKey)\n\treturn secretbox.Open(out, box, nonce, &sharedKey)\n}\n\n\n\nfunc OpenAfterPrecomputation(out, box []byte, nonce *[24]byte, sharedKey *[32]byte) ([]byte, bool) {\n\treturn secretbox.Open(out, box, nonce, sharedKey)\n}\n\nfunc GenerateKey(rand io.Reader) (publicKey, privateKey *[32]byte, err error) ", "output": "{\n\tpublicKey = new([32]byte)\n\tprivateKey = new([32]byte)\n\t_, err = io.ReadFull(rand, privateKey[:])\n\tif err != nil {\n\t\tpublicKey = nil\n\t\tprivateKey = nil\n\t\treturn\n\t}\n\n\tcurve25519.ScalarBaseMult(publicKey, privateKey)\n\treturn\n}"} {"input": "package gwent\n\nconst (\n\tAbilityNone = iota\n)\n\n\ntype CardUnit struct {\n\tUnitType CardType\n\tUnitRange CardRange\n\tUnitFaction CardFaction\n\n\tUnitPower, UnitAbility int\n\tUnitHero bool\n\n\tBasicCard\n}\n\n\nfunc (c *CardUnit) Play(p *Player, target Card) {\n\tc.PutOnTable(p)\n}\n\n\n\n\n\nfunc (c *CardUnit) Type() CardType {\n\treturn c.UnitType\n}\n\n\nfunc (c *CardUnit) Faction() CardFaction {\n\treturn c.UnitFaction\n}\n\n\nfunc (c *CardUnit) Range() CardRange {\n\treturn c.UnitRange\n}\n\n\nfunc (c *CardUnit) Power(p *Player) int {\n\tpwr := c.UnitPower\n\n\tif !c.Hero() && ((c.Range() == RangeClose && p.Game.WeatherClose) ||\n\t\t(c.Range() == RangeRanged && p.Game.WeatherRanged) ||\n\t\t(c.Range() == RangeSiege && p.Game.WeatherSiege)) {\n\t\tpwr = 1\n\t}\n\n\tif (c.Range() == RangeClose && p.HornClose) ||\n\t\t(c.Range() == RangeRanged && p.HornRanged) ||\n\t\t(c.Range() == RangeSiege && p.HornSiege) {\n\t\tpwr *= 2\n\t}\n\n\treturn pwr\n}\n\n\nfunc (c *CardUnit) Hero() bool {\n\treturn c.UnitHero\n}\n\n\nfunc (c *CardUnit) Targettable() bool {\n\treturn false\n}\n\nfunc (c *CardUnit) PutOnTable(p *Player) ", "output": "{\n\tswitch c.Range() {\n\tcase RangeClose:\n\t\tp.RowClose = append(p.RowClose, c)\n\tcase RangeRanged:\n\t\tp.RowRanged = append(p.RowRanged, c)\n\tcase RangeSiege:\n\t\tp.RowSiege = append(p.RowSiege, c)\n\t}\n}"} {"input": "package kafka\n\nimport (\n\t\"encoding/binary\"\n\t\"hash/crc32\"\n)\n\ntype crc32Writer struct {\n\ttable *crc32.Table\n\tbuffer [8]byte\n\tcrc32 uint32\n}\n\nfunc (w *crc32Writer) update(b []byte) {\n\tw.crc32 = crc32.Update(w.crc32, w.table, b)\n}\n\nfunc (w *crc32Writer) writeInt8(i int8) {\n\tw.buffer[0] = byte(i)\n\tw.update(w.buffer[:1])\n}\n\n\n\nfunc (w *crc32Writer) writeInt32(i int32) {\n\tbinary.BigEndian.PutUint32(w.buffer[:4], uint32(i))\n\tw.update(w.buffer[:4])\n}\n\nfunc (w *crc32Writer) writeInt64(i int64) {\n\tbinary.BigEndian.PutUint64(w.buffer[:8], uint64(i))\n\tw.update(w.buffer[:8])\n}\n\nfunc (w *crc32Writer) writeBytes(b []byte) {\n\tn := len(b)\n\tif b == nil {\n\t\tn = -1\n\t}\n\tw.writeInt32(int32(n))\n\tw.update(b)\n}\n\nfunc (w *crc32Writer) Write(b []byte) (int, error) {\n\tw.update(b)\n\treturn len(b), nil\n}\n\nfunc (w *crc32Writer) WriteString(s string) (int, error) {\n\tw.update([]byte(s))\n\treturn len(s), nil\n}\n\nfunc (w *crc32Writer) writeInt16(i int16) ", "output": "{\n\tbinary.BigEndian.PutUint16(w.buffer[:2], uint16(i))\n\tw.update(w.buffer[:2])\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"path\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n)\n\ntype tempNamer struct {\n\tprefix string\n}\n\nvar defTempNamer = tempNamer{\".syncthing\"}\n\nfunc (t tempNamer) IsTemporary(name string) bool {\n\tif runtime.GOOS == \"windows\" {\n\t\tname = filepath.ToSlash(name)\n\t}\n\treturn strings.HasPrefix(path.Base(name), t.prefix)\n}\n\n\n\nfunc (t tempNamer) TempName(name string) string ", "output": "{\n\ttdir := path.Dir(name)\n\ttname := fmt.Sprintf(\"%s.%s\", t.prefix, path.Base(name))\n\treturn path.Join(tdir, tname)\n}"} {"input": "package filesystem\n\ntype FileSystem struct{}\n\nconst name = \"filesystem\"\n\n\n\nfunc (self *FileSystem) Collect() (result interface{}, err error) {\n\tresult, err = getFileSystemInfo()\n\treturn\n}\n\nfunc (self *FileSystem) Name() string ", "output": "{\n\treturn name\n}"} {"input": "package engine\n\nimport (\n\tvtrpcpb \"vitess.io/vitess/go/vt/proto/vtrpc\"\n\t\"vitess.io/vitess/go/vt/vterrors\"\n\n\t\"vitess.io/vitess/go/sqltypes\"\n\t\"vitess.io/vitess/go/vt/proto/query\"\n)\n\nvar _ Primitive = (*UpdateTarget)(nil)\n\n\ntype UpdateTarget struct {\n\tTarget string\n\n\tnoInputs\n\n\tnoTxNeeded\n}\n\nfunc (updTarget *UpdateTarget) description() PrimitiveDescription {\n\treturn PrimitiveDescription{\n\t\tOperatorType: \"UpdateTarget\",\n\t\tOther: map[string]interface{}{\"target\": updTarget.Target},\n\t}\n}\n\n\nfunc (updTarget *UpdateTarget) RouteType() string {\n\treturn \"UpdateTarget\"\n}\n\n\nfunc (updTarget *UpdateTarget) GetKeyspaceName() string {\n\treturn updTarget.Target\n}\n\n\n\n\n\nfunc (updTarget *UpdateTarget) TryExecute(vcursor VCursor, bindVars map[string]*query.BindVariable, wantfields bool) (*sqltypes.Result, error) {\n\terr := vcursor.Session().SetTarget(updTarget.Target)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &sqltypes.Result{}, nil\n}\n\n\nfunc (updTarget *UpdateTarget) TryStreamExecute(vcursor VCursor, bindVars map[string]*query.BindVariable, wantfields bool, callback func(*sqltypes.Result) error) error {\n\tresult, err := updTarget.TryExecute(vcursor, bindVars, wantfields)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn callback(result)\n}\n\n\nfunc (updTarget *UpdateTarget) GetFields(vcursor VCursor, bindVars map[string]*query.BindVariable) (*sqltypes.Result, error) {\n\treturn nil, vterrors.Errorf(vtrpcpb.Code_INTERNAL, \"[BUG] GetFields not reachable for use statement\")\n}\n\nfunc (updTarget *UpdateTarget) GetTableName() string ", "output": "{\n\treturn \"\"\n}"} {"input": "package resctrl\n\nimport (\n\tinfo \"github.com/google/cadvisor/info/v1\"\n\t\"github.com/google/cadvisor/stats\"\n\n\t\"github.com/opencontainers/runc/libcontainer/configs\"\n\t\"github.com/opencontainers/runc/libcontainer/intelrdt\"\n)\n\ntype collector struct {\n\tresctrl intelrdt.Manager\n\tstats.NoopDestroy\n}\n\n\n\nfunc (c *collector) UpdateStats(stats *info.ContainerStats) error {\n\tstats.Resctrl = info.ResctrlStats{}\n\n\tresctrlStats, err := c.resctrl.GetStats()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnumberOfNUMANodes := len(*resctrlStats.MBMStats)\n\n\tstats.Resctrl.MemoryBandwidth = make([]info.MemoryBandwidthStats, 0, numberOfNUMANodes)\n\tstats.Resctrl.Cache = make([]info.CacheStats, 0, numberOfNUMANodes)\n\n\tfor _, numaNodeStats := range *resctrlStats.MBMStats {\n\t\tstats.Resctrl.MemoryBandwidth = append(stats.Resctrl.MemoryBandwidth,\n\t\t\tinfo.MemoryBandwidthStats{\n\t\t\t\tTotalBytes: numaNodeStats.MBMTotalBytes,\n\t\t\t\tLocalBytes: numaNodeStats.MBMLocalBytes,\n\t\t\t})\n\t}\n\n\tfor _, numaNodeStats := range *resctrlStats.CMTStats {\n\t\tstats.Resctrl.Cache = append(stats.Resctrl.Cache,\n\t\t\tinfo.CacheStats{LLCOccupancy: numaNodeStats.LLCOccupancy})\n\t}\n\n\treturn nil\n}\n\nfunc newCollector(id string, resctrlPath string) *collector ", "output": "{\n\tcollector := &collector{\n\t\tresctrl: intelrdt.NewManager(\n\t\t\t&configs.Config{\n\t\t\t\tIntelRdt: &configs.IntelRdt{},\n\t\t\t},\n\t\t\tid,\n\t\t\tresctrlPath,\n\t\t),\n\t}\n\n\treturn collector\n}"} {"input": "package record\n\nimport (\n\t\"crypto\"\n\t\"crypto/rsa\"\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/royvandewater/meshchain/cryptohelpers\"\n\t\"github.com/royvandewater/meshchain/record/encoding\"\n)\n\n\n\n\ntype signedRootRecord struct {\n\tmetadata Metadata\n\tdata []byte\n\tsignature []byte\n}\n\n\n\n\n\n\n\nfunc (record *signedRootRecord) JSON() (string, error) {\n\thash, err := record.Hash()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tmetadata, err := record.metadata.Proto()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tjsonBytes, err := json.Marshal(&encoding.Record{\n\t\tMetadata: metadata,\n\t\tData: record.data,\n\t\tSeal: &encoding.Seal{\n\t\t\tHash: hash,\n\t\t\tSignature: record.signature,\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn \"\", nil\n\t}\n\treturn string(jsonBytes), nil\n}\n\n\nfunc (record *signedRootRecord) validateSignature() error {\n\tpublicKeys, err := cryptohelpers.BuildRSAPublicKeys(record.metadata.PublicKeys)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thashed, err := record.Hash()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to generate Hash: %v\", err.Error())\n\t}\n\n\tfor _, publicKey := range publicKeys {\n\t\tif nil == rsa.VerifyPSS(publicKey, crypto.SHA256, hashed, record.signature, nil) {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"None of the PublicKeys matches the signature\")\n}\n\nfunc (record *signedRootRecord) Hash() ([]byte, error) ", "output": "{\n\tunsignedRootRecord, err := NewUnsignedRootRecord(record.metadata, record.data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn unsignedRootRecord.Hash()\n}"} {"input": "package model\n\nimport \"time\"\n\ntype folder struct {\n\tstateTracker\n\tscan folderscan\n\tmodel *Model\n\tstop chan struct{}\n}\n\nfunc (f *folder) IndexUpdated() {\n}\n\nfunc (f *folder) DelayScan(next time.Duration) {\n\tf.scan.Delay(next)\n}\n\n\nfunc (f *folder) Stop() {\n\tclose(f.stop)\n}\n\nfunc (f *folder) Jobs() ([]string, []string) {\n\treturn nil, nil\n}\n\nfunc (f *folder) BringToFront(string) {}\n\nfunc (f *folder) scanSubdirsIfHealthy(subDirs []string) error {\n\tif err := f.model.CheckFolderHealth(f.folderID); err != nil {\n\t\tl.Infoln(\"Skipping folder\", f.folderID, \"scan due to folder error:\", err)\n\t\treturn err\n\t}\n\tl.Debugln(f, \"Scanning subdirectories\")\n\tif err := f.model.internalScanFolderSubdirs(f.folderID, subDirs); err != nil {\n\t\tf.setError(err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (f *folder) Scan(subdirs []string) error ", "output": "{\n\treturn f.scan.Scan(subdirs)\n}"} {"input": "package matchers\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/cloudfoundry/cli/cf/terminal\"\n\t\"github.com/onsi/gomega\"\n)\n\ntype SliceMatcher struct {\n\texpected [][]string\n\tfailedAtIndex int\n}\n\nfunc ContainSubstrings(substrings ...[]string) gomega.OmegaMatcher {\n\treturn &SliceMatcher{expected: substrings}\n}\n\n\n\nfunc (matcher *SliceMatcher) FailureMessage(actual interface{}) string {\n\tactualStrings, ok := actual.([]string)\n\tif !ok {\n\t\treturn fmt.Sprintf(\"Expected actual to be a slice of strings, but it's actually a %T\", actual)\n\t}\n\n\treturn fmt.Sprintf(\"expected to find \\\"%s\\\" in actual:\\n'%s'\\n\", matcher.expected[matcher.failedAtIndex], strings.Join(actualStrings, \"\\n\"))\n}\n\nfunc (matcher *SliceMatcher) NegatedFailureMessage(actual interface{}) string {\n\tactualStrings, ok := actual.([]string)\n\tif !ok {\n\t\treturn fmt.Sprintf(\"Expected actual to be a slice of strings, but it's actually a %T\", actual)\n\t}\n\treturn fmt.Sprintf(\"expected to not find \\\"%s\\\" in actual:\\n'%s'\\n\", matcher.expected[matcher.failedAtIndex], strings.Join(actualStrings, \"\\n\"))\n}\n\nfunc (matcher *SliceMatcher) Match(actual interface{}) (success bool, err error) ", "output": "{\n\tactualStrings, ok := actual.([]string)\n\tif !ok {\n\t\treturn false, nil\n\t}\n\n\tallStringsMatched := make([]bool, len(matcher.expected))\n\n\tfor index, expectedArray := range matcher.expected {\n\t\tfor _, actualValue := range actualStrings {\n\n\t\t\tallStringsFound := true\n\n\t\t\tfor _, expectedValue := range expectedArray {\n\t\t\t\tallStringsFound = allStringsFound && strings.Contains(terminal.Decolorize(actualValue), expectedValue)\n\t\t\t}\n\n\t\t\tif allStringsFound {\n\t\t\t\tallStringsMatched[index] = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tfor index, value := range allStringsMatched {\n\t\tif !value {\n\t\t\tmatcher.failedAtIndex = index\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\treturn true, nil\n}"} {"input": "package repomodel\n\nimport (\n\t\"github.com/kopia/kopia/repo/content\"\n\t\"github.com/kopia/kopia/repo/manifest\"\n)\n\n\ntype RepositorySession struct {\n\tOpenRepo *OpenRepository\n\n\tWrittenContents ContentSet\n\tWrittenManifests ManifestSet\n}\n\n\nfunc (s *RepositorySession) WriteContent(cid content.ID) {\n\ts.WrittenContents.Add(cid)\n}\n\n\n\n\n\nfunc (s *RepositorySession) Refresh() {\n\ts.OpenRepo.Refresh()\n}\n\n\n\nfunc (s *RepositorySession) Flush(wc *ContentSet, wm *ManifestSet) {\n\ts.OpenRepo.mu.Lock()\n\tdefer s.OpenRepo.mu.Unlock()\n\n\ts.OpenRepo.Contents.Add(wc.ids...)\n\ts.OpenRepo.Manifests.Add(wm.ids...)\n\n\ts.OpenRepo.RepoData.Contents.Add(wc.ids...)\n\ts.OpenRepo.RepoData.Manifests.Add(wm.ids...)\n\n\ts.WrittenContents.RemoveAll(wc.ids...)\n\ts.WrittenManifests.RemoveAll(wm.ids...)\n}\n\nfunc (s *RepositorySession) WriteManifest(mid manifest.ID) ", "output": "{\n\ts.WrittenManifests.Add(mid)\n}"} {"input": "package tag \n\nimport \"sort\"\n\n\n\n\n\ntype Index string\n\n\nfunc (s Index) Elem(x int) string {\n\treturn string(s[x*4 : x*4+4])\n}\n\n\n\n\nfunc (s Index) Index(key []byte) int {\n\tn := len(key)\n\tindex := sort.Search(len(s)/4, func(i int) bool {\n\t\treturn cmp(s[i*4:i*4+n], key) != -1\n\t})\n\ti := index * 4\n\tif cmp(s[i:i+len(key)], key) != 0 {\n\t\treturn -1\n\t}\n\treturn index\n}\n\n\n\nfunc (s Index) Next(key []byte, x int) int {\n\tif x++; x*4 < len(s) && cmp(s[x*4:x*4+len(key)], key) == 0 {\n\t\treturn x\n\t}\n\treturn -1\n}\n\n\nfunc cmp(a Index, b []byte) int {\n\tn := len(a)\n\tif len(b) < n {\n\t\tn = len(b)\n\t}\n\tfor i, c := range b[:n] {\n\t\tswitch {\n\t\tcase a[i] > c:\n\t\t\treturn 1\n\t\tcase a[i] < c:\n\t\t\treturn -1\n\t\t}\n\t}\n\tswitch {\n\tcase len(a) < len(b):\n\t\treturn -1\n\tcase len(a) > len(b):\n\t\treturn 1\n\t}\n\treturn 0\n}\n\n\nfunc Compare(a string, b []byte) int {\n\treturn cmp(Index(a), b)\n}\n\n\n\n\n\nfunc FixCase(form string, b []byte) bool ", "output": "{\n\tif len(form) != len(b) {\n\t\treturn false\n\t}\n\tfor i, c := range b {\n\t\tif form[i] <= 'Z' {\n\t\t\tif c >= 'a' {\n\t\t\t\tc -= 'z' - 'Z'\n\t\t\t}\n\t\t\tif c < 'A' || 'Z' < c {\n\t\t\t\treturn false\n\t\t\t}\n\t\t} else {\n\t\t\tif c <= 'Z' {\n\t\t\t\tc += 'z' - 'Z'\n\t\t\t}\n\t\t\tif c < 'a' || 'z' < c {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tb[i] = c\n\t}\n\treturn true\n}"} {"input": "package openstack\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\n\t\"github.com/go-ini/ini\"\n\t\"github.com/rancher/types/apis/management.cattle.io/v3\"\n)\n\nconst (\n\tOpenstackCloudProviderName = \"openstack\"\n)\n\ntype CloudProvider struct {\n\tConfig *v3.OpenstackCloudProvider\n\tName string\n}\n\nfunc GetInstance() *CloudProvider {\n\treturn &CloudProvider{}\n}\n\n\n\nfunc (p *CloudProvider) GetName() string {\n\treturn p.Name\n}\n\nfunc (p *CloudProvider) GenerateCloudConfigFile() (string, error) {\n\tbuf := new(bytes.Buffer)\n\tcloudConfig, _ := ini.LoadSources(ini.LoadOptions{IgnoreInlineComment: true}, []byte(\"\"))\n\tif err := ini.ReflectFrom(cloudConfig, p.Config); err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to parse Openstack cloud config\")\n\t}\n\tif _, err := cloudConfig.WriteTo(buf); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn buf.String(), nil\n}\n\nfunc (p *CloudProvider) Init(cloudProviderConfig v3.CloudProvider) error ", "output": "{\n\tif cloudProviderConfig.OpenstackCloudProvider == nil {\n\t\treturn fmt.Errorf(\"Openstack Cloud Provider Config is empty\")\n\t}\n\tp.Name = OpenstackCloudProviderName\n\tif cloudProviderConfig.Name != \"\" {\n\t\tp.Name = cloudProviderConfig.Name\n\t}\n\tp.Config = cloudProviderConfig.OpenstackCloudProvider\n\treturn nil\n}"} {"input": "package remotecontext \n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n)\n\n\n\n\n\n\n\n\n\n\n\nfunc createTestTempSubdir(t *testing.T, dir, prefix string) string {\n\tpath, err := os.MkdirTemp(dir, prefix)\n\n\tif err != nil {\n\t\tt.Fatalf(\"Error when creating directory %s with prefix %s: %s\", dir, prefix, err)\n\t}\n\n\treturn path\n}\n\n\n\nfunc createTestTempFile(t *testing.T, dir, filename, contents string, perm os.FileMode) string {\n\tfilePath := filepath.Join(dir, filename)\n\terr := os.WriteFile(filePath, []byte(contents), perm)\n\n\tif err != nil {\n\t\tt.Fatalf(\"Error when creating %s file: %s\", filename, err)\n\t}\n\n\treturn filePath\n}\n\nfunc createTestTempDir(t *testing.T, dir, prefix string) (string, func()) ", "output": "{\n\tpath, err := os.MkdirTemp(dir, prefix)\n\n\tif err != nil {\n\t\tt.Fatalf(\"Error when creating directory %s with prefix %s: %s\", dir, prefix, err)\n\t}\n\n\treturn path, func() {\n\t\terr = os.RemoveAll(path)\n\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Error when removing directory %s: %s\", path, err)\n\t\t}\n\t}\n}"} {"input": "package grok\n\ntype nestingStack struct {\n\ttop *nestingElement\n\tsize int\n}\n\ntype nestingElement struct {\n\topenRune rune\n\tstartIndex int\n\tcommaCounter int\n\tlastSeparatorIndex int\n\tnext *nestingElement\n}\n\n\n\nfunc (ne *nestingElement) expressionStartIndex() int {\n\tstartIndex := ne.startIndex + 1\n\tif ne.lastSeparatorIndex+1 > startIndex {\n\t\treturn ne.lastSeparatorIndex + 1\n\t}\n\treturn startIndex\n}\n\n\n\n\nfunc (s *nestingStack) push(openRune rune, startIndex int) {\n\ts.top = &nestingElement{openRune, startIndex, 0, -1, s.top}\n\ts.size++\n}\n\n\nfunc (s *nestingStack) pop() (openRune rune, startIndex int) {\n\tif s.size > 0 {\n\t\topenRune, startIndex, s.top = s.top.openRune, s.top.startIndex, s.top.next\n\t\ts.size--\n\t\treturn\n\t}\n\treturn ' ', -1\n}\n\nfunc (s *nestingStack) topValue() (rune, int, bool) ", "output": "{\n\tif s.size == 0 {\n\t\treturn ' ', -1, false\n\t}\n\n\treturn s.top.openRune, s.top.startIndex, true\n}"} {"input": "package sol\n\n\ntype Operator interface {\n\tWrap(string) string \n}\n\n\n\n\n\nfunc Avg(col Columnar) ColumnElem {\n\treturn Function(AVG, col)\n}\n\n\nfunc Count(col Columnar) ColumnElem {\n\treturn Function(COUNT, col)\n}\n\n\nfunc Date(col Columnar) ColumnElem {\n\treturn Function(DATE, col)\n}\n\n\n\nfunc DatePart(part string, col Columnar) ColumnElem {\n\treturn col.Column().AddOperator(\n\t\tFuncClause{Name: DATEPART},\n\t).AddOperator(\n\t\tArrayClause{clauses: []Clause{String(part)}, post: true, sep: \", \"},\n\t)\n}\n\n\nfunc Max(col Columnar) ColumnElem {\n\treturn Function(MAX, col)\n}\n\n\nfunc Min(col Columnar) ColumnElem {\n\treturn Function(MIN, col)\n}\n\n\nfunc StdDev(col Columnar) ColumnElem {\n\treturn Function(STDDEV, col)\n}\n\n\nfunc Sum(col Columnar) ColumnElem {\n\treturn Function(SUM, col)\n}\n\n\nfunc Variance(col Columnar) ColumnElem {\n\treturn Function(VARIANCE, col)\n}\n\nfunc Function(name string, col Columnar) ColumnElem ", "output": "{\n\treturn col.Column().AddOperator(FuncClause{Name: name})\n}"} {"input": "package gtk\n\n\n\nimport \"C\"\nimport (\n\t\"unsafe\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (v *FileChooserButton) SetFocusOnClick(grabFocus bool) {\n\tC.gtk_file_chooser_button_set_focus_on_click(v.native(), gbool(grabFocus))\n}\n\n\n\n\nfunc (v *Button) GetFocusOnClick() bool {\n\tc := C.gtk_button_get_focus_on_click(v.native())\n\treturn gobool(c)\n}\n\n\nfunc (v *Button) SetFocusOnClick(focusOnClick bool) {\n\tC.gtk_button_set_focus_on_click(v.native(), gbool(focusOnClick))\n}\n\n\n\n\nfunc (v *TextIter) BeginsTag(v1 *TextTag) bool {\n\treturn gobool(C.gtk_text_iter_begins_tag(v.native(), v1.native()))\n}\n\n\n\n\nfunc (v *Window) ParseGeometry(geometry string) bool {\n\tcstr := C.CString(geometry)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tc := C.gtk_window_parse_geometry(v.native(), (*C.gchar)(cstr))\n\treturn gobool(c)\n}\n\n\nfunc (v *Window) ResizeToGeometry(width, height int) {\n\tC.gtk_window_resize_to_geometry(v.native(), C.gint(width), C.gint(height))\n}\n\n\nfunc (v *Window) SetDefaultGeometry(width, height int) {\n\tC.gtk_window_set_default_geometry(v.native(), C.gint(width),\n\t\tC.gint(height))\n}\n\nfunc (v *FileChooserButton) GetFocusOnClick() bool ", "output": "{\n\treturn gobool(C.gtk_file_chooser_button_get_focus_on_click(v.native()))\n}"} {"input": "package algorithm\n\n\n\nfunc SelectSort(items []int) []int ", "output": "{\n\titems_len := len(items)\n\tfor i := 0; i < items_len-1; i++ {\n\t\tp := i\n\t\tfor j := i + 1; j < items_len; j++ {\n\t\t\tif items[p] > items[j] {\n\t\t\t\tp = j\n\t\t\t}\n\t\t}\n\n\t\tif p != i {\n\t\t\titems[p], items[i] = items[i], items[p]\n\t\t}\n\t}\n\treturn items\n}"} {"input": "package connmgr\n\nimport \"github.com/abcsuite/abclog\"\n\n\n\n\nvar log abclog.Logger\n\n\nfunc init() {\n\tDisableLog()\n}\n\n\n\n\n\n\n\n\nfunc UseLogger(logger abclog.Logger) {\n\tlog = logger\n}\n\nfunc DisableLog() ", "output": "{\n\tlog = abclog.Disabled\n}"} {"input": "package core\n\ntype Context interface {\n\tCid() int\n}\n\ntype context int\n\nvar __cid int = 100\n\n\n\nfunc (v context) Cid() int {\n\treturn int(v)\n}\n\nfunc NewContext() Context ", "output": "{\n\tv := context(__cid)\n\t__cid++\n\treturn v\n}"} {"input": "package utils\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/heketi/heketi/tests\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestNewStatusGroup(t *testing.T) {\n\ts := NewStatusGroup()\n\ttests.Assert(t, s != nil)\n\ttests.Assert(t, s.results != nil)\n\ttests.Assert(t, len(s.results) == 0)\n\ttests.Assert(t, s.err == nil)\n}\n\nfunc TestStatusGroupSuccess(t *testing.T) {\n\n\ts := NewStatusGroup()\n\n\tmax := 100\n\ts.Add(max)\n\n\tfor i := 0; i < max; i++ {\n\t\tgo func(value int) {\n\t\t\tdefer s.Done()\n\t\t\ttime.Sleep(time.Millisecond * 1 * time.Duration(value))\n\t\t}(i)\n\t}\n\n\terr := s.Result()\n\ttests.Assert(t, err == nil)\n\n}\n\n\n\nfunc TestStatusGroupFailure(t *testing.T) ", "output": "{\n\ts := NewStatusGroup()\n\n\tfor i := 0; i < 100; i++ {\n\n\t\ts.Add(1)\n\t\tgo func(value int) {\n\t\t\tdefer s.Done()\n\t\t\ttime.Sleep(time.Millisecond * 1 * time.Duration(value))\n\t\t\tif value%10 == 0 {\n\t\t\t\ts.Err(errors.New(fmt.Sprintf(\"Err: %v\", value)))\n\t\t\t}\n\n\t\t}(i)\n\n\t}\n\n\terr := s.Result()\n\n\ttests.Assert(t, err != nil)\n\ttests.Assert(t, err.Error() == \"Err: 90\", err)\n\n}"} {"input": "package digitalocean\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"strconv\"\n\n\t\"github.com/digitalocean/godo\"\n)\n\ntype Artifact struct {\n\tsnapshotName string\n\n\tsnapshotId int\n\n\tregionName string\n\n\tclient *godo.Client\n}\n\nfunc (*Artifact) BuilderId() string {\n\treturn BuilderId\n}\n\nfunc (*Artifact) Files() []string {\n\treturn nil\n}\n\nfunc (a *Artifact) Id() string {\n\treturn fmt.Sprintf(\"%s:%s\", a.regionName, strconv.FormatUint(uint64(a.snapshotId), 10))\n}\n\nfunc (a *Artifact) String() string {\n\treturn fmt.Sprintf(\"A snapshot was created: '%v' (ID: %v) in region '%v'\", a.snapshotName, a.snapshotId, a.regionName)\n}\n\n\n\nfunc (a *Artifact) Destroy() error {\n\tlog.Printf(\"Destroying image: %d (%s)\", a.snapshotId, a.snapshotName)\n\t_, err := a.client.Images.Delete(context.TODO(), a.snapshotId)\n\treturn err\n}\n\nfunc (a *Artifact) State(name string) interface{} ", "output": "{\n\treturn nil\n}"} {"input": "package gumbleffmpeg \n\nimport (\n\t\"io\"\n\t\"os/exec\"\n)\n\n\ntype Source interface {\n\targuments() []string\n\tstart(*exec.Cmd) error\n\tdone()\n}\n\n\n\ntype sourceFile string\n\n\nfunc SourceFile(filename string) Source {\n\treturn sourceFile(filename)\n}\n\nfunc (s sourceFile) arguments() []string {\n\treturn []string{\"-i\", string(s)}\n}\n\nfunc (sourceFile) start(*exec.Cmd) error {\n\treturn nil\n}\n\nfunc (sourceFile) done() {\n}\n\n\n\ntype sourceReader struct {\n\tr io.ReadCloser\n}\n\n\nfunc SourceReader(r io.ReadCloser) Source {\n\treturn &sourceReader{r}\n}\n\nfunc (*sourceReader) arguments() []string {\n\treturn []string{\"-i\", \"-\"}\n}\n\nfunc (s *sourceReader) start(cmd *exec.Cmd) error {\n\tcmd.Stdin = s.r\n\treturn nil\n}\n\nfunc (s *sourceReader) done() {\n\ts.r.Close()\n}\n\n\n\ntype sourceExec struct {\n\tname string\n\targ []string\n\n\tcmd *exec.Cmd\n}\n\n\n\nfunc SourceExec(name string, arg ...string) Source {\n\treturn &sourceExec{\n\t\tname: name,\n\t\targ: arg,\n\t}\n}\n\nfunc (*sourceExec) arguments() []string {\n\treturn []string{\"-i\", \"-\"}\n}\n\n\n\nfunc (s *sourceExec) done() {\n\tif s.cmd != nil {\n\t\tif p := s.cmd.Process; p != nil {\n\t\t\tp.Kill()\n\t\t}\n\t\ts.cmd.Wait()\n\t}\n}\n\nfunc (s *sourceExec) start(cmd *exec.Cmd) error ", "output": "{\n\ts.cmd = exec.Command(s.name, s.arg...)\n\tr, err := s.cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmd.Stdin = r\n\tif err := s.cmd.Start(); err != nil {\n\t\tcmd.Stdin = nil\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package dnsclient\n\nimport (\n\t\"net\"\n\t\"strings\"\n)\n\n\ntype Records []*Record\n\n\n\n\n\nfunc (r Records) ByType(typ string) (res Records) {\n\tif typ == \"\" {\n\t\treturn r\n\t}\n\ttyp = strings.ToLower(typ)\n\tfor _, record := range r {\n\t\tif strings.ToLower(record.Type) == typ {\n\t\t\tres = append(res, record)\n\t\t}\n\t}\n\treturn res\n}\n\n\nfunc (r Records) ByValue(value string) (res Records) {\n\tif value == \"\" {\n\t\treturn r\n\t}\n\tfor _, record := range r {\n\t\tif record.IP == value {\n\t\t\tres = append(res, record)\n\t\t}\n\t}\n\treturn res\n}\n\n\nfunc (r Records) User() (res Records) {\n\tfor _, record := range r {\n\t\ttyp := strings.ToLower(record.Type)\n\n\t\tif typ != \"soa\" && typ != \"ns\" {\n\t\t\tres = append(res, record)\n\t\t}\n\t}\n\treturn res\n}\n\n\nfunc (r Records) Filter(f *Record) Records {\n\tif f == nil {\n\t\treturn r\n\t}\n\treturn r.ByValue(f.IP).ByType(f.Type).ByName(f.Name)\n}\n\n\n\nfunc ParseRecord(domain, address string) *Record {\n\thost, _, err := net.SplitHostPort(address)\n\tif err == nil {\n\t\taddress = host\n\t}\n\n\tif net.ParseIP(address) != nil {\n\t\treturn &Record{\n\t\t\tName: domain,\n\t\t\tType: \"A\",\n\t\t\tIP: address,\n\t\t\tTTL: 30,\n\t\t}\n\t}\n\n\treturn &Record{\n\t\tName: domain,\n\t\tType: \"CNAME\",\n\t\tIP: address,\n\t\tTTL: 30,\n\t}\n}\n\nfunc (r Records) ByName(name string) (res Records) ", "output": "{\n\tif name == \"\" {\n\t\treturn r\n\t}\n\tname = strings.ToLower(name)\n\tfor _, record := range r {\n\t\tif strings.ToLower(record.Name) == name {\n\t\t\tres = append(res, record)\n\t\t}\n\t}\n\treturn res\n}"} {"input": "package dshelp\n\nimport (\n\tcid \"gx/ipfs/QmPSQnBKM9g7BaUcZCvswUJVscQ1ipjmwxN5PXCjkp9EQ7/go-cid\"\n\t\"gx/ipfs/QmaRb5yNXKonhbkpNxNawoydk4N6es6b4fPj19sjEKsh5D/go-datastore\"\n\t\"gx/ipfs/QmfVj3x4D6Jkq9SEoi5n2NmoUomLwoeiwnYz2KQa15wRw6/base32\"\n)\n\n\nfunc NewKeyFromBinary(rawKey []byte) datastore.Key {\n\tbuf := make([]byte, 1+base32.RawStdEncoding.EncodedLen(len(rawKey)))\n\tbuf[0] = '/'\n\tbase32.RawStdEncoding.Encode(buf[1:], rawKey)\n\treturn datastore.RawKey(string(buf))\n}\n\n\n\n\n\nfunc CidToDsKey(k cid.Cid) datastore.Key {\n\treturn NewKeyFromBinary(k.Bytes())\n}\n\n\nfunc DsKeyToCid(dsKey datastore.Key) (cid.Cid, error) {\n\tkb, err := BinaryFromDsKey(dsKey)\n\tif err != nil {\n\t\treturn cid.Cid{}, err\n\t}\n\treturn cid.Cast(kb)\n}\n\nfunc BinaryFromDsKey(k datastore.Key) ([]byte, error) ", "output": "{\n\treturn base32.RawStdEncoding.DecodeString(k.String()[1:])\n}"} {"input": "package main\n\n\n\nfunc main() {\n\tVarargs(1, 2, 3, 4)\n}\n\nfunc Varargs(i ...int) int ", "output": "{\n\treturn 6\n}"} {"input": "package hugot\n\nimport \"context\"\n\n\n\n\ntype BackgroundHandler interface {\n\tDescriber\n\tStartBackground(ctx context.Context, w ResponseWriter)\n}\n\ntype baseBackgroundHandler struct {\n\tname string\n\tdesc string\n\tbhf BackgroundFunc\n}\n\n\ntype BackgroundFunc func(ctx context.Context, w ResponseWriter)\n\n\n\nfunc NewBackgroundHandler(name, desc string, f BackgroundFunc) BackgroundHandler {\n\treturn &baseBackgroundHandler{\n\t\tname: name,\n\t\tdesc: desc,\n\t\tbhf: f,\n\t}\n}\n\nfunc (bbh *baseBackgroundHandler) Describe() (string, string) {\n\treturn bbh.name, bbh.desc\n}\n\n\n\nfunc (bbh *baseBackgroundHandler) StartBackground(ctx context.Context, w ResponseWriter) ", "output": "{\n\tbbh.bhf(ctx, w)\n}"} {"input": "package cmd\n\n\ntype SetupType int\n\nconst (\n\tFSSetupType SetupType = iota + 1\n\n\tXLSetupType\n\n\tDistXLSetupType\n\n\tGatewaySetupType\n)\n\n\n\nfunc (setupType SetupType) String() string ", "output": "{\n\tswitch setupType {\n\tcase FSSetupType:\n\t\treturn globalMinioModeFS\n\tcase XLSetupType:\n\t\treturn globalMinioModeXL\n\tcase DistXLSetupType:\n\t\treturn globalMinioModeDistXL\n\tcase GatewaySetupType:\n\t\treturn globalMinioModeGatewayPrefix\n\t}\n\n\treturn \"\"\n}"} {"input": "package service\n\nimport (\n\t\"github.com/JacobXie/leanote/app/db\"\n\t\"github.com/JacobXie/leanote/app/info\"\n\t\"gopkg.in/mgo.v2/bson\"\n)\n\n\ntype NoteContentHistoryService struct {\n}\n\n\nvar maxSize = 10\n\n\n\nfunc (this *NoteContentHistoryService) AddHistory(noteId, userId string, eachHistory info.EachHistory) {\n\tif eachHistory.Content == \"\" {\n\t\treturn\n\t}\n\n\thistory := info.NoteContentHistory{}\n\tdb.GetByIdAndUserId(db.NoteContentHistories, noteId, userId, &history)\n\tif history.NoteId == \"\" {\n\t\tthis.newHistory(noteId, userId, eachHistory)\n\t} else {\n\t\tl := len(history.Histories)\n\t\tif l >= maxSize {\n\t\t\thistory.Histories = history.Histories[:maxSize]\n\t\t}\n\t\tnewHistory := []info.EachHistory{eachHistory}\n\t\tnewHistory = append(newHistory, history.Histories...) \n\t\thistory.Histories = newHistory\n\n\t\tdb.UpdateByIdAndUserId(db.NoteContentHistories, noteId, userId, history)\n\t}\n\treturn\n}\n\n\n\n\n\nfunc (this *NoteContentHistoryService) ListHistories(noteId, userId string) []info.EachHistory {\n\thistories := info.NoteContentHistory{}\n\tdb.GetByIdAndUserId(db.NoteContentHistories, noteId, userId, &histories)\n\treturn histories.Histories\n}\n\nfunc (this *NoteContentHistoryService) newHistory(noteId, userId string, eachHistory info.EachHistory) ", "output": "{\n\thistory := info.NoteContentHistory{NoteId: bson.ObjectIdHex(noteId),\n\t\tUserId: bson.ObjectIdHex(userId),\n\t\tHistories: []info.EachHistory{eachHistory},\n\t}\n\n\tdb.Insert(db.NoteContentHistories, history)\n}"} {"input": "package route\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\n\t\"controller\"\n\t\"route/middleware\"\n\t\"route/routewrapper\"\n\t\"shared\"\n\n\t\"github.com/gorilla/context\"\n\t\"github.com/josephspurrier/csrfbanana\"\n)\n\n\nfunc Load() http.Handler {\n\tlog.Println(\"Load all handlers\")\n\treturn middlewareHandler(routewrapper.Instance())\n}\n\n\nfunc LoadHTTPS() http.Handler {\n\tlog.Println(\"Load HTTPS handlers\")\n\treturn middlewareHandler(routewrapper.Instance())\n}\n\n\nfunc LoadHTTP() http.Handler {\n\tlog.Println(\"Load HTTP handlers\")\n\treturn middlewareHandler(routewrapper.Instance())\n}\n\n\n\n\n\nfunc middlewareHandler(h http.Handler) http.Handler {\n\tif shared.EnableCors && shared.Name != \"\" && shared.Store != nil {\n\t\tlog.Fatal(\"Cors and Session conflit\")\n\t} else if shared.Name != \"\" && shared.Store != nil {\n\t\tlog.Println(\"Prevents CSRF, Double Submits\")\n\t\tcs := csrfbanana.New(h, shared.Store, shared.Name)\n\t\tcs.FailureHandler(http.HandlerFunc(controller.InvalidToken))\n\t\tcs.ClearAfterUsage(true)\n\t\tcs.ExcludeRegexPaths([]string{\"/static(.*)\"})\n\t\tcsrfbanana.TokenLength = 32\n\t\tcsrfbanana.TokenName = \"token\"\n\t\tcsrfbanana.SingleToken = false\n\t\th = cs\n\t} else if shared.EnableCors {\n\t\tlog.Println(\"Prevents Cors\")\n\t\th = shared.CorsHandler(h)\n\t}\n\n\tlog.Println(\"Logger request activated\")\n\th = middleware.LogrequestHandler(h)\n\n\tlog.Println(\"Clear handler for Gorilla Context\")\n\th = context.ClearHandler(h)\n\n\treturn h\n}\n\nfunc redirectToHTTPS(w http.ResponseWriter, req *http.Request) ", "output": "{\n\tlog.Println(\"Redirect to https\")\n\thttp.Redirect(w, req, \"https://\"+req.Host, http.StatusMovedPermanently)\n}"} {"input": "package glu\n\nvar _Perspective func(fovy, aspect, near, far float64)\nvar _LookAt func(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ float64)\n\nfunc RegisterPerspective(fn func(fovy, aspect, near, far float64)) {\n\t_Perspective = fn\n}\n\n\n\nfunc Perspective(fovy, aspect, near, far float64) {\n\tif _Perspective == nil {\n\t\tpanic(\"Please register a Perspective with glu.RegisterPespective\")\n\t}\n\n\t_Perspective(fovy, aspect, near, far)\n}\n\nfunc LookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ float64) {\n\tif _LookAt == nil {\n\t\tpanic(\"Please register a LookAt with glu.RegisterLookAt\")\n\t}\n\n\t_LookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ)\n}\n\nfunc RegisterLookAt(fn func(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ float64)) ", "output": "{\n\t_LookAt = fn\n}"} {"input": "package slack\n\nimport (\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/ejholmes/slash\"\n)\n\n\n\n\n\nfunc replyHandler(text string) slash.Handler ", "output": "{\n\treturn slash.HandlerFunc(func(ctx context.Context, r slash.Responder, c slash.Command) (slash.Response, error) {\n\t\treturn slash.Reply(text), nil\n\t})\n}"} {"input": "package openid\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha1\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"hash\"\n\t\"log\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\thmacSHA1 = \"HMAC-SHA1\"\n\thmacSHA256 = \"HMAC-SHA256\"\n)\n\n\ntype Association struct {\n\tEndpoint string\n\tHandle string\n\tSecret []byte\n\tType string\n\tExpires time.Time\n}\n\n\n\n\ntype associations struct {\n\tsync.Map\n}\n\n\nfunc (as *associations) get(endpoint string) (*Association, bool) {\n\tendpoint = strings.TrimRight(endpoint, \"/\")\n\tvalue, ok := as.Load(endpoint)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\n\tassoc := value.(*Association)\n\tif assoc.Expires.After(time.Now()) {\n\t\treturn assoc, ok\n\t}\n\n\tfrom, to := as.gc()\n\tlog.Printf(\"associates GC from %d to %d\", from, to)\n\n\treturn nil, false\n}\n\n\nfunc (as *associations) set(endpoint string, a *Association) {\n\tas.Store(strings.TrimRight(endpoint, \"/\"), a)\n}\n\n\nfunc (as *associations) gc() (int, int) {\n\tfrom, purged := 0, 0\n\n\tas.Map.Range(func(k, v interface{}) bool {\n\t\ta := v.(*Association)\n\t\tif a.Expires.Before(time.Now()) {\n\t\t\tpurged++\n\t\t\tas.Map.Delete(k)\n\t\t}\n\t\tfrom++\n\t\treturn true\n\t})\n\n\treturn from, from - purged\n}\n\nfunc (a *Association) sign(\n\tparams map[string]string, signed []string) (string, error) ", "output": "{\n\n\tvar h hash.Hash\n\n\tswitch a.Type {\n\tcase hmacSHA1:\n\t\th = hmac.New(sha1.New, a.Secret)\n\tcase hmacSHA256:\n\t\th = hmac.New(sha256.New, a.Secret)\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"unsupported association type %q\", a.Type)\n\t}\n\n\tfor _, k := range signed {\n\t\twriteKeyValuePair(h, k, params[k])\n\t}\n\n\treturn base64.StdEncoding.EncodeToString(h.Sum(nil)), nil\n}"} {"input": "package diff\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"os/exec\"\n\t\"runtime\"\n)\n\n\n\n\nfunc writeTempFile(prefix string, data []byte) (string, error) {\n\tfile, err := ioutil.TempFile(\"\", prefix)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t_, err = file.Write(data)\n\tif err1 := file.Close(); err == nil {\n\t\terr = err1\n\t}\n\tif err != nil {\n\t\tos.Remove(file.Name())\n\t\treturn \"\", err\n\t}\n\treturn file.Name(), nil\n}\n\nfunc Diff(prefix string, b1, b2 []byte) ([]byte, error) ", "output": "{\n\tf1, err := writeTempFile(prefix, b1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer os.Remove(f1)\n\n\tf2, err := writeTempFile(prefix, b2)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer os.Remove(f2)\n\n\tcmd := \"diff\"\n\tif runtime.GOOS == \"plan9\" {\n\t\tcmd = \"/bin/ape/diff\"\n\t}\n\n\tdata, err := exec.Command(cmd, \"-u\", f1, f2).CombinedOutput()\n\tif len(data) > 0 {\n\t\terr = nil\n\t}\n\treturn data, err\n}"} {"input": "package bolthold\n\nimport (\n\t\"reflect\"\n\n\t\"github.com/boltdb/bolt\"\n)\n\n\n\nfunc (s *Store) Delete(key, dataType interface{}) error {\n\treturn s.Bolt().Update(func(tx *bolt.Tx) error {\n\t\treturn s.TxDelete(tx, key, dataType)\n\t})\n}\n\n\nfunc (s *Store) TxDelete(tx *bolt.Tx, key, dataType interface{}) error {\n\tif !tx.Writable() {\n\t\treturn bolt.ErrTxNotWritable\n\t}\n\n\tstorer := newStorer(dataType)\n\tgk, err := encode(key)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tb := tx.Bucket([]byte(storer.Type()))\n\tif b == nil {\n\t\treturn ErrNotFound\n\t}\n\n\tvalue := reflect.New(reflect.TypeOf(dataType)).Interface()\n\n\tbVal := b.Get(gk)\n\n\terr = decode(bVal, value)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = b.Delete(gk)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = indexDelete(storer, tx, gk, value)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc (s *Store) DeleteMatching(dataType interface{}, query *Query) error {\n\treturn s.Bolt().Update(func(tx *bolt.Tx) error {\n\t\treturn s.TxDeleteMatching(tx, dataType, query)\n\t})\n}\n\n\n\n\nfunc (s *Store) TxDeleteMatching(tx *bolt.Tx, dataType interface{}, query *Query) error ", "output": "{\n\treturn deleteQuery(tx, dataType, query)\n}"} {"input": "package esicache\n\nimport (\n\t\"context\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/corestoreio/errors\"\n)\n\n\n\n\ntype Cacher interface {\n\tSet(key string, value []byte, expiration time.Duration) error\n\tGet(key string) ([]byte, error)\n}\n\n\n\n\n\n\ntype Caches []Cacher\n\n\nfunc (c Caches) Set(key string, value []byte, expiration time.Duration) error {\n\treturn nil\n}\n\n\nfunc (c Caches) Get(key string) ([]byte, error) {\n\treturn nil, nil\n}\n\n\nvar MainRegistry = ®istry{\n\tcaches: make(map[string]Caches),\n}\n\ntype registry struct {\n\tmu sync.RWMutex\n\tcaches map[string]Caches\n}\n\nfunc (r *registry) Get(ctx context.Context, scope, alias, key string) error {\n\treturn errors.New(\"TODO IMPLEMENT\")\n}\n\n\n\n\nfunc (r *registry) Register(scope, url string) error {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\n\tc, err := NewCacher(url)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"[esikv] NewCacher URL %q\", url)\n\t}\n\n\tif _, ok := r.caches[scope]; !ok {\n\t\tr.caches[scope] = make(Caches, 0, 2)\n\t}\n\tr.caches[scope] = append(r.caches[scope], c)\n\n\treturn nil\n}\n\n\nfunc (r *registry) Len(scope string) int {\n\tr.mu.RLock()\n\tdefer r.mu.RUnlock()\n\treturn len(r.caches[scope])\n}\n\n\nfunc (r *registry) Clear() {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\tr.caches = make(map[string]Caches)\n}\n\nfunc NewCacher(url string) (Cacher, error) ", "output": "{\n\n\treturn nil, nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/grandcat/zeroconf\"\n)\n\nvar (\n\tzeroConfName = \"Omxremote\"\n\tzeroconfService = \"_omxremote._tcp\"\n\tzeroconfDomain = \"local.\"\n\tzeroconfPort = 8080\n)\n\n\n\nfunc startZeroConfAdvertisement(stop chan bool) ", "output": "{\n\thostname, err := os.Hostname()\n\tif err == nil && hostname != \"\" {\n\t\tzeroConfName = fmt.Sprintf(\"%s (%s)\", zeroConfName, strings.Split(hostname, \".\")[0])\n\t}\n\n\tlog.Println(\"Starting zeroconf:\", zeroConfName, zeroconfService, zeroconfPort)\n\tdefer log.Println(\"Zeroconf service terminated\")\n\n\tserver, err := zeroconf.Register(\n\t\tzeroConfName,\n\t\tzeroconfService,\n\t\tzeroconfDomain,\n\t\tzeroconfPort,\n\t\t[]string{\"version=\" + VERSION},\n\t\tnil,\n\t)\n\tif err != nil {\n\t\tlog.Println(\"Zeroconf server error:\", err)\n\t\treturn\n\t}\n\tdefer server.Shutdown()\n\n\t<-stop\n}"} {"input": "package http\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/Cepave/open-falcon-backend/modules/transfer/g\"\n\tlog \"github.com/sirupsen/logrus\"\n\t\"net/http\"\n\t_ \"net/http/pprof\"\n)\n\ntype Dto struct {\n\tMsg string `json:\"msg\"`\n\tData interface{} `json:\"data\"`\n}\n\n\nfunc startHttpServer() {\n\tif !g.Config().Http.Enabled {\n\t\treturn\n\t}\n\n\taddr := g.Config().Http.Listen\n\tif addr == \"\" {\n\t\treturn\n\t}\n\n\tconfigCommonRoutes()\n\tconfigProcHttpRoutes()\n\tconfigDebugHttpRoutes()\n\tconfigApiHttpRoutes()\n\n\ts := &http.Server{\n\t\tAddr: addr,\n\t\tMaxHeaderBytes: 1 << 30,\n\t}\n\n\tlog.Println(\"http.startHttpServer ok, listening\", addr)\n\tlog.Fatalln(s.ListenAndServe())\n}\n\nfunc RenderJson(w http.ResponseWriter, v interface{}) {\n\tbs, err := json.Marshal(v)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.Write(bs)\n}\n\nfunc RenderDataJson(w http.ResponseWriter, data interface{}) {\n\tRenderJson(w, Dto{Msg: \"success\", Data: data})\n}\n\nfunc RenderMsgJson(w http.ResponseWriter, msg string) {\n\tRenderJson(w, map[string]string{\"msg\": msg})\n}\n\nfunc AutoRender(w http.ResponseWriter, data interface{}, err error) {\n\tif err != nil {\n\t\tRenderMsgJson(w, err.Error())\n\t\treturn\n\t}\n\tRenderDataJson(w, data)\n}\n\nfunc Start() ", "output": "{\n\tgo startHttpServer()\n}"} {"input": "package decorators\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\ntype jiraIssueConfig struct {\n\tCREDENTIALS struct {\n\t\tUSERNAME string\n\t\tPASSWORD string\n\t}\n\tENDPOINT struct {\n\t\tURL string\n\t}\n\tKEYS map[string]struct {\n\t\tDESTKEY string\n\t\tFIELD string\n\t}\n}\n\n\ntype jiraIssue struct {\n\tclient http.Client\n\tconfig jiraIssueConfig\n}\n\nfunc (j jiraIssue) Decorate(commitMap *map[string]interface{}) (*map[string]interface{}, error) {\n\tvar ID string\n\n\tswitch v := (*commitMap)[\"jiraIssueId\"].(type) {\n\tcase string:\n\t\tID = v\n\tcase int64:\n\t\tID = fmt.Sprintf(\"%d\", v)\n\tdefault:\n\t\treturn commitMap, nil\n\t}\n\n\tif ID == \"\" {\n\t\treturn commitMap, nil\n\t}\n\n\treq, err := http.NewRequest(\"GET\", fmt.Sprintf(\"%s/rest/api/2/issue/%s\", j.config.ENDPOINT.URL, ID), nil)\n\n\tif err != nil {\n\t\treturn commitMap, err\n\t}\n\n\treq.SetBasicAuth(j.config.CREDENTIALS.USERNAME, j.config.CREDENTIALS.PASSWORD)\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\treturn jSONResponse{&j.client, req, j.config.KEYS}.Decorate(commitMap)\n}\n\n\n\nfunc newJiraIssue(config jiraIssueConfig) Decorater ", "output": "{\n\treturn jiraIssue{http.Client{}, config}\n}"} {"input": "package sdk\n\nimport (\n\t\"io/ioutil\"\n\t\"net/url\"\n\n\t\"gopkg.in/yaml.v2\"\n)\n\ntype hydraConfig struct {\n\tClusterURL string `yaml:\"cluster_url\"`\n\tClientID string `yaml:\"client_id\"`\n\tClientSecret string `yaml:\"client_secret\"`\n}\n\n\nfunc FromYAML(file string) option {\n\treturn func(c *Client) error {\n\t\tvar err error\n\t\tvar config = hydraConfig{}\n\n\t\tdata, err := ioutil.ReadFile(file)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = yaml.Unmarshal(data, &config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.clusterURL, err = url.Parse(config.ClusterURL)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.clientID = config.ClientID\n\t\tc.clientSecret = config.ClientSecret\n\n\t\treturn nil\n\t}\n}\n\n\n\n\n\n\nfunc ClusterURL(urlStr string) option {\n\treturn func(c *Client) error {\n\t\tvar err error\n\t\tc.clusterURL, err = url.Parse(urlStr)\n\t\treturn err\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc ClientSecret(secret string) option {\n\treturn func(c *Client) error {\n\t\tc.clientSecret = secret\n\t\treturn nil\n\t}\n}\n\n\n\n\n\n\nfunc SkipTLSVerify() option {\n\treturn func(c *Client) error {\n\t\tc.skipTLSVerify = true\n\t\treturn nil\n\t}\n}\n\n\n\n\n\n\nfunc Scopes(scopes ...string) option {\n\treturn func(c *Client) error {\n\t\tc.scopes = scopes\n\t\treturn nil\n\t}\n}\n\nfunc ClientID(id string) option ", "output": "{\n\treturn func(c *Client) error {\n\t\tc.clientID = id\n\t\treturn nil\n\t}\n}"} {"input": "package msg\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com/KunTengRom/xfrps/utils/errors\"\n)\n\nfunc unpack(typeByte byte, buffer []byte, msgIn Message) (msg Message, err error) {\n\tif msgIn == nil {\n\t\tt, ok := TypeMap[typeByte]\n\t\tif !ok {\n\t\t\terr = fmt.Errorf(\"Unsupported message type %b\", typeByte)\n\t\t\treturn\n\t\t}\n\n\t\tmsg = reflect.New(t).Interface().(Message)\n\t} else {\n\t\tmsg = msgIn\n\t}\n\n\terr = json.Unmarshal(buffer, &msg)\n\treturn\n}\n\n\n\nfunc UnPack(typeByte byte, buffer []byte) (msg Message, err error) {\n\treturn unpack(typeByte, buffer, nil)\n}\n\nfunc Pack(msg Message) ([]byte, error) {\n\ttypeByte, ok := TypeStringMap[reflect.TypeOf(msg).Elem()]\n\tif !ok {\n\t\treturn nil, errors.ErrMsgType\n\t}\n\n\tcontent, err := json.Marshal(msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbuffer := bytes.NewBuffer(nil)\n\tbuffer.WriteByte(typeByte)\n\tbinary.Write(buffer, binary.BigEndian, int32(len(content)))\n\tbuffer.Write(content)\n\treturn buffer.Bytes(), nil\n}\n\nfunc UnPackInto(buffer []byte, msg Message) (err error) ", "output": "{\n\t_, err = unpack(' ', buffer, msg)\n\treturn\n}"} {"input": "package main\n\ntype Session struct {\n\tseq int32\n\tservers map[int32]int32 \n}\n\n\n\n\nfunc (s *Session) nextSeq() int32 {\n\ts.seq++\n\treturn s.seq\n}\n\n\nfunc (s *Session) Put(server int32) (seq int32) {\n\tseq = s.nextSeq()\n\ts.servers[seq] = server\n\treturn\n}\n\nfunc (s *Session) Servers() (seqs []int32, servers []int32) {\n\tvar (\n\t\ti = len(s.servers)\n\t\tseq, server int32\n\t)\n\tseqs = make([]int32, i)\n\tservers = make([]int32, i)\n\tfor seq, server = range s.servers {\n\t\ti--\n\t\tseqs[i] = seq\n\t\tservers[i] = server\n\t}\n\treturn\n}\n\n\nfunc (s *Session) Del(seq int32) bool {\n\tdelete(s.servers, seq)\n\treturn (len(s.servers) == 0)\n}\n\nfunc (s *Session) Size() int {\n\treturn len(s.servers)\n}\n\nfunc NewSession(server int) *Session ", "output": "{\n\ts := new(Session)\n\ts.servers = make(map[int32]int32, server)\n\ts.seq = 0\n\treturn s\n}"} {"input": "package events\n\nimport (\n\t\"io\"\n\t\"time\"\n\n\t\"github.com/gravitational/teleport/lib/session\"\n)\n\n\n\ntype DiscardAuditLog struct {\n}\n\n\n\nfunc (d *DiscardAuditLog) EmitAuditEvent(eventType string, fields EventFields) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) PostSessionChunk(namespace string, sid session.ID, reader io.Reader) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) PostSessionSlice(SessionSlice) error {\n\treturn nil\n}\nfunc (d *DiscardAuditLog) GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\nfunc (d *DiscardAuditLog) GetSessionEvents(namespace string, sid session.ID, after int) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\nfunc (d *DiscardAuditLog) SearchEvents(fromUTC, toUTC time.Time, query string) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\nfunc (d *DiscardAuditLog) SearchSessionEvents(fromUTC time.Time, toUTC time.Time) ([]EventFields, error) {\n\treturn make([]EventFields, 0), nil\n}\n\n\n\n\ntype discardSessionLogger struct {\n}\n\nfunc (d *discardSessionLogger) LogEvent(fields EventFields) {\n\treturn\n}\n\nfunc (d *discardSessionLogger) Close() error {\n\treturn nil\n}\n\nfunc (d *discardSessionLogger) Finalize() error {\n\treturn nil\n}\n\nfunc (d *discardSessionLogger) WriteChunk(chunk *SessionChunk) (written int, err error) {\n\treturn 0, nil\n}\n\nfunc (d *DiscardAuditLog) Close() error ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"sync\"\n\n\t\"github.com/jacobsa/util/password\"\n)\n\nvar gPassword string\nvar gPasswordOnce sync.Once\n\n\nconst passwordEnvVar = \"COMEBACK_PASSWORD\"\n\n\n\nfunc getPassword() string {\n\tgPasswordOnce.Do(initPassword)\n\treturn gPassword\n}\n\nfunc initPassword() ", "output": "{\n\tvar ok bool\n\tif gPassword, ok = os.LookupEnv(passwordEnvVar); ok {\n\t\treturn\n\t}\n\n\tgPassword = password.ReadPassword(\"Enter crypto password: \")\n\tif len(gPassword) == 0 {\n\t\tlog.Fatalln(\"You must enter a password.\")\n\t}\n}"} {"input": "package client\n\nimport (\n\t\"net\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n)\n\n\n\nfunc TcpClient(server string) ", "output": "{\n\tconn,err := net.Dial(\"tcp\", server)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdefer conn.Close()\n\n\t_,err = conn.Write([]byte(\"HEAD / HTTP/1.0\\r\\n\\r\\n\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tresp,err:=ioutil.ReadAll(conn)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(string(resp))\n}"} {"input": "package goZKP\n\nimport (\n\t\"errors\"\n\t\"math/big\"\n)\n\n\ntype ZZ struct {\n\tg *big.Int\n\tmodulo *big.Int\n}\n\nfunc (z *ZZ) Bytes() []byte {\n\treturn z.g.Bytes()\n}\n\nfunc (z *ZZ) Mul(x *ZZ) (*ZZ, error) {\n\tif x.modulo.Cmp(z.modulo) != 0 {\n\t\treturn nil, errors.New(\"Unmatched modulo in ZZ multiplication.\")\n\t}\n\tz.g.Mul(z.g, x.g)\n\tz.g.Mod(z.g, z.modulo)\n\treturn z, nil\n}\n\n\n\nfunc (z *ZZ) Inverse() *ZZ {\n\tz.g.ModInverse(z.g, z.modulo)\n\treturn z\n}\n\nfunc (z *ZZ) Exp(x *big.Int) *ZZ ", "output": "{\n\tz.g.Exp(z.g, x, z.modulo)\n\treturn z\n}"} {"input": "package clang\n\n\n\nimport \"C\"\nimport (\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype IdxCXXClassDeclInfo struct {\n\tc C.CXIdxCXXClassDeclInfo\n}\n\nfunc (icxxcdi IdxCXXClassDeclInfo) DeclInfo() *IdxDeclInfo {\n\to := icxxcdi.c.declInfo\n\n\tvar gop_o *IdxDeclInfo\n\tif o != nil {\n\t\tgop_o = &IdxDeclInfo{o}\n\t}\n\n\treturn gop_o\n}\n\n\n\nfunc (icxxcdi IdxCXXClassDeclInfo) NumBases() uint32 {\n\treturn uint32(icxxcdi.c.numBases)\n}\n\nfunc (icxxcdi IdxCXXClassDeclInfo) Bases() []*IdxBaseClassInfo ", "output": "{\n\tvar s []*IdxBaseClassInfo\n\tgos_s := (*reflect.SliceHeader)(unsafe.Pointer(&s))\n\tgos_s.Cap = int(icxxcdi.c.numBases)\n\tgos_s.Len = int(icxxcdi.c.numBases)\n\tgos_s.Data = uintptr(unsafe.Pointer(icxxcdi.c.bases))\n\n\treturn s\n}"} {"input": "package automation\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Version() string {\n\treturn \"v10.0.2-beta\"\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn \"Azure-SDK-For-Go/v10.0.2-beta arm-automation/\"\n}"} {"input": "package fasthttpradix\n\n\nimport (\n\t\"github.com/valyala/fasthttp\"\n\trr \"github.com/byte-mug/golibs/radixroute\"\n\t\"strings\"\n)\n\n\nfunc NormPath(str string) string {\n\treturn \"/\"+strings.Trim(str,\"/\")+\"/\"\n}\n\nfunc InvalidPath(ctx *fasthttp.RequestCtx) {\n\tctx.SetBody([]byte(\"404 Not Found\\n\"))\n\tctx.SetStatusCode(fasthttp.StatusNotFound)\n}\n\ntype handling struct{\n\thandle fasthttp.RequestHandler\n}\ntype Router struct{\n\troutes map[string]*rr.Tree\n}\nfunc (r *Router) getOrCreate(m string) *rr.Tree {\n\tt := r.routes[m]\n\tif t!=nil { return t }\n\tif r.routes==nil { r.routes = make(map[string]*rr.Tree) }\n\tr.routes[m] = rr.New()\n\treturn r.routes[m]\n}\n\nfunc (r *Router) RequestHandler(ctx *fasthttp.RequestCtx) {\n\tt := r.routes[string(ctx.Method())]\n\tif t==nil {\n\t\tInvalidPath(ctx)\n\t\treturn\n\t}\n\ti,_ := t.Get(ctx.Path(),ctx.SetUserValue)\n\th,ok := i.(*handling)\n\tif !ok {\n\t\tInvalidPath(ctx)\n\t\treturn\n\t}\n\th.handle(ctx)\n}\n\nfunc (r *Router) Handle(method string,path string,handler fasthttp.RequestHandler) ", "output": "{\n\tif handler==nil { panic(\"handler must not be nil\") }\n\th := &handling{handler}\n\tcpath := []byte(NormPath(path))\n\tbpath := cpath[:len(cpath)-1]\n\tif method==\"\" {\n\t\tmethod = \"DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT\"\n\t}\n\tfor _,m := range strings.Split(method,\",\") {\n\t\trrt := r.getOrCreate(m)\n\t\trrt.InsertRoute(bpath,h)\n\t\trrt.InsertRoute(cpath,h)\n\t}\n}"} {"input": "package common\n\nimport \"math/big\"\n\ntype _N_ [_S_]byte\n\nfunc BytesTo_N_(b []byte) _N_ {\n\tvar h _N_\n\th.SetBytes(b)\n\treturn h\n}\n\nfunc BigTo_N_(b *big.Int) _N_ { return BytesTo_N_(b.Bytes()) }\nfunc HexTo_N_(s string) _N_ { return BytesTo_N_(FromHex(s)) }\n\n\n\n\nfunc (h _N_) Str() string { return string(h[:]) }\nfunc (h _N_) Bytes() []byte { return h[:] }\nfunc (h _N_) Big() *big.Int { return Bytes2Big(h[:]) }\nfunc (h _N_) Hex() string { return \"0x\" + Bytes2Hex(h[:]) }\n\n\nfunc (h *_N_) SetBytes(b []byte) {\n\tif len(b) > len(h) {\n\t\tb = b[len(b)-_S_:]\n\t}\n\n\tfor i := len(b) - 1; i >= 0; i-- {\n\t\th[_S_-len(b)+i] = b[i]\n\t}\n}\n\n\nfunc (h *_N_) SetString(s string) { h.SetBytes([]byte(s)) }\n\n\nfunc (h *_N_) Set(other _N_) {\n\tfor i, v := range other {\n\t\th[i] = v\n\t}\n}\n\nfunc StringTo_N_(s string) _N_ ", "output": "{ return BytesTo_N_([]byte(s)) }"} {"input": "package store\n\nimport (\n \"encoding/json\"\n)\n\nconst (\n ILocalNodeFile = \"lo\" + NodeSepFile + \":\"\n ILocalNodeDir = \"lo\" + NodeSepDir + \":\"\n)\n\nfunc (this *Store) LocalNodeSet(pl *NodeProposal) uint16 {\n\n \n in := nodePathFilter(pl.Key)\n p := split(in, \"/\")\n l := len(p)\n if pl.Val == NodeDelFlag {\n this.Del(ILocalNodeFile + in)\n this.Srem(ILocalNodeDir+join(p[0:l-1], \"/\"), NodeSepFile+p[l-1])\n return 0\n }\n\n if pl.Ttl < 1 {\n pl.Ttl = 86400\n } else if pl.Ttl > 86400*30 {\n pl.Ttl = 86400 * 30\n }\n\n this.Setex(ILocalNodeFile+in, pl.Ttl, pl.Val)\n\n \n for i := l - 1; i >= 0; i-- {\n in = join(p[0:i], \"/\")\n if i == len(p)-1 {\n this.Sadd(ILocalNodeDir+in, NodeSepFile+p[i])\n } else {\n this.Sadd(ILocalNodeDir+in, NodeSepDir+p[i])\n }\n }\n\n return 0\n}\n\nfunc (this *Store) LocalNodeGet(path string) (*Node, error) {\n\n in := nodePathFilter(path)\n\n v, e := this.Get(ILocalNodeFile + in)\n if e != nil {\n return nil, e\n }\n\n node := new(Node)\n node.C = v\n\n return node, nil\n}\n\n\n\nfunc (this *Store) LocalNodeList(path string) (string, error) ", "output": "{\n\n in := nodePathFilter(path)\n\n item, e := this.Smembers(ILocalNodeDir + in)\n if e != nil {\n return \"\", e\n }\n\n list := []Node{}\n for _, v := range item {\n\n n := Node{}\n switch v[0:1] {\n case NodeSepDir:\n n.T = NodeTypeDir\n case NodeSepFile:\n n.T = NodeTypeFile\n }\n n.P = v[1:]\n list = append(list, n)\n }\n\n if rs, e := json.Marshal(list); e == nil {\n return string(rs), nil\n }\n\n return \"\", nil\n}"} {"input": "package api\n\nimport \"testing\"\n\nfunc assertQueryMeta(t *testing.T, qm *QueryMeta) {\n\tif qm.LastIndex == 0 {\n\t\tt.Fatalf(\"bad index: %d\", qm.LastIndex)\n\t}\n\tif !qm.KnownLeader {\n\t\tt.Fatalf(\"expected known leader, got none\")\n\t}\n}\n\n\n\nfunc testJob() *Job {\n\ttask := NewTask(\"task1\", \"exec\").\n\t\tSetConfig(\"command\", \"/bin/sleep\").\n\t\tRequire(&Resources{\n\t\t\tCPU: 100,\n\t\t\tMemoryMB: 256,\n\t\t\tIOPS: 10,\n\t\t}).\n\t\tSetLogConfig(&LogConfig{\n\t\t\tMaxFiles: 1,\n\t\t\tMaxFileSizeMB: 2,\n\t\t})\n\n\tgroup := NewTaskGroup(\"group1\", 1).\n\t\tAddTask(task).\n\t\tRequireDisk(&EphemeralDisk{\n\t\t\tSizeMB: 25,\n\t\t})\n\n\tjob := NewBatchJob(\"job1\", \"redis\", \"region1\", 1).\n\t\tAddDatacenter(\"dc1\").\n\t\tAddTaskGroup(group)\n\n\treturn job\n}\n\nfunc testPeriodicJob() *Job {\n\tjob := testJob().AddPeriodicConfig(&PeriodicConfig{\n\t\tEnabled: true,\n\t\tSpec: \"*/30 * * * *\",\n\t\tSpecType: \"cron\",\n\t})\n\treturn job\n}\n\nfunc assertWriteMeta(t *testing.T, wm *WriteMeta) ", "output": "{\n\tif wm.LastIndex == 0 {\n\t\tt.Fatalf(\"bad index: %d\", wm.LastIndex)\n\t}\n}"} {"input": "package dchan\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype SimpleReq struct {\n\tHeader Header\n\tBody io.ReadCloser\n}\n\ntype Header []header\n\nfunc (h Header) get(k string) int {\n\tfor idx := range h {\n\t\tif strings.EqualFold(h[idx].Name, k) {\n\t\t\treturn idx\n\t\t}\n\t}\n\treturn -1\n}\n\nfunc (h Header) Get(k string) string {\n\tidx := h.get(k)\n\tif idx < 0 {\n\t\treturn \"\"\n\t}\n\treturn h[idx].Values[0]\n}\n\nfunc (h *Header) Add(k string, v string) {\n\tidx := h.get(k)\n\tif idx < 0 {\n\t\t*h = append(*h, header{k, []string{v}})\n\t} else {\n\t\t(*h)[idx].Values = append((*h)[idx].Values, v)\n\t}\n}\n\ntype header struct {\n\tName string\n\tValues []string\n}\n\n\n\nfunc NewSimpleReq(r *bufio.Reader) (*SimpleReq, error) ", "output": "{\n\tsr := &SimpleReq{\n\t\tHeader: make(Header, 0, 16),\n\t}\n\n\tfor {\n\t\tline, err := r.ReadSlice('\\n')\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(line) == 2 {\n\t\t\tbreak\n\t\t}\n\n\t\tif idx := bytes.Index(line, []byte(\":\")); idx > 0 {\n\t\t\tsr.Header.Add(string(line[:idx]), string(bytes.TrimSpace(line[idx+1:])))\n\t\t}\n\t}\n\n\tcl := sr.Header.Get(\"Content-Length\")\n\tif n, _ := strconv.Atoi(cl); n > 0 {\n\t\tsr.Body = ioutil.NopCloser(io.LimitReader(r, int64(n)))\n\t} else {\n\t\tsr.Body = ioutil.NopCloser(r)\n\t}\n\treturn sr, nil\n}"} {"input": "package jujuc\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"launchpad.net/gnuflag\"\n\n\t\"github.com/juju/core/cmd\"\n)\n\n\ntype UnitGetCommand struct {\n\tcmd.CommandBase\n\tctx Context\n\tKey string\n\tout cmd.Output\n}\n\nfunc NewUnitGetCommand(ctx Context) cmd.Command {\n\treturn &UnitGetCommand{ctx: ctx}\n}\n\nfunc (c *UnitGetCommand) Info() *cmd.Info {\n\treturn &cmd.Info{\n\t\tName: \"unit-get\",\n\t\tArgs: \"\",\n\t\tPurpose: \"print public-address or private-address\",\n\t}\n}\n\nfunc (c *UnitGetCommand) SetFlags(f *gnuflag.FlagSet) {\n\tc.out.AddFlags(f, \"smart\", cmd.DefaultFormatters)\n}\n\n\n\nfunc (c *UnitGetCommand) Run(ctx *cmd.Context) error {\n\tvalue, ok := \"\", false\n\tif c.Key == \"private-address\" {\n\t\tvalue, ok = c.ctx.PrivateAddress()\n\t} else {\n\t\tvalue, ok = c.ctx.PublicAddress()\n\t}\n\tif !ok {\n\t\treturn fmt.Errorf(\"%s not set\", c.Key)\n\t}\n\treturn c.out.Write(ctx, value)\n}\n\nfunc (c *UnitGetCommand) Init(args []string) error ", "output": "{\n\tif args == nil {\n\t\treturn errors.New(\"no setting specified\")\n\t}\n\tif args[0] != \"private-address\" && args[0] != \"public-address\" {\n\t\treturn fmt.Errorf(\"unknown setting %q\", args[0])\n\t}\n\tc.Key = args[0]\n\treturn cmd.CheckEmpty(args[1:])\n}"} {"input": "package testing\n\nimport (\n\t\"github.com/markdaws/gohome/pkg/cmd\"\n\t\"github.com/markdaws/gohome/pkg/gohome\"\n)\n\ntype extension struct {\n\tgohome.NullExtension\n}\n\nfunc (e *extension) Name() string {\n\treturn \"testing\"\n}\n\nfunc (e *extension) BuilderForDevice(sys *gohome.System, d *gohome.Device) cmd.Builder {\n\tswitch d.ModelNumber {\n\tcase \"testing.hardware\":\n\t\treturn &cmdBuilder{ModelNumber: d.ModelNumber, Device: d}\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc (e *extension) NetworkForDevice(sys *gohome.System, d *gohome.Device) gohome.Network {\n\treturn nil\n}\n\nfunc (e *extension) EventsForDevice(sys *gohome.System, d *gohome.Device) *gohome.ExtEvents {\n\tswitch d.ModelNumber {\n\tcase \"testing.hardware\":\n\t\tevts := &gohome.ExtEvents{}\n\t\tevts.Producer = &producer{\n\t\t\tDevice: d,\n\t\t\tSystem: sys,\n\t\t}\n\t\tevts.Consumer = &consumer{\n\t\t\tDevice: d,\n\t\t\tSystem: sys,\n\t\t}\n\t\treturn evts\n\tdefault:\n\t\treturn nil\n\t}\n}\n\n\n\nfunc NewExtension() *extension {\n\treturn &extension{}\n}\n\nfunc (e *extension) Discovery(sys *gohome.System) gohome.Discovery ", "output": "{\n\treturn &discovery{}\n}"} {"input": "package main\nimport (\n\"time\"\n\"fmt\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar deposits = make (chan int)\nvar balances = make (chan int)\n\nfunc Balance() int{\n\treturn <-balances\n}\nfunc teller(){\n\tvar balance int\n\tfor{\n\t\tselect{\n\t\t\tcase amount:=<-deposits:\n\t\t\t\tbalance+=amount\n\t\t\tcase balances<-balance:\n\t\t}\n\t}\n}\n\nfunc init(){\n\tgo teller()\n}\nfunc main() {\n\tgo func(){\n\t\tDeposit(200)\n\t\tfmt.Println(\"=\",Balance()) \n\t}()\n\n\tgo func(){\n\t\tDeposit(100)\n\t}()\n\ttime.Sleep(time.Second*1)\n}\n\nfunc Deposit(amount int)", "output": "{\n\tdeposits<-amount\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/gogf/gf/v2/errors/gerror\"\n)\n\n\n\nfunc OpenConfig() error {\n\treturn gerror.Wrap(OpenFile(), \"configuration file opening failed\")\n}\n\nfunc ReadConfig() error {\n\treturn gerror.Wrap(OpenConfig(), \"reading configuration failed\")\n}\n\nfunc main() {\n\tfmt.Println(gerror.Cause(ReadConfig()))\n}\n\nfunc OpenFile() error ", "output": "{\n\treturn gerror.New(\"permission denied\")\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestBye(t *testing.T) ", "output": "{\n\tvar actual = Hello()\n\tvar expected = \"Hello.\"\n\n\tif actual != expected {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n}"} {"input": "package delete\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewDeleteNodesIdentifierParams() *DeleteNodesIdentifierParams {\n\tvar ()\n\treturn &DeleteNodesIdentifierParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}\n\n\n\n\n\n\ntype DeleteNodesIdentifierParams struct {\n\n\tIdentifier string\n\n\ttimeout time.Duration\n}\n\n\nfunc (o *DeleteNodesIdentifierParams) WithIdentifier(identifier string) *DeleteNodesIdentifierParams {\n\to.Identifier = identifier\n\treturn o\n}\n\n\nfunc (o *DeleteNodesIdentifierParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif err := r.SetPathParam(\"identifier\", o.Identifier); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc NewDeleteNodesIdentifierParamsWithTimeout(timeout time.Duration) *DeleteNodesIdentifierParams ", "output": "{\n\tvar ()\n\treturn &DeleteNodesIdentifierParams{\n\n\t\ttimeout: timeout,\n\t}\n}"} {"input": "package render\n\n\ntype Data map[string]interface{}\n\n\nfunc NewData() *Data {\n\treturn &Data{}\n}\n\n\n\n\n\nfunc (d *Data) Del(key string) {\n\tif *d == nil {\n\t\treturn\n\t}\n\tdelete(*d, key)\n}\n\n\nfunc (d *Data) Get(key string) interface{} {\n\tif *d == nil {\n\t\treturn nil\n\t}\n\tdata, ok := (*d)[key]\n\tif ok == false {\n\t\treturn nil\n\t}\n\treturn data\n}\n\n\nfunc (d *Data) Merge(data *Data) {\n\tif *d == nil {\n\t\tdata := Data(map[string]interface{}{})\n\t\t*d = data\n\t}\n\tif data == nil || *data == nil {\n\t\treturn\n\t}\n\tfor k, v := range *data {\n\t\td.Set(k, v)\n\t}\n}\n\nfunc (d *Data) Set(key string, data interface{}) ", "output": "{\n\tif *d == nil {\n\t\tdata := Data(map[string]interface{}{})\n\t\t*d = data\n\t}\n\t(*d)[key] = data\n}"} {"input": "package gitlab\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n\n\t\"github.com/openshift/origin/pkg/oauthserver/oauth/external\"\n\n\t\"github.com/golang/glog\"\n)\n\n\n\nconst gitlabHostedDomain = \"gitlab.com\"\n\n\n\nfunc isLegacy(legacy *bool, URL string) bool {\n\tif legacy != nil {\n\t\treturn *legacy\n\t}\n\n\tif u, err := url.Parse(URL); err == nil && strings.EqualFold(u.Hostname(), gitlabHostedDomain) {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc NewProvider(providerName, URL, clientID, clientSecret string, transport http.RoundTripper, legacy *bool) (external.Provider, error) ", "output": "{\n\tif isLegacy(legacy, URL) {\n\t\tglog.Infof(\"Using legacy OAuth2 for GitLab identity provider %s url=%s clientID=%s\", providerName, URL, clientID)\n\t\treturn NewOAuthProvider(providerName, URL, clientID, clientSecret, transport)\n\t}\n\tglog.Infof(\"Using OIDC for GitLab identity provider %s url=%s clientID=%s\", providerName, URL, clientID)\n\treturn NewOIDCProvider(providerName, URL, clientID, clientSecret, transport)\n}"} {"input": "package v1beta1\n\nimport (\n\tv1beta1 \"k8s.io/api/certificates/v1beta1\"\n\t\"k8s.io/client-go/kubernetes/scheme\"\n\trest \"k8s.io/client-go/rest\"\n)\n\ntype CertificatesV1beta1Interface interface {\n\tRESTClient() rest.Interface\n\tCertificateSigningRequestsGetter\n}\n\n\ntype CertificatesV1beta1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *CertificatesV1beta1Client) CertificateSigningRequests() CertificateSigningRequestInterface {\n\treturn newCertificateSigningRequests(c)\n}\n\n\n\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *CertificatesV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *CertificatesV1beta1Client {\n\treturn &CertificatesV1beta1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *CertificatesV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc NewForConfig(c *rest.Config) (*CertificatesV1beta1Client, error) ", "output": "{\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &CertificatesV1beta1Client{client}, nil\n}"} {"input": "package iso20022\n\n\ntype AcknowledgementReason1 struct {\n\n\tCode *AcknowledgementReason1Choice `xml:\"Cd\"`\n\n\tAdditionalReasonInformation *Max210Text `xml:\"AddtlRsnInf,omitempty\"`\n}\n\nfunc (a *AcknowledgementReason1) AddCode() *AcknowledgementReason1Choice {\n\ta.Code = new(AcknowledgementReason1Choice)\n\treturn a.Code\n}\n\n\n\nfunc (a *AcknowledgementReason1) SetAdditionalReasonInformation(value string) ", "output": "{\n\ta.AdditionalReasonInformation = (*Max210Text)(&value)\n}"} {"input": "package flags\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n)\n\n\n\ntype IniError struct {\n\tMessage string\n\n\tFile string\n\n\tLineNumber uint\n}\n\n\nfunc (x *IniError) Error() string {\n\treturn fmt.Sprintf(\"%s:%d: %s\",\n\t\tx.File,\n\t\tx.LineNumber,\n\t\tx.Message)\n}\n\n\ntype IniOptions uint\n\nconst (\n\tIniNone IniOptions = 0\n\n\tIniIncludeDefaults = 1 << iota\n\n\tIniCommentDefaults\n\n\tIniIncludeComments\n\n\tIniDefault = IniIncludeComments\n)\n\n\n\ntype IniParser struct {\n\tparser *Parser\n}\n\n\nfunc NewIniParser(p *Parser) *IniParser {\n\treturn &IniParser{\n\t\tparser: p,\n\t}\n}\n\n\n\n\n\nfunc IniParse(filename string, data interface{}) error {\n\tp := NewParser(data, Default)\n\treturn NewIniParser(p).ParseFile(filename)\n}\n\n\n\n\nfunc (i *IniParser) ParseFile(filename string) error {\n\ti.parser.storeDefaults()\n\n\tini, err := readIniFromFile(filename)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn i.parse(ini)\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (i *IniParser) WriteFile(filename string, options IniOptions) error {\n\tfile, err := os.Create(filename)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer file.Close()\n\ti.Write(file, options)\n\n\treturn nil\n}\n\n\n\n\n\n\nfunc (i *IniParser) Write(writer io.Writer, options IniOptions) {\n\twriteIni(i, writer, options)\n}\n\nfunc (i *IniParser) Parse(reader io.Reader) error ", "output": "{\n\ti.parser.storeDefaults()\n\n\tini, err := readIni(reader, \"\")\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn i.parse(ini)\n}"} {"input": "package v1\n\n\n\ntype EnvVarSourceApplyConfiguration struct {\n\tFieldRef *ObjectFieldSelectorApplyConfiguration `json:\"fieldRef,omitempty\"`\n\tResourceFieldRef *ResourceFieldSelectorApplyConfiguration `json:\"resourceFieldRef,omitempty\"`\n\tConfigMapKeyRef *ConfigMapKeySelectorApplyConfiguration `json:\"configMapKeyRef,omitempty\"`\n\tSecretKeyRef *SecretKeySelectorApplyConfiguration `json:\"secretKeyRef,omitempty\"`\n}\n\n\n\nfunc EnvVarSource() *EnvVarSourceApplyConfiguration {\n\treturn &EnvVarSourceApplyConfiguration{}\n}\n\n\n\n\nfunc (b *EnvVarSourceApplyConfiguration) WithFieldRef(value *ObjectFieldSelectorApplyConfiguration) *EnvVarSourceApplyConfiguration {\n\tb.FieldRef = value\n\treturn b\n}\n\n\n\n\nfunc (b *EnvVarSourceApplyConfiguration) WithResourceFieldRef(value *ResourceFieldSelectorApplyConfiguration) *EnvVarSourceApplyConfiguration {\n\tb.ResourceFieldRef = value\n\treturn b\n}\n\n\n\n\n\n\n\n\n\nfunc (b *EnvVarSourceApplyConfiguration) WithSecretKeyRef(value *SecretKeySelectorApplyConfiguration) *EnvVarSourceApplyConfiguration {\n\tb.SecretKeyRef = value\n\treturn b\n}\n\nfunc (b *EnvVarSourceApplyConfiguration) WithConfigMapKeyRef(value *ConfigMapKeySelectorApplyConfiguration) *EnvVarSourceApplyConfiguration ", "output": "{\n\tb.ConfigMapKeyRef = value\n\treturn b\n}"} {"input": "package events\n\n\ntype Broker struct {\n\tevents chan Event \n\tsubs map[chan Event]string \n\tsub chan sub \n\tunsub chan sub \n}\n\n\ntype Event struct {\n\tName string \n\tData interface{} \n}\n\ntype sub struct {\n\tname string \n\tevents chan Event \n}\n\n\n\n\n\n\nfunc (b Broker) Subscribe(name string) chan Event {\n\tc := make(chan Event)\n\tb.sub <- sub{name: name, events: c}\n\treturn c\n}\n\n\nfunc (b Broker) Unsubscribe(c chan Event) {\n\tb.unsub <- sub{events: c}\n}\n\n\nfunc (b Broker) Publish(e Event) {\n\tb.events <- e\n}\n\nfunc New() *Broker ", "output": "{\n\tb := &Broker{\n\t\tevents: make(chan Event, 8),\n\t\tsubs: make(map[chan Event]string),\n\t\tsub: make(chan sub),\n\t\tunsub: make(chan sub),\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase c := <-b.sub: \n\t\t\t\tb.subs[c.events] = c.name\n\t\t\tcase c := <-b.unsub: \n\t\t\t\tdelete(b.subs, c.events)\n\t\t\tcase e := <-b.events: \n\t\t\t\tfor c := range b.subs {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase c <- e:\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn b\n}"} {"input": "package utils\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"testing\"\n)\n\n\n\nfunc TestFileExistsFunction(t *testing.T) ", "output": "{\n\ttmpDir := os.TempDir()\n\n\tdefer os.Remove(tmpDir)\n\n\tif exists := FileExists(tmpDir); exists {\n\t\tt.Errorf(\"Expected false when calling FileExists with directory: %s\", tmpDir)\n\t}\n\n\ttmpFile, err := ioutil.TempFile(tmpDir, \"functest\")\n\n\tif err != nil {\n\t\tt.Fatalf(\"Creating a temporary file filed: %s\", err)\n\t}\n\n\tdefer func() {\n\t\ttmpFile.Close()\n\t\tos.Remove(tmpFile.Name())\n\t}()\n\n\tif exists := FileExists(tmpFile.Name()); !exists {\n\t\tt.Errorf(\"Expected true when calling FileEists with a file %s\", tmpFile.Name())\n\t}\n}"} {"input": "package iso20022\n\n\ntype PointOfInteractionComponent6 struct {\n\n\tType *POIComponentType4Code `xml:\"Tp\"`\n\n\tIdentification *PointOfInteractionComponentIdentification1 `xml:\"Id\"`\n\n\tStatus *PointOfInteractionComponentStatus3 `xml:\"Sts,omitempty\"`\n\n\tStandardCompliance []*GenericIdentification48 `xml:\"StdCmplc,omitempty\"`\n\n\tCharacteristics *PointOfInteractionComponentCharacteristics2 `xml:\"Chrtcs,omitempty\"`\n\n\tAssessment []*PointOfInteractionComponentAssessment1 `xml:\"Assmnt,omitempty\"`\n}\n\nfunc (p *PointOfInteractionComponent6) SetType(value string) {\n\tp.Type = (*POIComponentType4Code)(&value)\n}\n\nfunc (p *PointOfInteractionComponent6) AddIdentification() *PointOfInteractionComponentIdentification1 {\n\tp.Identification = new(PointOfInteractionComponentIdentification1)\n\treturn p.Identification\n}\n\nfunc (p *PointOfInteractionComponent6) AddStatus() *PointOfInteractionComponentStatus3 {\n\tp.Status = new(PointOfInteractionComponentStatus3)\n\treturn p.Status\n}\n\nfunc (p *PointOfInteractionComponent6) AddStandardCompliance() *GenericIdentification48 {\n\tnewValue := new(GenericIdentification48)\n\tp.StandardCompliance = append(p.StandardCompliance, newValue)\n\treturn newValue\n}\n\n\n\nfunc (p *PointOfInteractionComponent6) AddAssessment() *PointOfInteractionComponentAssessment1 {\n\tnewValue := new(PointOfInteractionComponentAssessment1)\n\tp.Assessment = append(p.Assessment, newValue)\n\treturn newValue\n}\n\nfunc (p *PointOfInteractionComponent6) AddCharacteristics() *PointOfInteractionComponentCharacteristics2 ", "output": "{\n\tp.Characteristics = new(PointOfInteractionComponentCharacteristics2)\n\treturn p.Characteristics\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\n\n\nfunc isPrime(n int) bool {\n\tif n%2 == 0 {\n\t\treturn n == 2\n\t}\n\tfor i := 3; i*i <= n; i += 2 {\n\t\tif n%i == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc primeFactorize(n int) []int {\n\tvar p []int\n\tfor i := 2; i <= n; i++ {\n\t\tfor isPrime(i) {\n\t\t\tfor n%i == 0 {\n\t\t\t\tp = append(p, i)\n\t\t\t\tn /= i\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\treturn p\n}\n\nfunc main() {\n\tin, _ := os.Open(\"10042.in\")\n\tdefer in.Close()\n\tout, _ := os.Create(\"10042.out\")\n\tdefer out.Close()\n\n\tvar n, num int\n\tfor fmt.Fscanf(in, \"%d\", &n); n > 0; n-- {\n\t\tfor fmt.Fscanf(in, \"%d\", &num); ; num++ {\n\t\t\tsum1 := digitSum(num)\n\t\t\tsum2 := 0\n\t\t\tfor _, v := range primeFactorize(num) {\n\t\t\t\tsum2 += digitSum(v)\n\t\t\t}\n\t\t\tif sum1 == sum2 {\n\t\t\t\tfmt.Fprintln(out, num)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc digitSum(n int) int ", "output": "{\n\tsum := 0\n\tfor n > 0 {\n\t\tsum += n % 10\n\t\tn /= 10\n\t}\n\treturn sum\n}"} {"input": "package srtgears\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\nconst newLine = \"\\r\\n\" \n\n\ntype writer struct {\n\tw io.Writer \n\terr error \n}\n\n\nfunc (w *writer) pr(a ...interface{}) {\n\tif w.err == nil {\n\t\t_, w.err = fmt.Fprint(w.w, a...)\n\t}\n}\n\n\nfunc (w *writer) prn(a ...interface{}) {\n\tw.pr(a...)\n\tw.pr(newLine)\n}\n\n\n\n\nfunc (w *writer) prf(format string, a ...interface{}) ", "output": "{\n\tif w.err == nil {\n\t\t_, w.err = fmt.Fprintf(w.w, format, a...)\n\t}\n}"} {"input": "package crdt\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/mediocregopher/radix.v2/redis\"\n\t\"log\"\n)\n\nvar redisPort int\nvar zset string\nvar client *redis.Client\nvar err error\n\n\n\nfunc Remove(value int, elemName string) string {\n\tresp := client.Cmd(fmt.Sprintf(\"ZREM\"), zset, value, elemName)\n\tif resp.Err != nil {\n\t\tlog.Fatal(fmt.Sprintf(\"Command failed: %s\\n\", resp.Err))\n\t} else {\n\t\tfmt.Printf(\"%s\\n\", resp.String())\n\t}\n\treturn resp.String()\n}\n\nfunc PrintAll(minValue int, maxValue int, constraints string) string {\n\tresp := client.Cmd(fmt.Sprintf(\"ZRANGE\"), zset, minValue, maxValue, constraints)\n\tif resp.Err != nil {\n\t\tlog.Fatal(fmt.Sprintf(\"Command failed: %s\\n\", resp.Err))\n\t} else {\n\t\tfmt.Printf(\"%s\\n\", resp.String())\n\t}\n\n\treturn resp.String()\n}\n\nfunc checkInput() {\n\tif redisPort == 0 {\n\t\tlog.Fatal(\"Please specify the port at which the redis server is running using --port option.\")\n\t} else if zset == \"\" {\n\t\tlog.Fatal(\"Please specify the name of the ZSET to store using the --zset option.\")\n\t}\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tcheckInput()\n}\n\nfunc Add(value int, elemName string) string ", "output": "{\n\tresp := client.Cmd(fmt.Sprintf(\"ZADD\"), zset, value, elemName)\n\tif resp.Err != nil {\n\t\tlog.Fatal(fmt.Sprintf(\"Command failed: %s\\n\", resp.Err))\n\t} else {\n\t\tfmt.Printf(\"%s\\n\", resp.String())\n\t}\n\treturn resp.String()\n}"} {"input": "package node\n\nimport (\n\t\"fmt\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/docker/docker/api/types\"\n\t\"github.com/docker/docker/cli\"\n\t\"github.com/docker/docker/cli/command\"\n\t\"github.com/spf13/cobra\"\n)\n\ntype removeOptions struct {\n\tforce bool\n}\n\nfunc newRemoveCommand(dockerCli *command.DockerCli) *cobra.Command {\n\topts := removeOptions{}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"rm [OPTIONS] NODE [NODE...]\",\n\t\tAliases: []string{\"remove\"},\n\t\tShort: \"Remove one or more nodes from the swarm\",\n\t\tArgs: cli.RequiresMinArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn runRemove(dockerCli, args, opts)\n\t\t},\n\t}\n\tflags := cmd.Flags()\n\tflags.BoolVar(&opts.force, \"force\", false, \"Force remove an active node\")\n\treturn cmd\n}\n\n\n\nfunc runRemove(dockerCli *command.DockerCli, args []string, opts removeOptions) error ", "output": "{\n\tclient := dockerCli.Client()\n\tctx := context.Background()\n\tfor _, nodeID := range args {\n\t\terr := client.NodeRemove(ctx, nodeID, types.NodeRemoveOptions{Force: opts.force})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Fprintf(dockerCli.Out(), \"%s\\n\", nodeID)\n\t}\n\treturn nil\n}"} {"input": "package jwt_test\n\nimport (\n\t\"camlistore.org/third_party/golang.org/x/oauth2\"\n\t\"camlistore.org/third_party/golang.org/x/oauth2/jwt\"\n)\n\n\n\nfunc ExampleJWTConfig() ", "output": "{\n\tconf := &jwt.Config{\n\t\tEmail: \"xxx@developer.com\",\n\t\tPrivateKey: []byte(\"-----BEGIN RSA PRIVATE KEY-----...\"),\n\t\tSubject: \"user@example.com\",\n\t\tTokenURL: \"https:provider.com/o/oauth2/token\",\n\t}\n\tclient := conf.Client(oauth2.NoContext)\n\tclient.Get(\"...\")\n}"} {"input": "package rules\n\nimport (\n\t\"go/ast\"\n\t\"go/token\"\n\n\t\"istio.io/tools/pkg/checker\"\n)\n\n\n\n\n\n\ntype SkipIssue struct {\n\tskipArgsRegex string \n}\n\n\nfunc NewSkipByIssue() *SkipIssue {\n\treturn &SkipIssue{\n\t\tskipArgsRegex: `https:\\/\\/github\\.com\\/istio\\/istio\\/issues\\/[0-9]+`,\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc (lr *SkipIssue) Check(aNode ast.Node, fs *token.FileSet, lrp *checker.Report) {\n\tif fn, isFn := aNode.(*ast.FuncDecl); isFn {\n\t\tfor _, bd := range fn.Body.List {\n\t\t\tif ok, _ := matchFunc(bd, \"t\", \"SkipNow\"); ok {\n\t\t\t\tlrp.AddItem(fs.Position(bd.Pos()), lr.GetID(), \"Only t.Skip() is allowed and t.Skip() should contain an url to GitHub issue.\")\n\t\t\t} else if ok, _ := matchFunc(bd, \"t\", \"Skipf\"); ok {\n\t\t\t\tlrp.AddItem(fs.Position(bd.Pos()), lr.GetID(), \"Only t.Skip() is allowed and t.Skip() should contain an url to GitHub issue.\")\n\t\t\t} else if ok, fcall := matchFunc(bd, \"t\", \"Skip\"); ok && !matchFuncArgs(fcall, lr.skipArgsRegex) {\n\t\t\t\tlrp.AddItem(fs.Position(bd.Pos()), lr.GetID(), \"Only t.Skip() is allowed and t.Skip() should contain an url to GitHub issue.\")\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (lr *SkipIssue) GetID() string ", "output": "{\n\treturn GetCallerFileName()\n}"} {"input": "package node\n\nimport (\n\t\"fmt\"\n)\n\n\ntype Node struct {\n\tPriority uint\n\tLoad interface{}\n}\n\nfunc (n Node) String() string {\n\treturn fmt.Sprintf(\"{ Priority : %d, Load : %+v}\", n.Priority, n.Load)\n}\n\n\n\n\n\nfunc New(load interface{}, priority uint) *Node {\n\treturn &Node{Load: load, Priority: priority}\n}\n\nfunc NewEmptyNode() Node ", "output": "{\n\treturn Node{}\n}"} {"input": "package filter\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/200sc/klangsynthese/audio/filter/supports\"\n)\n\n\n\n\n\nfunc Speed(ratio float64, pitchShifter PitchShifter) Encoding ", "output": "{\n\treturn func(senc supports.Encoding) {\n\t\tr := ratio\n\t\tfmt.Println(ratio)\n\t\tfor r < .5 {\n\t\t\tr *= 2\n\t\t\tpitchShifter.PitchShift(.5)(senc)\n\t\t}\n\t\tfor r > 2.0 {\n\t\t\tr /= 2\n\t\t\tpitchShifter.PitchShift(2.0)(senc)\n\t\t}\n\t\tpitchShifter.PitchShift(1 / r)(senc)\n\t\tModSampleRate(ratio)(senc.GetSampleRate())\n\t}\n}"} {"input": "package core\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\n\n\nfunc PodContainerKey(namespace, podName, containerName string) string {\n\treturn fmt.Sprintf(\"namespace:%s/pod:%s/container:%s\", namespace, podName, containerName)\n}\n\nfunc PodKey(namespace, podName string) string {\n\treturn fmt.Sprintf(\"namespace:%s/pod:%s\", namespace, podName)\n}\n\nfunc NamespaceKey(namespace string) string {\n\treturn fmt.Sprintf(\"namespace:%s\", namespace)\n}\n\nfunc NodeKey(node string) string {\n\treturn fmt.Sprintf(\"node:%s\", node)\n}\n\n\n\nfunc ClusterKey() string {\n\treturn \"cluster\"\n}\n\nfunc NodeContainerKey(node, container string) string ", "output": "{\n\treturn fmt.Sprintf(\"node:%s/container:%s\", node, container)\n}"} {"input": "package server\n\nimport (\n\t\"math/rand\"\n\t\"time\"\n\n\t\"github.com/kyokomi/expcache\"\n)\n\ntype ImageCache interface {\n\tGetRandomImageURL() string\n}\n\ntype imageCache struct {\n\tExpire expcache.ExpireOnMemoryCache\n\tcache []string\n\n\ttwAPI TwitterAPI\n\trd *rand.Rand\n\ttwitterID string\n\tcacheCnt int\n}\n\nfunc NewImageCache(twAPI TwitterAPI, twitterID string, cacheCnt int) ImageCache {\n\te := &imageCache{\n\t\tcache: []string{},\n\t\ttwAPI: twAPI,\n\t\trd: rand.New(rand.NewSource(time.Now().UnixNano())),\n\t\ttwitterID: twitterID,\n\t\tcacheCnt: cacheCnt,\n\t}\n\te.Expire = expcache.NewExpireMemoryCache(e, 24*time.Hour)\n\treturn e\n}\n\n\n\nfunc (c *imageCache) Refresh() error {\n\timages, err := c.twAPI.GetFavoritesImages(c.cacheCnt, c.twitterID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.cache = images\n\treturn nil\n}\n\nvar _ expcache.OnMemoryCache = (*imageCache)(nil)\nvar _ ImageCache = (*imageCache)(nil)\n\nfunc (c *imageCache) GetRandomImageURL() string ", "output": "{\n\tvar result string\n\tc.Expire.WithRefreshLock(time.Now(), func() {\n\t\tidx := c.rd.Int31n(int32(len(c.cache))) - 1\n\t\tresult = c.cache[idx]\n\t})\n\treturn result\n}"} {"input": "package protocol\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\tsyncthingprotocol \"github.com/syncthing/syncthing/lib/protocol\"\n)\n\nconst (\n\tmessageTypePing int32 = iota\n\tmessageTypePong\n\tmessageTypeJoinRelayRequest\n\tmessageTypeJoinSessionRequest\n\tmessageTypeResponse\n\tmessageTypeConnectRequest\n\tmessageTypeSessionInvitation\n)\n\ntype header struct {\n\tmagic uint32\n\tmessageType int32\n\tmessageLength int32\n}\n\ntype Ping struct{}\ntype Pong struct{}\ntype JoinRelayRequest struct{}\n\ntype JoinSessionRequest struct {\n\tKey []byte \n}\n\ntype Response struct {\n\tCode int32\n\tMessage string\n}\n\ntype ConnectRequest struct {\n\tID []byte \n}\n\ntype SessionInvitation struct {\n\tFrom []byte \n\tKey []byte \n\tAddress []byte \n\tPort uint16\n\tServerSocket bool\n}\n\nfunc (i SessionInvitation) String() string {\n\treturn fmt.Sprintf(\"%s@%s\", syncthingprotocol.DeviceIDFromBytes(i.From), i.AddressString())\n}\n\nfunc (i SessionInvitation) GoString() string {\n\treturn i.String()\n}\n\n\n\nfunc (i SessionInvitation) AddressString() string ", "output": "{\n\treturn fmt.Sprintf(\"%s:%d\", net.IP(i.Address), i.Port)\n}"} {"input": "package modules\n\nimport (\n\t\"github.com/FederatedAI/KubeFATE/k8s-deploy/pkg/service\"\n\t\"github.com/rs/zerolog/log\"\n)\n\n\n\nfunc (e *Cluster) GetClusterStatus() (map[string]map[string]string, error) ", "output": "{\n\n\tClusterPodStatus, err := service.GetClusterPodStatus(e.Name, e.NameSpace)\n\tif err != nil {\n\t\tlog.Error().Err(err).Msg(\"GetClusterPodStatus error\")\n\t\treturn nil, err\n\t}\n\n\n\treturn map[string]map[string]string{\n\t\t\"modules\": ClusterPodStatus,\n\t}, nil\n}"} {"input": "package common\n\nimport (\n\t\"github.com/golang/protobuf/proto\"\n\t\"github.com/hyperledger/fabric/core/util\"\n)\n\nfunc (b *BlockHeader) Hash() []byte {\n\tdata, err := proto.Marshal(b) \n\tif err != nil {\n\t\tpanic(\"This should never fail and is generally irrecoverable\")\n\t}\n\n\treturn util.ComputeCryptoHash(data)\n}\n\n\n\nfunc (b *BlockData) Hash() []byte ", "output": "{\n\tdata, err := proto.Marshal(b) \n\tif err != nil {\n\t\tpanic(\"This should never fail and is generally irrecoverable\")\n\t}\n\n\treturn util.ComputeCryptoHash(data)\n}"} {"input": "package cpumanager\n\nimport (\n\t\"k8s.io/api/core/v1\"\n\t\"k8s.io/klog\"\n\t\"k8s.io/kubernetes/pkg/kubelet/cm/cpumanager/state\"\n\t\"k8s.io/kubernetes/pkg/kubelet/cm/topologymanager\"\n)\n\ntype nonePolicy struct{}\n\nvar _ Policy = &nonePolicy{}\n\n\nconst PolicyNone policyName = \"none\"\n\n\nfunc NewNonePolicy() Policy {\n\treturn &nonePolicy{}\n}\n\nfunc (p *nonePolicy) Name() string {\n\treturn string(PolicyNone)\n}\n\nfunc (p *nonePolicy) Start(s state.State) {\n\tklog.Info(\"[cpumanager] none policy: Start\")\n}\n\n\n\nfunc (p *nonePolicy) RemoveContainer(s state.State, podUID string, containerName string) error {\n\treturn nil\n}\n\nfunc (p *nonePolicy) GetTopologyHints(s state.State, pod v1.Pod, container v1.Container) map[string][]topologymanager.TopologyHint {\n\treturn nil\n}\n\nfunc (p *nonePolicy) AddContainer(s state.State, pod *v1.Pod, container *v1.Container) error ", "output": "{\n\treturn nil\n}"} {"input": "package common\n\nimport (\n . \"launchpad.net/gocheck\"\n \"sync\"\n)\n\ntype HealthzSuite struct {\n}\n\nvar _ = Suite(&HealthzSuite{})\n\nfunc (s *HealthzSuite) SetUpTest(c *C) {\n Component = VcapComponent{\n Config: map[string]interface{}{\"ip\": \"localhost\", \"port\": 8080},\n }\n}\n\n\n\nfunc (s *HealthzSuite) TestJsonMarshal(c *C) {\n healthz := &Healthz{\n LockableObject: &sync.Mutex{},\n }\n bytes, _ := healthz.MarshalJSON()\n c.Assert(string(bytes), Equals, \"{\\\"health\\\":\\\"ok\\\"}\")\n}\n\nfunc (s *HealthzSuite) TearDownTest(c *C) ", "output": "{\n Component = VcapComponent{}\n}"} {"input": "package client\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\tkapi \"k8s.io/kubernetes/pkg/api\"\n\n\tquotaapi \"github.com/openshift/origin/pkg/quota/api\"\n)\n\n\ntype AppliedClusterResourceQuotasNamespacer interface {\n\tAppliedClusterResourceQuotas(namespace string) AppliedClusterResourceQuotaInterface\n}\n\n\ntype AppliedClusterResourceQuotaInterface interface {\n\tList(opts metav1.ListOptions) (*quotaapi.AppliedClusterResourceQuotaList, error)\n\tGet(name string, options metav1.GetOptions) (*quotaapi.AppliedClusterResourceQuota, error)\n}\n\n\ntype appliedClusterResourceQuotas struct {\n\tr *Client\n\tns string\n}\n\n\nfunc newAppliedClusterResourceQuotas(c *Client, namespace string) *appliedClusterResourceQuotas {\n\treturn &appliedClusterResourceQuotas{\n\t\tr: c,\n\t\tns: namespace,\n\t}\n}\n\n\nfunc (c *appliedClusterResourceQuotas) List(opts metav1.ListOptions) (result *quotaapi.AppliedClusterResourceQuotaList, err error) {\n\tresult = "aapi.AppliedClusterResourceQuotaList{}\n\terr = c.r.Get().Namespace(c.ns).Resource(\"appliedclusterresourcequotas\").VersionedParams(&opts, kapi.ParameterCodec).Do().Into(result)\n\treturn\n}\n\n\n\n\nfunc (c *appliedClusterResourceQuotas) Get(name string, options metav1.GetOptions) (result *quotaapi.AppliedClusterResourceQuota, err error) ", "output": "{\n\tresult = "aapi.AppliedClusterResourceQuota{}\n\terr = c.r.Get().Namespace(c.ns).Resource(\"appliedclusterresourcequotas\").Name(name).VersionedParams(&options, kapi.ParameterCodec).Do().Into(result)\n\treturn\n}"} {"input": "package route\n\nimport \"unsafe\"\n\nvar (\n\tnativeEndian binaryByteOrder\n\tkernelAlign int\n\trtmVersion byte\n\twireFormats map[int]*wireFormat\n)\n\n\n\nfunc roundup(l int) int {\n\tif l == 0 {\n\t\treturn kernelAlign\n\t}\n\treturn (l + kernelAlign - 1) &^ (kernelAlign - 1)\n}\n\ntype wireFormat struct {\n\textOff int \n\tbodyOff int \n\tparse func(RIBType, []byte) (Message, error)\n}\n\nfunc init() ", "output": "{\n\ti := uint32(1)\n\tb := (*[4]byte)(unsafe.Pointer(&i))\n\tif b[0] == 1 {\n\t\tnativeEndian = littleEndian\n\t} else {\n\t\tnativeEndian = bigEndian\n\t}\n\trtmVersion = sysRTM_VERSION\n\tkernelAlign, wireFormats = probeRoutingStack()\n}"} {"input": "package host_path\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"syscall\"\n\n\t\"k8s.io/api/core/v1\"\n)\n\n\n\nfunc (dftc *defaultFileTypeChecker) getFileType(info os.FileInfo) (v1.HostPathType, error) ", "output": "{\n\tmode := info.Sys().(*syscall.Win32FileAttributeData).FileAttributes\n\tswitch mode & syscall.S_IFMT {\n\tcase syscall.S_IFSOCK:\n\t\treturn v1.HostPathSocket, nil\n\tcase syscall.S_IFBLK:\n\t\treturn v1.HostPathBlockDev, nil\n\tcase syscall.S_IFCHR:\n\t\treturn v1.HostPathCharDev, nil\n\t}\n\treturn \"\", fmt.Errorf(\"only recognise socket, block device and character device\")\n}"} {"input": "package auth\n\nimport (\n\t\"context\"\n)\n\ntype tokenNop struct{}\n\nfunc (t *tokenNop) enable() {}\nfunc (t *tokenNop) disable() {}\nfunc (t *tokenNop) invalidateUser(string) {}\nfunc (t *tokenNop) genTokenPrefix() (string, error) { return \"\", nil }\nfunc (t *tokenNop) info(ctx context.Context, token string, rev uint64) (*AuthInfo, bool) {\n\treturn nil, false\n}\nfunc (t *tokenNop) assign(ctx context.Context, username string, revision uint64) (string, error) {\n\treturn \"\", ErrAuthFailed\n}\n\n\nfunc newTokenProviderNop() (*tokenNop, error) ", "output": "{\n\treturn &tokenNop{}, nil\n}"} {"input": "package main\n\nimport \"github.com/go-check/check\"\n\n\n\n\nfunc (s *DockerSwarmSuite) nodeCmd(c *check.C, id, cmd string, args ...string) (string, error) {\n\treturn s.getDaemon(c, id).Cmd(cmd, args...)\n}\n\nfunc (s *DockerSwarmSuite) getDaemon(c *check.C, nodeID string) *SwarmDaemon ", "output": "{\n\ts.daemonsLock.Lock()\n\tdefer s.daemonsLock.Unlock()\n\tfor _, d := range s.daemons {\n\t\tif d.NodeID == nodeID {\n\t\t\treturn d\n\t\t}\n\t}\n\tc.Fatalf(\"could not find node with id: %s\", nodeID)\n\treturn nil\n}"} {"input": "package lifegame\n\ntype Universe struct {\n\taliveCells []Cell\n}\n\ntype Cell struct{}\n\n\n\nfunc (u *Universe) HasAliveCell() bool {\n\treturn len(u.AliveCells()) != 0\n}\n\nfunc (u *Universe) AliveCells() []Cell {\n\treturn u.aliveCells\n}\n\nfunc (u *Universe) NextGeneration() {\n\tu.aliveCells = []Cell{}\n}\n\nfunc (u *Universe) BornCellAtLocation(x, y int) {\n\tu.aliveCells = append(u.aliveCells, Cell{})\n}\n\nfunc (c *Cell) Location() (int, int) {\n\treturn 0, 0\n}\n\nfunc NewUniverse() *Universe ", "output": "{\n\treturn &Universe{}\n}"} {"input": "package gtk\n\n\n\nimport \"C\"\n\nimport (\n\t\"unsafe\"\n)\n\n\nfunc (v *Menu) PopupAtMouseCursor(parentMenuShell IMenu, parentMenuItem IMenuItem, button int, activateTime uint32) {\n\twshell := nullableWidget(parentMenuShell)\n\twitem := nullableWidget(parentMenuItem)\n\n\tC.gtk_menu_popup(v.native(),\n\t\twshell,\n\t\twitem,\n\t\tnil,\n\t\tnil,\n\t\tC.guint(button),\n\t\tC.guint32(activateTime))\n}\n\nfunc (v *SizeGroup) GetIgnoreHidden() bool {\n\tc := C.gtk_size_group_get_ignore_hidden(v.native())\n\treturn gobool(c)\n}\n\n\n\n\nfunc (v *SizeGroup) SetIgnoreHidden(ignoreHidden bool) {\n\tC.gtk_size_group_set_ignore_hidden(v.native(), gbool(ignoreHidden))\n}\n\n\nfunc (v *FontButton) GetFontName() string {\n\tc := C.gtk_font_button_get_font_name(v.native())\n\treturn goString(c)\n}\n\n\nfunc (v *FontButton) SetFontName(fontname string) bool {\n\tcstr := C.CString(fontname)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tc := C.gtk_font_button_set_font_name(v.native(), (*C.gchar)(cstr))\n\treturn gobool(c)\n}\n\nfunc (v *Window) SetWMClass(name, class string) ", "output": "{\n\tcName := C.CString(name)\n\tdefer C.free(unsafe.Pointer(cName))\n\tcClass := C.CString(class)\n\tdefer C.free(unsafe.Pointer(cClass))\n\tC.gtk_window_set_wmclass(v.native(), (*C.gchar)(cName), (*C.gchar)(cClass))\n}"} {"input": "package frame\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com/go-git/go-git/v5/utils/merkletrie/noder\"\n)\n\n\n\ntype Frame struct {\n\tstack []noder.Noder\n}\n\ntype byName []noder.Noder\n\nfunc (a byName) Len() int { return len(a) }\nfunc (a byName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a byName) Less(i, j int) bool {\n\treturn strings.Compare(a[i].Name(), a[j].Name()) < 0\n}\n\n\nfunc New(n noder.Noder) (*Frame, error) {\n\tchildren, err := n.Children()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsort.Sort(sort.Reverse(byName(children)))\n\treturn &Frame{\n\t\tstack: children,\n\t}, nil\n}\n\n\n\n\n\n\n\n\nfunc (f *Frame) String() string {\n\tvar buf bytes.Buffer\n\t_ = buf.WriteByte('[')\n\n\tsep := \"\"\n\tfor i := f.Len() - 1; i >= 0; i-- {\n\t\t_, _ = buf.WriteString(sep)\n\t\tsep = \", \"\n\t\t_, _ = buf.WriteString(fmt.Sprintf(\"%q\", f.stack[i].Name()))\n\t}\n\n\t_ = buf.WriteByte(']')\n\n\treturn buf.String()\n}\n\n\n\n\nfunc (f *Frame) First() (noder.Noder, bool) {\n\tif f.Len() == 0 {\n\t\treturn nil, false\n\t}\n\n\ttop := f.Len() - 1\n\n\treturn f.stack[top], true\n}\n\n\n\n\n\n\nfunc (f *Frame) Len() int {\n\treturn len(f.stack)\n}\n\nfunc (f *Frame) Drop() ", "output": "{\n\tif f.Len() == 0 {\n\t\treturn\n\t}\n\n\ttop := f.Len() - 1\n\tf.stack[top] = nil\n\tf.stack = f.stack[:top]\n}"} {"input": "package terraform\n\nimport (\n\t\"github.com/hashicorp/terraform/config/module\"\n)\n\n\n\n\ntype ImportGraphBuilder struct {\n\tImportTargets []*ImportTarget\n\n\tModule *module.Tree\n\n\tProviders []string\n}\n\n\nfunc (b *ImportGraphBuilder) Build(path []string) (*Graph, error) {\n\treturn (&BasicGraphBuilder{\n\t\tSteps: b.Steps(),\n\t\tValidate: true,\n\t\tName: \"ImportGraphBuilder\",\n\t}).Build(path)\n}\n\n\n\n\n\nfunc (b *ImportGraphBuilder) Steps() []GraphTransformer ", "output": "{\n\tmod := b.Module\n\tif mod == nil {\n\t\tmod = module.NewEmptyTree()\n\t}\n\n\tproviderFactory := func(name string, path []string) GraphNodeProvider {\n\t\treturn &NodeApplyableProvider{\n\t\t\tNameValue: name,\n\t\t\tPathValue: path,\n\t\t}\n\t}\n\n\tsteps := []GraphTransformer{\n\t\t&ConfigTransformerOld{Module: mod},\n\n\t\t&ImportStateTransformer{Targets: b.ImportTargets},\n\n\t\t&MissingProviderTransformer{Providers: b.Providers, Factory: providerFactory},\n\t\t&ProviderTransformer{},\n\t\t&DisableProviderTransformerOld{},\n\t\t&PruneProviderTransformer{},\n\t\t&AttachProviderConfigTransformer{Module: mod},\n\n\t\t&ImportProviderValidateTransformer{},\n\n\t\t&RootTransformer{},\n\n\t\t&TransitiveReductionTransformer{},\n\t}\n\n\treturn steps\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"compress/gzip\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"math\"\n\t\"math/rand\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc compress(s string) string {\n\tvar buf bytes.Buffer\n\tzw := gzip.NewWriter(&buf)\n\n\t_, err := zw.Write([]byte(s))\n\tif err != nil {\n\t\tfmt.Println(\"gzip 1 err\", err)\n\t\treturn \"\"\n\t}\n\tif err := zw.Close(); err != nil {\n\t\tfmt.Println(\"gzip 2 err\", err)\n\t\treturn \"\"\n\t}\n\treturn buf.String()\n}\n\n\n\nfunc generate100Uint32() string {\n\tlist := make([]string, 100)\n\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tfor i := 0; i < 100; i++ {\n\t\tlist[i] = strconv.FormatUint(uint64(r.Uint32()), 10)\n\t}\n\treturn strings.Join(list, \" \")\n}\n\nfunc main() {\n\ttotal, min, max, count := 0, math.MaxInt32, 0, 1000000\n\tstarttime := time.Now()\n\tfor i := 0; i < count; i++ {\n\t\tr := generate100Uint32()\n\t\ts := compress(r)\n\t\tif len(s) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tlength := len(s)\n\t\tif min > length {\n\t\t\tmin = length\n\t\t}\n\t\tif max < length {\n\t\t\tmax = length\n\t\t}\n\t\ttotal += length\n\n\t\tif i%100000 == 0 {\n\t\t\tfmt.Println(i, \"is done and takes\", time.Since(starttime))\n\t\t}\n\t}\n\tfmt.Printf(\"max:%d, min:%d, avg:%d\\n\", max, min, total/count)\n}\n\nfunc uncompress(s string) string ", "output": "{\n\tbuf := bytes.NewBufferString(s)\n\tzr, err := gzip.NewReader(buf)\n\tif err != nil {\n\t\tfmt.Println(\"gzip 3 err\", err)\n\t\treturn \"\"\n\t}\n\n\tbts, err := ioutil.ReadAll(zr)\n\tif err != nil {\n\t\tfmt.Println(\"gzip 4 err\", err)\n\t\treturn \"\"\n\t}\n\n\tif err := zr.Close(); err != nil {\n\t\tfmt.Println(\"gzip 5 err\", err)\n\t\treturn \"\"\n\t}\n\treturn string(bts)\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"text/tabwriter\"\n\n\t\"github.com/skriptble/froxy/cmd/froxy/Godeps/_workspace/src/github.com/BurntSushi/toml\"\n)\n\nvar (\n\tflagTypes = false\n)\n\nfunc init() {\n\tlog.SetFlags(0)\n\n\tflag.BoolVar(&flagTypes, \"types\", flagTypes,\n\t\t\"When set, the types of every defined key will be shown.\")\n\n\tflag.Usage = usage\n\tflag.Parse()\n}\n\nfunc usage() {\n\tlog.Printf(\"Usage: %s toml-file [ toml-file ... ]\\n\",\n\t\tpath.Base(os.Args[0]))\n\tflag.PrintDefaults()\n\n\tos.Exit(1)\n}\n\nfunc main() {\n\tif flag.NArg() < 1 {\n\t\tflag.Usage()\n\t}\n\tfor _, f := range flag.Args() {\n\t\tvar tmp interface{}\n\t\tmd, err := toml.DecodeFile(f, &tmp)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error in '%s': %s\", f, err)\n\t\t}\n\t\tif flagTypes {\n\t\t\tprintTypes(md)\n\t\t}\n\t}\n}\n\n\n\nfunc printTypes(md toml.MetaData) ", "output": "{\n\ttabw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)\n\tfor _, key := range md.Keys() {\n\t\tfmt.Fprintf(tabw, \"%s%s\\t%s\\n\",\n\t\t\tstrings.Repeat(\" \", len(key)-1), key, md.Type(key...))\n\t}\n\ttabw.Flush()\n}"} {"input": "package consul\n\nimport (\n\t\"log\"\n\n\t\"github.com/armon/consul-api\"\n\t\"github.com/hashicorp/terraform/helper/config\"\n\t\"github.com/hashicorp/terraform/terraform\"\n)\n\ntype ResourceProvider struct {\n\tConfig Config\n\tclient *consulapi.Client\n}\n\n\n\nfunc (p *ResourceProvider) ValidateResource(\n\tt string, c *terraform.ResourceConfig) ([]string, []error) {\n\treturn resourceMap.Validate(t, c)\n}\n\nfunc (p *ResourceProvider) Configure(c *terraform.ResourceConfig) error {\n\tif _, err := config.Decode(&p.Config, c.Config); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"[INFO] Initializing Consul client\")\n\tvar err error\n\tp.client, err = p.Config.Client()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (p *ResourceProvider) Apply(\n\ts *terraform.ResourceState,\n\td *terraform.ResourceDiff) (*terraform.ResourceState, error) {\n\treturn resourceMap.Apply(s, d, p)\n}\n\nfunc (p *ResourceProvider) Diff(\n\ts *terraform.ResourceState,\n\tc *terraform.ResourceConfig) (*terraform.ResourceDiff, error) {\n\treturn resourceMap.Diff(s, c, p)\n}\n\nfunc (p *ResourceProvider) Refresh(\n\ts *terraform.ResourceState) (*terraform.ResourceState, error) {\n\treturn resourceMap.Refresh(s, p)\n}\n\nfunc (p *ResourceProvider) Resources() []terraform.ResourceType {\n\treturn resourceMap.Resources()\n}\n\nfunc (p *ResourceProvider) Validate(c *terraform.ResourceConfig) ([]string, []error) ", "output": "{\n\tv := &config.Validator{\n\t\tOptional: []string{\n\t\t\t\"datacenter\",\n\t\t\t\"address\",\n\t\t},\n\t}\n\treturn v.Validate(c)\n}"} {"input": "package bot\n\nimport(\n \"github.com/mduszyk/foobot/proto\"\n \"github.com/mduszyk/foobot/module\"\n)\n\ntype HelpModule struct {\n bot *Bot\n}\n\nfunc NewHelpModule(bot *Bot) *HelpModule {\n return &HelpModule{bot}\n}\n\nfunc (m *HelpModule) CMD_(msg *proto.Msg) string {\n rsp := \"\"\n for k, v := range m.bot.GetModules() {\n rsp += \" \" + k\n methods := module.CmdMethods(v)\n if len(methods) > 0 {\n rsp += \" (\" + methods + \")\"\n }\n rsp += \"\\n\"\n }\n\n return rsp\n}\n\n\n\nfunc (m *HelpModule) Handle(msg *proto.Msg) string ", "output": "{\n return module.CallCmdMethod(m, msg)\n}"} {"input": "package persist\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\n\t_ \"github.com/go-sql-driver/mysql\"\n)\n\n\ntype Database struct {\n\tuser string\n\tpassword string\n\tdatabase string\n\thost string\n}\n\n\nfunc NewDatabase(username string, password string, database string, host string) Database {\n\treturn Database{username, password, database, host}\n}\n\n\nfunc (db Database) TestConnection() error {\n\tcon, err := db.getConnection()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer con.Close()\n\n\terr = con.Ping()\n\treturn err\n}\n\nfunc (db Database) getConnection() (*sql.DB, error) {\n\tcon, err := sql.Open(\"mysql\", fmt.Sprintf(\"%v:%v@tcp(%v:3306)/%v?parseTime=true\", db.user, db.password, db.host, db.database))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn con, nil\n}\n\n\n\n\nfunc (db Database) GetConnectionString() string ", "output": "{\n\treturn fmt.Sprintf(\"Data Source=%s;Database=%s;User ID=%s;Password=%s;Old Guids=true;\", db.host, db.database, db.user, db.password)\n}"} {"input": "package scan\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"h12.io/dfa\"\n)\n\ntype Matcher struct {\n\t*dfa.M\n\tEOF int\n\tIllegal int\n\n\tfast *dfa.FastM\n}\ntype MID struct {\n\tM interface{}\n\tID int\n}\n\nfunc NewMatcher(eof, illegal int, mids []MID) *Matcher {\n\tm := or(mids)\n\tfast := m.ToFast()\n\treturn &Matcher{\n\t\tEOF: eof,\n\t\tIllegal: illegal,\n\t\tM: m,\n\t\tfast: fast}\n}\n\nfunc (m *Matcher) Init() *Matcher {\n\tm.fast = m.M.ToFast()\n\treturn m\n}\n\n\n\nfunc (m *Matcher) Count() int {\n\treturn m.fast.Count()\n}\n\nfunc (m *Matcher) WriteGo(w io.Writer, pac string) {\n\tfmt.Fprintln(w, \"&scan.Matcher{\")\n\tfmt.Fprintf(w, \"EOF: %d,\\n\", m.EOF)\n\tfmt.Fprintf(w, \"Illegal: %d,\\n\", m.Illegal)\n\tfmt.Fprint(w, \"M: \")\n\tm.M.WriteGo(w, pac)\n\tfmt.Fprintln(w, \"}\")\n}\n\nfunc or(mids []MID) *dfa.M {\n\tms := make([]interface{}, len(mids))\n\tfor i, mid := range mids {\n\t\tvar m *dfa.M\n\t\tswitch o := mid.M.(type) {\n\t\tcase *dfa.M:\n\t\t\tm = o\n\t\tcase string:\n\t\t\tm = dfa.Str(o)\n\t\tdefault:\n\t\t\tpanic(\"member M of MID should be type of either string or *M\")\n\t\t}\n\t\tms[i] = m.As(mid.ID)\n\t}\n\treturn dfa.Or(ms...)\n}\n\nfunc (m *Matcher) Size() int ", "output": "{\n\treturn m.fast.Size()\n}"} {"input": "package goutils\n\nimport (\n\t\"bytes\"\n\t\"crypto/aes\"\n\t\"crypto/cipher\"\n\t\"crypto/rand\"\n\t\"encoding/base64\"\n\t\"errors\"\n\t\"io\"\n\t\"strings\"\n)\n\nfunc AddBase64Padding(value string) string {\n\tm := len(value) % 4\n\tif m != 0 {\n\t\tvalue += strings.Repeat(\"=\", 4-m)\n\t}\n\n\treturn value\n}\n\nfunc RemoveBase64Padding(value string) string {\n\treturn strings.Replace(value, \"=\", \"\", -1)\n}\n\nfunc PKCS5PaddingPad(src []byte) []byte {\n\tpadding := aes.BlockSize - len(src)%aes.BlockSize\n\tpadtext := bytes.Repeat([]byte{byte(padding)}, padding)\n\treturn append(src, padtext...)\n}\n\nfunc PKCS5PaddingUnpad(src []byte) ([]byte, error) {\n\tlength := len(src)\n\tunpadding := int(src[length-1])\n\n\tif unpadding > length {\n\t\treturn nil, errors.New(\"unpad error. This could happen when incorrect encryption key is used\")\n\t}\n\n\treturn src[:(length - unpadding)], nil\n}\n\nfunc AesCBCEncrypt(key []byte, text string) (string, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tmsg := PKCS5PaddingPad([]byte(text))\n\tciphertext := make([]byte, aes.BlockSize+len(msg))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcbc := cipher.NewCBCEncrypter(block, iv)\n\tcbc.CryptBlocks(ciphertext[aes.BlockSize:], msg)\n\tfinalMsg := RemoveBase64Padding(base64.URLEncoding.EncodeToString(ciphertext))\n\treturn finalMsg, nil\n}\n\n\n\nfunc AesCBCDecrypt(key []byte, text string) (string, error) ", "output": "{\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdecodedMsg, err := base64.URLEncoding.DecodeString(AddBase64Padding(text))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif (len(decodedMsg) % aes.BlockSize) != 0 {\n\t\treturn \"\", errors.New(\"blocksize must be multipe of decoded message length\")\n\t}\n\n\tiv := decodedMsg[:aes.BlockSize]\n\tmsg := decodedMsg[aes.BlockSize:]\n\n\tcbc := cipher.NewCBCDecrypter(block, iv)\n\tcbc.CryptBlocks(msg, msg)\n\n\tunpadMsg, err := PKCS5PaddingUnpad(msg)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(unpadMsg), nil\n}"} {"input": "package gftest\n\nimport (\n \"errors\"\n \"reflect\"\n \"encoding/json\"\n)\n\nfunc (req *Request) Debug(msg string) { req.t.Log(req.FullPath() + \": %v\", msg) }\n\nfunc (req *Request) NewError(msg string) error {\n\n\terr := errors.New(req.FullPath() + \": \" + msg)\n\treturn err\n}\n\nfunc (req *Request) Error(e error) { req.t.Log(e.Error()) }\n\nfunc (req *Request) Reflect(e interface{}) {\n\tmsg := \"REFLECT VALUE IS NIL\"\n\tif e != nil {\n\t\tmsg = \"REFLECT VALUE IS \"+reflect.TypeOf(e).String()\n\t}\n\treq.NewError(msg)\n}\n\n\n\nfunc (req *Request) DebugJSON(i interface{}) ", "output": "{\n\tb, err := json.Marshal(i); if err != nil { req.Error(err); return }\n\treq.Debug(string(b))\n}"} {"input": "package oauth2\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\nconst (\n\tErrorAccessDenied = \"access_denied\"\n\tErrorInvalidClient = \"invalid_client\"\n\tErrorInvalidGrant = \"invalid_grant\"\n\tErrorInvalidRequest = \"invalid_request\"\n\tErrorServerError = \"server_error\"\n\tErrorUnauthorizedClient = \"unauthorized_client\"\n\tErrorUnsupportedGrantType = \"unsupported_grant_type\"\n\tErrorUnsupportedResponseType = \"unsupported_response_type\"\n)\n\ntype Error struct {\n\tType string `json:\"error\"`\n\tState string `json:\"state,omitempty\"`\n}\n\nfunc (e *Error) Error() string {\n\treturn e.Type\n}\n\nfunc NewError(typ string) *Error {\n\treturn &Error{Type: typ}\n}\n\n\n\nfunc unmarshalError(b []byte) error ", "output": "{\n\tvar oerr Error\n\terr := json.Unmarshal(b, &oerr)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unrecognized error: %s\", string(b))\n\t}\n\treturn &oerr\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n)\n\ntype Command struct {\n\tinput string\n}\n\nfunc (c *Command) Run() {\n\tname, args := c.parse(c.input)\n\n\tcmd := exec.Command(name, args...)\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\n\terr := cmd.Run()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\n\n\nfunc (c *Command) parse(input string) (string, []string) ", "output": "{\n\tinputs := strings.Split(input, \" \")\n\tname := inputs[0]\n\targs := inputs[1:]\n\n\treturn name, args\n}"} {"input": "package fs\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\nvar execExts map[string]bool\n\nfunc init() {\n\tpathext := filepath.SplitList(os.Getenv(\"PATHEXT\"))\n\texecExts = make(map[string]bool, len(pathext))\n\tfor _, ext := range pathext {\n\t\texecExts[strings.ToLower(ext)] = true\n\t}\n}\n\n\n\n\n\nfunc (e basicFileInfo) Mode() FileMode {\n\tm := e.FileInfo.Mode()\n\tif m&os.ModeSymlink != 0 && e.Size() > 0 {\n\t\tm &^= os.ModeSymlink\n\t}\n\tif isWindowsExecutable(e.Name()) {\n\t\tm |= 0111\n\t}\n\tm &^= 0022\n\treturn FileMode(m)\n}\n\nfunc (e basicFileInfo) Owner() int {\n\treturn -1\n}\n\nfunc (e basicFileInfo) Group() int {\n\treturn -1\n}\n\n\n\nfunc (e *basicFileInfo) osFileInfo() os.FileInfo {\n\tfi := e.FileInfo\n\tif fi, ok := fi.(*dirJunctFileInfo); ok {\n\t\treturn fi.FileInfo\n\t}\n\treturn fi\n}\n\nfunc isWindowsExecutable(path string) bool ", "output": "{\n\treturn execExts[strings.ToLower(filepath.Ext(path))]\n}"} {"input": "package app\n\nimport (\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com/urfave/cli\"\n)\n\n\n\n\n\nfunc GenerateSubcommandsUsage(cmd cli.Command, prefix string) (commandsUsage []string) {\n\tif cmd.Subcommands == nil || len(cmd.Subcommands) == 0 {\n\t\tfullName := prefix + cmd.Name\n\n\t\treturn []string{fullName + \": \" + cmd.Usage}\n\t}\n\tcommandsUsage = make([]string, 0, len(cmd.Subcommands))\n\tfor _, subcmd := range cmd.Subcommands {\n\t\tcommandsUsage = append(commandsUsage, GenerateSubcommandsUsage(subcmd, prefix+cmd.Name+\" \")...)\n\t}\n\treturn\n}\n\nfunc GenerateCommandsHelp(cmds []cli.Command) string ", "output": "{\n\tcommandsUsage := make([]string, 0, len(cmds))\n\tfor _, cmd := range cmds {\n\t\tcommandsUsage = append(commandsUsage, GenerateSubcommandsUsage(cmd, \"\")...)\n\t}\n\n\tsort.Strings(commandsUsage)\n\n\treturn \" \" + strings.Join(commandsUsage, \"\\r\\n \")\n}"} {"input": "package models\n\nimport (\n\t\"github.com/macococo/go-gamereviews/utils\"\n)\n\ntype User struct {\n\tId int\n\tName string\n\tType int\n\tModel\n}\n\ntype UserManager struct {\n}\n\n\n\nfunc (this *UserManager) AddTable() {\n\tDbMap.AddTableWithName(User{}, this.TableName()).SetKeys(true, \"Id\")\n}\n\nfunc (this *UserManager) Count(t int) int64 {\n\tcount, err := DbMap.SelectInt(\"SELECT count(*) FROM \"+this.TableName()+\" WHERE type = ?\", t)\n\tutils.HandleError(err)\n\n\treturn count\n}\n\nfunc (this *UserManager) Find(t int, pagination *Pagination) []*User {\n\tvar users []*User\n\t_, err := DbMap.Select(&users, \"SELECT * FROM \"+this.TableName()+\" WHERE type = ? LIMIT ?, ?\", t, (pagination.Page-1)*pagination.Length, pagination.Length)\n\tutils.HandleError(err)\n\n\treturn users\n}\n\nfunc (this *UserManager) Create(user *User) *User {\n\tutils.HandleError(DbMap.Insert(user))\n\treturn user\n}\n\nfunc (this *UserManager) TableName() string ", "output": "{\n\treturn \"t_user\"\n}"} {"input": "package protocol\n\nimport \"sync\"\n\nvar msgPool = sync.Pool{\n\tNew: func() interface{} {\n\t\theader := Header([12]byte{})\n\t\theader[0] = magicNumber\n\n\t\treturn &Message{\n\t\t\tHeader: &header,\n\t\t}\n\t},\n}\n\n\nfunc GetPooledMsg() *Message {\n\treturn msgPool.Get().(*Message)\n}\n\n\n\n\nvar poolUint32Data = sync.Pool{\n\tNew: func() interface{} {\n\t\tdata := make([]byte, 4)\n\t\treturn &data\n\t},\n}\n\nfunc FreeMsg(msg *Message) ", "output": "{\n\tif msg != nil {\n\t\tmsg.Reset()\n\t\tmsgPool.Put(msg)\n\t}\n}"} {"input": "package state\n\nimport (\n\tabci \"github.com/tendermint/tendermint/abci/types\"\n\t\"github.com/tendermint/tendermint/types\"\n)\n\n\n\n\n\nfunc ValidateValidatorUpdates(abciUpdates []abci.ValidatorUpdate, params types.ValidatorParams) error ", "output": "{\n\treturn validateValidatorUpdates(abciUpdates, params)\n}"} {"input": "package cluster\n\nimport (\n\t\"encoding/binary\"\n\t\"os\"\n)\n\ntype stateFile struct {\n\tHandle *os.File\n\tName string\n\tCount int32\n\tTimestamp int64\n}\n\nfunc newStateFile(name string) *stateFile {\n\tsf := new(stateFile)\n\tsf.Name = name\n\treturn sf\n}\n\n\n\nfunc (sf *stateFile) write() error {\n\terr := sf.Handle.Truncate(0)\n\tsf.Handle.Seek(0, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = binary.Write(sf.Handle, binary.LittleEndian, sf.Count)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = binary.Write(sf.Handle, binary.LittleEndian, sf.Timestamp)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (sf *stateFile) read() error {\n\tsf.Handle.Seek(0, 0)\n\terr := binary.Read(sf.Handle, binary.LittleEndian, &sf.Count)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = binary.Read(sf.Handle, binary.LittleEndian, &sf.Timestamp)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (sf *stateFile) access() error ", "output": "{\n\tvar err error\n\tsf.Handle, err = os.OpenFile(sf.Name, os.O_RDWR|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package common\n\nimport (\n\t\"fmt\"\n\t\"github.com/vv1133/vvblog/models\"\n\t\"gopkg.in/mgo.v2/bson\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc filterHtml(str string) string {\n\tre, _ := regexp.Compile(\"\\\\<[\\\\S\\\\s]+?\\\\>\")\n\tstr = re.ReplaceAllStringFunc(str, strings.ToLower)\n\n\tre, _ = regexp.Compile(\"\\\\\")\n\tstr = re.ReplaceAllString(str, \"\")\n\n\tre, _ = regexp.Compile(\"\\\\\")\n\tstr = re.ReplaceAllString(str, \"\")\n\n\tre, _ = regexp.Compile(\"\\\\<[\\\\S\\\\s]+?\\\\>\")\n\tstr = re.ReplaceAllString(str, \"\\n\")\n\n\tre, _ = regexp.Compile(\"\\\\S\\\\s{2,}\")\n\tstr = re.ReplaceAllString(str, \"\\n\")\n\n\treturn str\n}\n\nfunc Preview(str string, length int) string {\n\tstr = filterHtml(str)\n\trs := []rune(str)\n\trl := len(rs)\n\n\tif length > rl {\n\t\tstr = string(rs[0:rl])\n\t} else {\n\t\tstr = string(rs[0:length]) + \"...\"\n\t}\n\n\treturn strings.Replace(str, \"\\n\", \"\", -1)\n}\n\nfunc GetId(id bson.ObjectId) string {\n\treturn id.Hex()\n}\n\nfunc GetTagSlug(caption string) string {\n\tvar tag models.BlogTag\n\n\tmodels.GetOneByQuery(models.DbTag, bson.M{\"caption\": caption}, &tag)\n\n\treturn tag.Slug\n}\n\n\n\nfunc LoadTimes(startTime time.Time) string {\n\treturn fmt.Sprintf(\"%dms\", time.Now().Sub(startTime)/1000000)\n}\n\nfunc GetSlug(str string, isslug bool) string ", "output": "{\n\tretstr := \"\"\n\n\tfor _, i := range str {\n\t\tinside_code := i\n\t\tif inside_code == 12288 {\n\t\t\tinside_code = 32\n\t\t} else {\n\t\t\tinside_code -= 65248\n\t\t}\n\t\tif inside_code < 32 || inside_code > 126 {\n\t\t\tretstr += string(i)\n\t\t} else {\n\t\t\tretstr += string(inside_code)\n\t\t}\n\t}\n\n\treg := regexp.MustCompile(`[\\pP]+`)\n\tstr = reg.ReplaceAllString(retstr, \"\")\n\tstr = strings.TrimSpace(str)\n\treg = regexp.MustCompile(`[\\sS]+`)\n\tstr = reg.ReplaceAllString(retstr, \"\")\n\tstr = strings.Replace(str, \" \", \"-\", -1)\n\n\treturn str\n}"} {"input": "package local\n\nimport (\n\t\"context\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/grafana/loki/pkg/storage/chunk\"\n)\n\ntype TableClient struct {\n\tdirectory string\n}\n\n\nfunc NewTableClient(directory string) (chunk.TableClient, error) {\n\treturn &TableClient{directory: directory}, nil\n}\n\nfunc (c *TableClient) ListTables(ctx context.Context) ([]string, error) {\n\tboltDbFiles := []string{}\n\terr := filepath.Walk(c.directory, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !info.IsDir() {\n\t\t\tboltDbFiles = append(boltDbFiles, info.Name())\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn boltDbFiles, nil\n}\n\nfunc (c *TableClient) CreateTable(ctx context.Context, desc chunk.TableDesc) error {\n\tfile, err := os.OpenFile(filepath.Join(c.directory, desc.Name), os.O_CREATE|os.O_RDONLY, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn file.Close()\n}\n\n\n\nfunc (c *TableClient) DescribeTable(ctx context.Context, name string) (desc chunk.TableDesc, isActive bool, err error) {\n\treturn chunk.TableDesc{\n\t\tName: name,\n\t}, true, nil\n}\n\nfunc (c *TableClient) UpdateTable(ctx context.Context, current, expected chunk.TableDesc) error {\n\treturn nil\n}\n\nfunc (*TableClient) Stop() {}\n\nfunc (c *TableClient) DeleteTable(ctx context.Context, name string) error ", "output": "{\n\treturn os.Remove(filepath.Join(c.directory, name))\n}"} {"input": "package task\n\nimport (\n\t\"fmt\"\n)\n\n\ntype Event struct {\n\tTask *Task\n\tPayload interface{}\n}\n\nfunc (e *Event) String() string {\n\treturn fmt.Sprintf(\"%T{from %v: %v}\", e, e.Task, e.Payload)\n}\n\n\n\ntype Ended struct {\n\tError error\n}\n\nfunc (p *Ended) String() string {\n\treturn fmt.Sprintf(\"%T{%v}\", p, p.Error)\n}\n\n\ntype Output struct {\n\tChunk string\n}\n\n\n\nfunc (p *Output) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%T{%v}\", p, p.Chunk)\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n)\n\n\nfunc test() {\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}()\n\n\terr := initConfig()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}\n\nfunc main() {\n\tfor {\n\t\ttest()\n\t\tfmt.Println(\"hello\")\n\t\ttime.Sleep(time.Second)\n\t}\n\n}\n\nfunc initConfig() (err error) ", "output": "{\n\treturn errors.New(\"init config faild\")\n}"} {"input": "package fake\n\nimport (\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apimachinery/pkg/watch\"\n\t\"k8s.io/client-go/discovery\"\n\tfakediscovery \"k8s.io/client-go/discovery/fake\"\n\t\"k8s.io/client-go/testing\"\n\tclientset \"k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset\"\n\tapiregistrationv1beta1 \"k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/typed/apiregistration/v1beta1\"\n\tfakeapiregistrationv1beta1 \"k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/typed/apiregistration/v1beta1/fake\"\n)\n\n\n\n\n\n\n\n\n\n\ntype Clientset struct {\n\ttesting.Fake\n\tdiscovery *fakediscovery.FakeDiscovery\n}\n\nfunc (c *Clientset) Discovery() discovery.DiscoveryInterface {\n\treturn c.discovery\n}\n\nvar _ clientset.Interface = &Clientset{}\n\n\nfunc (c *Clientset) ApiregistrationV1beta1() apiregistrationv1beta1.ApiregistrationV1beta1Interface {\n\treturn &fakeapiregistrationv1beta1.FakeApiregistrationV1beta1{Fake: &c.Fake}\n}\n\n\nfunc (c *Clientset) Apiregistration() apiregistrationv1beta1.ApiregistrationV1beta1Interface {\n\treturn &fakeapiregistrationv1beta1.FakeApiregistrationV1beta1{Fake: &c.Fake}\n}\n\nfunc NewSimpleClientset(objects ...runtime.Object) *Clientset ", "output": "{\n\to := testing.NewObjectTracker(scheme, codecs.UniversalDecoder())\n\tfor _, obj := range objects {\n\t\tif err := o.Add(obj); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tfakePtr := testing.Fake{}\n\tfakePtr.AddReactor(\"*\", \"*\", testing.ObjectReaction(o))\n\tfakePtr.AddWatchReactor(\"*\", func(action testing.Action) (handled bool, ret watch.Interface, err error) {\n\t\tgvr := action.GetResource()\n\t\tns := action.GetNamespace()\n\t\twatch, err := o.Watch(gvr, ns)\n\t\tif err != nil {\n\t\t\treturn false, nil, err\n\t\t}\n\t\treturn true, watch, nil\n\t})\n\n\treturn &Clientset{fakePtr, &fakediscovery.FakeDiscovery{Fake: &fakePtr}}\n}"} {"input": "package models\n\nimport \"fmt\"\n\ntype TaskManager struct {\n\ttasks []*Task\n\tlastID int64\n}\n\nfunc NewTaskManager() *TaskManager {\n\treturn &TaskManager{}\n}\n\n\n\nfunc (m *TaskManager) Add(task *Task) error {\n\tif task.Id == 0 {\n\t\tm.lastID++\n\t\ttask.Id = m.lastID\n\t\tm.tasks = append(m.tasks, task.clone())\n\t\treturn nil\n\t}\n\n\t_, found := m.Find(task.Id)\n\tif found {\n\t\tm.tasks[task.Id-1] = task\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"unknown task\")\n}\n\nfunc (m *TaskManager) Find(id int64) (*Task, bool) {\n\tfor _, t := range m.tasks {\n\t\tif t.Id == id {\n\t\t\treturn t, true\n\t\t}\n\t}\n\treturn nil, false\n}\n\nfunc (m *TaskManager) Tasks() []*Task ", "output": "{\n\treturn m.tasks\n}"} {"input": "package dev\n\nimport \"fmt\"\n\n\n\ntype Configuration struct {\n\tid uint32\n\tnodes []*Node\n\tn int\n\tmgr *Manager\n\tqspec QuorumSpec\n\terrs chan CallGRPCError\n}\n\n\n\nfunc (c *Configuration) SubError() <-chan CallGRPCError {\n\treturn c.errs\n}\n\n\nfunc (c *Configuration) ID() uint32 {\n\treturn c.id\n}\n\n\n\n\nfunc (c *Configuration) NodeIDs() []uint32 {\n\tids := make([]uint32, len(c.nodes))\n\tfor i, node := range c.nodes {\n\t\tids[i] = node.ID()\n\t}\n\treturn ids\n}\n\n\n\nfunc (c *Configuration) Nodes() []*Node {\n\treturn c.nodes\n}\n\n\n\n\nfunc (c *Configuration) String() string {\n\treturn fmt.Sprintf(\"configuration %d\", c.id)\n}\n\nfunc (c *Configuration) tstring() string {\n\treturn fmt.Sprintf(\"config-%d\", c.id)\n}\n\n\n\nfunc Equal(a, b *Configuration) bool { return a.id == b.id }\n\n\n\n\nfunc NewTestConfiguration(q, n int) *Configuration {\n\treturn &Configuration{\n\t\tnodes: make([]*Node, n),\n\t}\n}\n\nfunc (c *Configuration) Size() int ", "output": "{\n\treturn c.n\n}"} {"input": "package label\n\n\n\n\nfunc InitLabels(mcsdir string, options []string) (string, string, error) {\n\treturn \"\", \"\", nil\n}\n\nfunc FormatMountLabel(src string, mountLabel string) string {\n\treturn src\n}\n\nfunc SetProcessLabel(processLabel string) error {\n\treturn nil\n}\n\nfunc SetFileLabel(path string, fileLabel string) error {\n\treturn nil\n}\n\nfunc SetFileCreateLabel(fileLabel string) error {\n\treturn nil\n}\n\nfunc Relabel(path string, fileLabel string, relabel string) error {\n\treturn nil\n}\n\nfunc GetPidLabel(pid int) (string, error) {\n\treturn \"\", nil\n}\n\nfunc Init() {\n}\n\n\n\nfunc UnreserveLabel(label string) error {\n\treturn nil\n}\n\n\n\nfunc DupSecOpt(src string) []string {\n\treturn nil\n}\n\n\n\nfunc DisableSecOpt() []string {\n\treturn nil\n}\n\nfunc ReserveLabel(label string) error ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n)\n\n\n\nvar primeSet = func() map[int]bool {\n\tprimeSet := make(map[int]bool)\n\tfor i := 3; i < 1000000; i += 2 {\n\t\tif isPrime(i) {\n\t\t\tprimeSet[i] = true\n\t\t}\n\t}\n\treturn primeSet\n}()\n\nfunc solve(out io.Writer, n int) {\n\tfor i := 3; i <= n/2; i += 2 {\n\t\tif primeSet[i] && primeSet[n-i] {\n\t\t\tfmt.Fprintf(out, \"%d = %d + %d\\n\", n, i, n-i)\n\t\t\treturn\n\t\t}\n\t}\n\tfmt.Fprintln(out, \"Goldbach's conjecture is wrong.\")\n}\n\nfunc main() {\n\tin, _ := os.Open(\"543.in\")\n\tdefer in.Close()\n\tout, _ := os.Create(\"543.out\")\n\tdefer out.Close()\n\n\tvar n int\n\tfor {\n\t\tif fmt.Fscanf(in, \"%d\", &n); n == 0 {\n\t\t\tbreak\n\t\t}\n\t\tsolve(out, n)\n\t}\n}\n\nfunc isPrime(n int) bool ", "output": "{\n\tfor i := 3; i*i <= n; i += 2 {\n\t\tif n%i == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}"} {"input": "package v1\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n\t\"k8s.io/client-go/pkg/apis/extensions/v1beta1\"\n)\n\nconst (\n\tIotDaemonSetKind = \"IotDaemonSet\"\n\tIotDaemonSetType = \"iotdaemonsets\"\n)\n\ntype IotDaemonSet struct {\n\tmetav1.TypeMeta `json:\",inline\"`\n\tMetadata metav1.ObjectMeta `json:\"metadata,omitempty\"`\n\tSpec v1beta1.DaemonSetSpec `json:\"spec,omitempty\"`\n\tStatus v1beta1.DaemonSetStatus `json:\"status,omitempty\"`\n}\n\ntype IotDaemonSetList struct {\n\tmetav1.TypeMeta `json:\",inline\"`\n\tMetadata metav1.ListMeta `json:\"metadata,omitempty\"`\n\tItems []IotDaemonSet `json:\"items\"`\n}\n\nfunc (iotDaemonSet *IotDaemonSet) GetObjectKind() schema.ObjectKind {\n\treturn &iotDaemonSet.TypeMeta\n}\n\nfunc (iotDaemonSet *IotDaemonSet) GetObjectMeta() *metav1.ObjectMeta {\n\treturn &iotDaemonSet.Metadata\n}\n\nfunc (iotDaemonSetList *IotDaemonSetList) GetObjectKind() schema.ObjectKind {\n\treturn &iotDaemonSetList.TypeMeta\n}\n\n\n\nfunc (iotDaemonSetList *IotDaemonSetList) GetListMeta() metav1.List ", "output": "{\n\treturn &iotDaemonSetList.Metadata\n}"} {"input": "package main\n\nimport (\n\t\"container/list\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n\nconst SymbolBorderLeft = \"[\"\nconst SymbolBorderRight = \"]\"\nconst SymbolItemHead = SymbolBorderLeft + \"HEAD\" + SymbolBorderRight\nconst SymbolItemTail = SymbolBorderLeft + \"TAIL\" + SymbolBorderRight\nconst SymbolChainLink = \"=\"\n\nconst FormatA = \"%v\"\n\n\n\n\nfunc listToSnake(aList list.List) string ", "output": "{\n\n\tvar item *list.Element\n\tvar itemStr string\n\tvar output strings.Builder\n\tvar tmpStr string\n\n\toutput.WriteString(SymbolItemHead)\n\n\tfor item = aList.Front(); item != nil; item = item.Next() {\n\n\t\titemStr = fmt.Sprintf(FormatA, item.Value)\n\t\ttmpStr = SymbolChainLink +\n\t\t\tSymbolBorderLeft +\n\t\t\titemStr +\n\t\t\tSymbolBorderRight +\n\t\t\tSymbolChainLink\n\t\toutput.WriteString(tmpStr)\n\t}\n\n\toutput.WriteString(SymbolItemTail)\n\n\treturn output.String()\n}"} {"input": "package framework\n\nimport \"github.com/onsi/gomega\"\n\n\nfunc ExpectEqual(actual interface{}, extra interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.Equal(extra), explain...)\n}\n\n\nfunc ExpectNotEqual(actual interface{}, extra interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).NotTo(gomega.Equal(extra), explain...)\n}\n\n\n\n\n\nfunc ExpectNoError(err error, explain ...interface{}) {\n\tExpectNoErrorWithOffset(1, err, explain...)\n}\n\n\n\nfunc ExpectNoErrorWithOffset(offset int, err error, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1+offset, err).NotTo(gomega.HaveOccurred(), explain...)\n}\n\n\nfunc ExpectConsistOf(actual interface{}, extra interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.ConsistOf(extra), explain...)\n}\n\n\nfunc ExpectHaveKey(actual interface{}, key interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.HaveKey(key), explain...)\n}\n\n\nfunc ExpectEmpty(actual interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.BeEmpty(), explain...)\n}\n\nfunc ExpectError(err error, explain ...interface{}) ", "output": "{\n\tgomega.ExpectWithOffset(1, err).To(gomega.HaveOccurred(), explain...)\n}"} {"input": "package routing\n\nimport \"net/http\"\n\n\nfunc Method(method string, handler http.Handler) Matcher {\n\treturn func(remainingPath string, resp http.ResponseWriter, req *http.Request) bool {\n\t\tif req.Method == method {\n\t\t\thandler.ServeHTTP(resp, req)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n}\n\n\nfunc GET(handler http.Handler) Matcher {\n\treturn Method(\"GET\", handler)\n}\n\n\nfunc GETFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn GET(http.HandlerFunc(handler))\n}\n\n\nfunc POST(handler http.Handler) Matcher {\n\treturn Method(\"POST\", handler)\n}\n\n\nfunc POSTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn POST(http.HandlerFunc(handler))\n}\n\n\nfunc PUT(handler http.Handler) Matcher {\n\treturn Method(\"PUT\", handler)\n}\n\n\nfunc PUTFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn PUT(http.HandlerFunc(handler))\n}\n\n\nfunc PATCH(handler http.Handler) Matcher {\n\treturn Method(\"PATCH\", handler)\n}\n\n\nfunc PATCHFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn PATCH(http.HandlerFunc(handler))\n}\n\n\nfunc DELETE(handler http.Handler) Matcher {\n\treturn Method(\"DELETE\", handler)\n}\n\n\nfunc DELETEFunc(handler func(http.ResponseWriter, *http.Request)) Matcher {\n\treturn DELETE(http.HandlerFunc(handler))\n}\n\n\n\n\n\nfunc MethodNotAllowed(remainingPath string, resp http.ResponseWriter, req *http.Request) bool ", "output": "{\n\tresp.WriteHeader(405)\n\treturn true\n}"} {"input": "package repomodel\n\nimport (\n\t\"github.com/kopia/kopia/repo/content\"\n\t\"github.com/kopia/kopia/repo/manifest\"\n)\n\n\ntype RepositorySession struct {\n\tOpenRepo *OpenRepository\n\n\tWrittenContents ContentSet\n\tWrittenManifests ManifestSet\n}\n\n\n\n\n\nfunc (s *RepositorySession) WriteManifest(mid manifest.ID) {\n\ts.WrittenManifests.Add(mid)\n}\n\n\nfunc (s *RepositorySession) Refresh() {\n\ts.OpenRepo.Refresh()\n}\n\n\n\nfunc (s *RepositorySession) Flush(wc *ContentSet, wm *ManifestSet) {\n\ts.OpenRepo.mu.Lock()\n\tdefer s.OpenRepo.mu.Unlock()\n\n\ts.OpenRepo.Contents.Add(wc.ids...)\n\ts.OpenRepo.Manifests.Add(wm.ids...)\n\n\ts.OpenRepo.RepoData.Contents.Add(wc.ids...)\n\ts.OpenRepo.RepoData.Manifests.Add(wm.ids...)\n\n\ts.WrittenContents.RemoveAll(wc.ids...)\n\ts.WrittenManifests.RemoveAll(wm.ids...)\n}\n\nfunc (s *RepositorySession) WriteContent(cid content.ID) ", "output": "{\n\ts.WrittenContents.Add(cid)\n}"} {"input": "package fitsio\n\nimport \"io\"\n\ntype Reader struct {\n\tr io.Reader\n}\n\n\n\nfunc NewReader(r io.Reader) *Reader ", "output": "{\n\treturn &Reader{\n\t\tr: r,\n\t}\n}"} {"input": "package versioned\n\nimport (\n\t\"strconv\"\n)\n\n\ntype Version int64\n\n\n\n\nfunc ParseVersion(s string) Version {\n\ti, _ := strconv.ParseInt(s, 10, 64)\n\treturn Version(i)\n}\n\n\ntype Object struct {\n\tData interface{}\n\tVersion Version\n}\n\n\n\n\n\n\n\nfunc (o *Object) CompareVersion(other Object) int64 ", "output": "{\n\treturn int64(o.Version) - int64(other.Version)\n}"} {"input": "package pgjson\n\nimport (\n\t\"io\"\n)\n\nvar provider Provider = StdProvider{}\n\n\n\ntype Provider interface {\n\tMarshal(v interface{}) ([]byte, error)\n\tUnmarshal(data []byte, v interface{}) error\n\tNewEncoder(w io.Writer) Encoder\n\tNewDecoder(r io.Reader) Decoder\n}\n\ntype Decoder interface {\n\tDecode(v interface{}) error\n\tUseNumber()\n}\n\ntype Encoder interface {\n\tEncode(v interface{}) error\n}\n\nfunc Marshal(v interface{}) ([]byte, error) {\n\treturn provider.Marshal(v)\n}\n\nfunc Unmarshal(data []byte, v interface{}) error {\n\treturn provider.Unmarshal(data, v)\n}\n\nfunc NewEncoder(w io.Writer) Encoder {\n\treturn provider.NewEncoder(w)\n}\n\nfunc NewDecoder(r io.Reader) Decoder {\n\treturn provider.NewDecoder(r)\n}\n\nfunc SetProvider(p Provider) ", "output": "{\n\tprovider = p\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n)\n\n\n\n\nvar wait sync.WaitGroup\n\n\n\nfunc upper(ch chan string) {\n\tfor {\n\t\tword := <-ch\n\n\t\tif word == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tfmt.Println(strings.ToUpper(word))\n\t}\n}\n\nfunc add(ch chan string, words []string) {\n\tfor _, word := range words {\n\t\tch <- word\n\t}\n}\n\nfunc main() {\n\twords := []string{\"test1\", \"test2\", \"test3\"}\n\n\tfmt.Println(\"Use go routines to capitalize our words.\")\n\twait.Add(len(words))\n\n\tfor i := 0; i < len(words); i++ {\n\t\tgo capitalize(words[i])\n\t}\n\n\twait.Wait()\n\tfmt.Println()\n\n\n\n\tfmt.Println(\"Use channels to upper case our words.\")\n\n\tword_chan := make(chan string)\n\n\n\tgo upper(word_chan)\n\n\tadd(word_chan, words)\n\n\tclose(word_chan)\n}\n\nfunc capitalize(word string) ", "output": "{\n\tdefer wait.Done()\n\tfmt.Println(strings.Title(word))\n}"} {"input": "package simulation\n\nimport \"encoding/json\"\n\n\ntype TrainType struct {\n\tcode string\n\tDescription string `json:\"description\"`\n\tEmergBraking float64 `json:\"emergBraking\"`\n\tLength float64 `json:\"length\"`\n\tMaxSpeed float64 `json:\"maxSpeed\"`\n\tStdAccel float64 `json:\"stdAccel\"`\n\tStdBraking float64 `json:\"stdBraking\"`\n\tElementsStr []string `json:\"elements\"`\n\n\tsimulation *Simulation\n}\n\n\nfunc (tt *TrainType) ID() string {\n\treturn tt.code\n}\n\n\nfunc (tt *TrainType) setSimulation(sim *Simulation) {\n\ttt.simulation = sim\n}\n\n\nfunc (tt *TrainType) initialize(code string) {\n\ttt.code = code\n}\n\n\n\n\n\nfunc (tt *TrainType) MarshalJSON() ([]byte, error) {\n\ttype auxTT struct {\n\t\tID string `json:\"id\"`\n\t\tDescription string `json:\"description\"`\n\t\tEmergBraking float64 `json:\"emergBraking\"`\n\t\tLength float64 `json:\"length\"`\n\t\tMaxSpeed float64 `json:\"maxSpeed\"`\n\t\tStdAccel float64 `json:\"stdAccel\"`\n\t\tStdBraking float64 `json:\"stdBraking\"`\n\t\tElementsStr []string `json:\"elements\"`\n\t}\n\tatt := auxTT{\n\t\tID: tt.ID(),\n\t\tDescription: tt.Description,\n\t\tEmergBraking: tt.EmergBraking,\n\t\tLength: tt.Length,\n\t\tMaxSpeed: tt.MaxSpeed,\n\t\tStdAccel: tt.StdAccel,\n\t\tStdBraking: tt.StdBraking,\n\t\tElementsStr: tt.ElementsStr,\n\t}\n\treturn json.Marshal(att)\n}\n\nfunc (tt *TrainType) Elements() []*TrainType ", "output": "{\n\tres := make([]*TrainType, 0)\n\tfor _, code := range tt.ElementsStr {\n\t\tres = append(res, tt.simulation.TrainTypes[code])\n\t}\n\treturn res\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/ChuckHa/grout\"\n\t\"net/http\"\n)\n\ntype Blog struct {\n}\n\nfunc (b *Blog) PostById(id string) string {\n\treturn \"a blog post\"\n}\n\nfunc BlogByName(name string) *Blog {\n\treturn &Blog{}\n}\n\n\n\nfunc main() {\n\tmux := grout.NewRouteMux()\n\tmux.Route(`/blogs/(?P[a-z][a-z_-]+[a-z])/(?P[0-9]+)`, blogsHandler)\n\tfmt.Println(\"Listening on port 8080\")\n\thttp.ListenAndServe(\":8080\", mux)\n}\n\nfunc blogsHandler(w http.ResponseWriter, r *http.Request, data map[string]string) ", "output": "{\n\ttheBlog := BlogByName(data[\"name\"])\n\tpost := theBlog.PostById(data[\"othername\"])\n\tfmt.Fprintf(w, post)\n}"} {"input": "package recovery\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\n\t\"github.com/containous/traefik/middlewares\"\n\t\"github.com/sirupsen/logrus\"\n)\n\nconst (\n\ttypeName = \"Recovery\"\n)\n\ntype recovery struct {\n\tnext http.Handler\n\tname string\n}\n\n\n\n\nfunc (re *recovery) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\tdefer recoverFunc(middlewares.GetLogger(req.Context(), re.name, typeName), rw)\n\tre.next.ServeHTTP(rw, req)\n}\n\nfunc recoverFunc(logger logrus.FieldLogger, rw http.ResponseWriter) {\n\tif err := recover(); err != nil {\n\t\tlogger.Errorf(\"Recovered from panic in http handler: %+v\", err)\n\t\thttp.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t}\n}\n\nfunc New(ctx context.Context, next http.Handler, name string) (http.Handler, error) ", "output": "{\n\tmiddlewares.GetLogger(ctx, name, typeName).Debug(\"Creating middleware\")\n\n\treturn &recovery{\n\t\tnext: next,\n\t\tname: name,\n\t}, nil\n}"} {"input": "package debug\n\n\n\nfunc SavePanicTrace() ", "output": "{\n\tr := recover()\n\tif r == nil {\n\t\treturn\n\t}\n\tpanic(\"dumper \" + r.(string))\n}"} {"input": "package producer\n\nimport (\n\t\"fmt\"\n\t\"github.com/elodina/siesta\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype Metadata struct {\n\tconnector siesta.Connector\n\tmetadataExpire time.Duration\n\tcache map[string]*metadataEntry\n\tmetadataLock sync.RWMutex\n}\n\nfunc NewMetadata(connector siesta.Connector, metadataExpire time.Duration) *Metadata {\n\treturn &Metadata{\n\t\tconnector: connector,\n\t\tmetadataExpire: metadataExpire,\n\t\tcache: make(map[string]*metadataEntry),\n\t}\n}\n\n\n\nfunc (tmc *Metadata) Refresh(topics []string) error {\n\ttmc.metadataLock.Lock()\n\tdefer tmc.metadataLock.Unlock()\n\tLogger.Info(\"Refreshing metadata for topics %v\", topics)\n\n\ttopicMetadataResponse, err := tmc.connector.GetTopicMetadata(topics)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, topicMetadata := range topicMetadataResponse.TopicsMetadata {\n\t\tpartitions := make([]int32, 0)\n\t\tfor _, partitionMetadata := range topicMetadata.PartitionsMetadata {\n\t\t\tpartitions = append(partitions, partitionMetadata.PartitionID)\n\t\t}\n\t\ttmc.cache[topicMetadata.Topic] = newMetadataEntry(partitions)\n\t\tLogger.Debug(\"Received metadata: partitions %v for topic %s\", partitions, topicMetadata.Topic)\n\t}\n\n\treturn nil\n}\n\ntype metadataEntry struct {\n\tpartitions []int32\n\ttimestamp time.Time\n}\n\nfunc newMetadataEntry(partitions []int32) *metadataEntry {\n\treturn &metadataEntry{\n\t\tpartitions: partitions,\n\t\ttimestamp: time.Now(),\n\t}\n}\n\nfunc (tmc *Metadata) Get(topic string) ([]int32, error) ", "output": "{\n\ttmc.metadataLock.RLock()\n\tcache := tmc.cache[topic]\n\ttmc.metadataLock.RUnlock()\n\n\tif cache == nil || cache.timestamp.Add(tmc.metadataExpire).Before(time.Now()) {\n\t\terr := tmc.Refresh([]string{topic})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttmc.metadataLock.RLock()\n\t\tcache = tmc.cache[topic]\n\t\ttmc.metadataLock.RUnlock()\n\n\t\tif cache != nil {\n\t\t\treturn cache.partitions, nil\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"Could not get topic metadata for topic %s\", topic)\n\t}\n\n\treturn cache.partitions, nil\n}"} {"input": "package main\n\nimport \"fmt\"\n\ntype T struct { i int }\n\n\n\nfunc (t *T) Bar () {\n fmt.Println (t.i)\n}\n\nfunc main () {\n fmt.Println (\"Shall we?\")\n var t T\n t.Foo ()\n var pt = new (T)\n pt.Bar ()\n}\n\nfunc (t T) Foo () ", "output": "{\n fmt.Println (t.i)\n}"} {"input": "package logger\n\nimport (\n\t\"io\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\nvar _ Logger = Logrus{}\nvar _ FieldLogger = Logrus{}\nvar _ Outable = Logrus{}\n\n\ntype Logrus struct {\n\tlogrus.FieldLogger\n}\n\n\n\n\n\n\nfunc (l Logrus) WithField(s string, i interface{}) FieldLogger {\n\treturn Logrus{l.FieldLogger.WithField(s, i)}\n}\n\n\nfunc (l Logrus) WithFields(m map[string]interface{}) FieldLogger {\n\treturn Logrus{l.FieldLogger.WithFields(m)}\n}\n\nfunc (l Logrus) SetOutput(w io.Writer) ", "output": "{\n\tif lg, ok := l.FieldLogger.(Outable); ok {\n\t\tlg.SetOutput(w)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/TykTechnologies/tyk/apidef\"\n)\n\n\ntype TransformMethod struct {\n\t*BaseMiddleware\n}\n\nfunc (t *TransformMethod) Name() string {\n\treturn \"TransformMethod\"\n}\n\n\n\n\nfunc (t *TransformMethod) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int) {\n\t_, versionPaths, _, _ := t.Spec.Version(r)\n\tfound, meta := t.Spec.CheckSpecMatchesStatus(r, versionPaths, MethodTransformed)\n\tif !found {\n\t\treturn nil, 200\n\t}\n\tmmeta := meta.(*apidef.MethodTransformMeta)\n\tswitch strings.ToUpper(mmeta.ToMethod) {\n\tcase \"GET\":\n\t\tr.Method = \"GET\"\n\tcase \"POST\":\n\t\tr.Method = \"POST\"\n\tcase \"PUT\":\n\t\tr.Method = \"PUT\"\n\tcase \"DELETE\":\n\t\tr.Method = \"DELETE\"\n\tcase \"OPTIONS\":\n\t\tr.Method = \"OPTIONS\"\n\tcase \"PATCH\":\n\t\tr.Method = \"PATCH\"\n\tdefault:\n\t\treturn errors.New(\"Method not allowed\"), 405\n\t}\n\treturn nil, 200\n}\n\nfunc (t *TransformMethod) IsEnabledForSpec() bool ", "output": "{\n\tfor _, version := range t.Spec.VersionData.Versions {\n\t\tif len(version.ExtendedPaths.MethodTransforms) > 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package main\n\nimport (\n\t\"strings\"\n\n\t\"github.com/docker/docker/pkg/integration/checker\"\n\t\"github.com/go-check/check\"\n)\n\n\n\nfunc (s *DockerSuite) TestExperimentalVersionFalse(c *check.C) {\n\ttestRequires(c, NotExperimentalDaemon)\n\n\tout, _ := dockerCmd(c, \"version\")\n\tfor _, line := range strings.Split(out, \"\\n\") {\n\t\tif strings.HasPrefix(strings.TrimSpace(line), \"Experimental:\") {\n\t\t\tc.Assert(line, checker.Matches, \"*false\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tc.Fatal(`\"Experimental\" not found in version output`)\n}\n\nfunc (s *DockerSuite) TestExperimentalVersionTrue(c *check.C) ", "output": "{\n\ttestRequires(c, ExperimentalDaemon)\n\n\tout, _ := dockerCmd(c, \"version\")\n\tfor _, line := range strings.Split(out, \"\\n\") {\n\t\tif strings.HasPrefix(strings.TrimSpace(line), \"Experimental:\") {\n\t\t\tc.Assert(line, checker.Matches, \"*true\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tc.Fatal(`\"Experimental\" not found in version output`)\n}"} {"input": "package mount\n\n\nfunc GetMounts() ([]*Info, error) {\n\treturn parseMountTable()\n}\n\n\n\nfunc Mounted(mountpoint string) (bool, error) {\n\tentries, err := parseMountTable()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfor _, e := range entries {\n\t\tif e.Mountpoint == mountpoint {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc ForceMount(device, target, mType, options string) error {\n\tflag, data := parseOptions(options)\n\treturn mount(device, target, mType, uintptr(flag), data)\n}\n\n\n\nfunc Unmount(target string) error {\n\tif mounted, err := Mounted(target); err != nil || !mounted {\n\t\treturn err\n\t}\n\treturn unmount(target, mntDetach)\n}\n\nfunc Mount(device, target, mType, options string) error ", "output": "{\n\tflag, _ := parseOptions(options)\n\tif flag&REMOUNT != REMOUNT {\n\t\tif mounted, err := Mounted(target); err != nil || mounted {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn ForceMount(device, target, mType, options)\n}"} {"input": "package backup\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\n\n\n\nfunc Version() string {\n\treturn version.Number\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn \"Azure-SDK-For-Go/\" + Version() + \" backup/2019-06-15\"\n}"} {"input": "package stats\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/go-webpack/webpack/util\"\n\t\"github.com/pkg/errors\"\n)\n\ntype assetList map[string][]string\n\n\nfunc Read(isDev bool, host, fsPath, webPath string) (assetList, error) {\n\tvar data []byte\n\tvar err error\n\n\tif isDev {\n\t\tdata, err = devManifest(host, webPath)\n\t} else {\n\t\tdata, err = prodManifest(fsPath)\n\t}\n\n\tif err != nil {\n\t\treturn assetList{}, errors.Wrap(err, \"go-webpack: Error reading manifest\")\n\t}\n\n\treturn parseManifest(data)\n}\n\nfunc parseChunk(d []string, akey string, assets *assetList) {\n\t(*assets)[akey+\".js\"] = util.Filter(d, func(v string) bool {\n\t\treturn strings.HasSuffix(v, \".js\")\n\t})\n\n\t(*assets)[akey+\".css\"] = util.Filter(d, func(v string) bool {\n\t\treturn strings.HasSuffix(v, \".css\")\n\t})\n}\n\n\n\n\nfunc parseManifest(data []byte) (assetList, error) ", "output": "{\n\tvar err error\n\n\tresp := statsResponse{}\n\terr = json.Unmarshal(data, &resp)\n\tif err != nil {\n\t\treturn assetList{}, errors.Wrap(err, \"go-webpack: Error parsing manifest - json decode\")\n\t}\n\twebpackBase := resp.PublicPath\n\n\tassets := make(assetList, len(resp.AssetsByChunkName))\n\n\tfor akey, aval := range resp.AssetsByChunkName {\n\t\tvar d []string\n\t\terr = json.Unmarshal(*aval, &d)\n\t\tif err != nil {\n\t\t\treturn assets, errors.Wrap(err, fmt.Sprintf(\"go-webpack: Error when parsing manifest for %s: %s %s\", akey, err, string(*aval)))\n\t\t}\n\t\tfor i, v := range d {\n\t\t\td[i] = webpackBase + v\n\t\t}\n\n\t\tparseChunk(d, akey, &assets)\n\t}\n\treturn assets, nil\n}"} {"input": "package delete\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewDeleteFilesFileidentifierParams() *DeleteFilesFileidentifierParams {\n\tvar ()\n\treturn &DeleteFilesFileidentifierParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}\n\n\n\nfunc NewDeleteFilesFileidentifierParamsWithTimeout(timeout time.Duration) *DeleteFilesFileidentifierParams {\n\tvar ()\n\treturn &DeleteFilesFileidentifierParams{\n\n\t\ttimeout: timeout,\n\t}\n}\n\n\ntype DeleteFilesFileidentifierParams struct {\n\n\tFileidentifier string\n\n\ttimeout time.Duration\n}\n\n\nfunc (o *DeleteFilesFileidentifierParams) WithFileidentifier(fileidentifier string) *DeleteFilesFileidentifierParams {\n\to.Fileidentifier = fileidentifier\n\treturn o\n}\n\n\n\n\nfunc (o *DeleteFilesFileidentifierParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error ", "output": "{\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif err := r.SetPathParam(\"fileidentifier\", o.Fileidentifier); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport \"github.com/gin-gonic/gin\"\n\n\n\nfunc setupPages(router *gin.Engine, cache *SiteUsersCache) {\n router.GET(\"/life\", GetRenderLifeGamePage)\n router.GET(\"/form\", GetRenderFormPage)\n router.POST(\"/form_ajax\", func(ctx *gin.Context) {\n PostRenderFormPage(ctx, cache)\n })\n router.GET(\"/calc\", GetRenderCalcPage)\n router.POST(\"/calc_ajax\", func(ctx *gin.Context) {\n PostRenderCalcPage(ctx, cache)\n })\n}\n\nfunc main() {\n cache := NewSiteUsersCache()\n\n router := gin.Default()\n setupStatic(router)\n setupPages(router, cache)\n\n router.Run(\":8080\")\n}\n\nfunc setupStatic(router *gin.Engine) ", "output": "{\n router.Static(\"/css\", STATIC_DIR + \"css\")\n router.Static(\"/js\", STATIC_DIR + \"js\")\n router.LoadHTMLGlob(STATIC_DIR + \"tpl/*.tpl\")\n}"} {"input": "package user\n\nimport (\n\t\"os\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"syscall\"\n\t\"testing\"\n)\n\n\n\nfunc TestLookup(t *testing.T) {\n\tif skip(t) {\n\t\treturn\n\t}\n\n\tuid := syscall.Getuid()\n\tu, err := LookupId(uid)\n\tif err != nil {\n\t\tt.Fatalf(\"LookupId: %v\", err)\n\t}\n\tif e, g := uid, u.Uid; e != g {\n\t\tt.Errorf(\"expected Uid of %d; got %d\", e, g)\n\t}\n\tfi, err := os.Stat(u.HomeDir)\n\tif err != nil || !fi.IsDirectory() {\n\t\tt.Errorf(\"expected a valid HomeDir; stat(%q): err=%v, IsDirectory=%v\", u.HomeDir, err, fi.IsDirectory())\n\t}\n\tif u.Username == \"\" {\n\t\tt.Fatalf(\"didn't get a username\")\n\t}\n\n\tun, err := Lookup(u.Username)\n\tif err != nil {\n\t\tt.Fatalf(\"Lookup: %v\", err)\n\t}\n\tif !reflect.DeepEqual(u, un) {\n\t\tt.Errorf(\"Lookup by userid vs. name didn't match\\n\"+\n\t\t\t\"LookupId(%d): %#v\\n\"+\n\t\t\t\"Lookup(%q): %#v\\n\", uid, u, u.Username, un)\n\t}\n}\n\nfunc skip(t *testing.T) bool ", "output": "{\n\tif runtime.GOARCH == \"arm\" {\n\t\tt.Logf(\"user: cgo not implemented on arm; skipping tests\")\n\t\treturn true\n\t}\n\n\tif runtime.GOOS == \"linux\" || runtime.GOOS == \"freebsd\" || runtime.GOOS == \"darwin\" {\n\t\treturn false\n\t}\n\n\tt.Logf(\"user: Lookup not implemented on %s; skipping test\", runtime.GOOS)\n\treturn true\n}"} {"input": "package thuder\n\nimport (\n\t\"errors\"\n\n\t\"github.com/stianeikeland/go-rpio/v4\"\n)\n\n\n\nfunc setupGPIO() error ", "output": "{\n\tif pinID < 0 {\n\t\treturn errors.New(\"need to SetPinID\")\n\t}\n\terr := rpio.Open()\n\tif err != nil {\n\t\treturn err\n\t}\n\tpin := rpio.Pin(pinID)\n\tpin.Output()\n\tlightOn = pin.High\n\tlightOff = pin.Low\n\treturn nil\n}"} {"input": "package eventhub\n\n\n\n\n\n\n\nimport (\n\t\"github.com/Azure/go-autorest/autorest\"\n)\n\nconst (\n\tDefaultBaseURI = \"https:management.azure.com\"\n)\n\n\ntype BaseClient struct {\n\tautorest.Client\n\tBaseURI string\n\tSubscriptionID string\n}\n\n\n\n\n\n\nfunc NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tBaseURI: baseURI,\n\t\tSubscriptionID: subscriptionID,\n\t}\n}\n\nfunc New(subscriptionID string) BaseClient ", "output": "{\n\treturn NewWithBaseURI(DefaultBaseURI, subscriptionID)\n}"} {"input": "package msg\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com/KunTengRom/xfrps/utils/errors\"\n)\n\nfunc unpack(typeByte byte, buffer []byte, msgIn Message) (msg Message, err error) {\n\tif msgIn == nil {\n\t\tt, ok := TypeMap[typeByte]\n\t\tif !ok {\n\t\t\terr = fmt.Errorf(\"Unsupported message type %b\", typeByte)\n\t\t\treturn\n\t\t}\n\n\t\tmsg = reflect.New(t).Interface().(Message)\n\t} else {\n\t\tmsg = msgIn\n\t}\n\n\terr = json.Unmarshal(buffer, &msg)\n\treturn\n}\n\nfunc UnPackInto(buffer []byte, msg Message) (err error) {\n\t_, err = unpack(' ', buffer, msg)\n\treturn\n}\n\n\n\nfunc Pack(msg Message) ([]byte, error) {\n\ttypeByte, ok := TypeStringMap[reflect.TypeOf(msg).Elem()]\n\tif !ok {\n\t\treturn nil, errors.ErrMsgType\n\t}\n\n\tcontent, err := json.Marshal(msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbuffer := bytes.NewBuffer(nil)\n\tbuffer.WriteByte(typeByte)\n\tbinary.Write(buffer, binary.BigEndian, int32(len(content)))\n\tbuffer.Write(content)\n\treturn buffer.Bytes(), nil\n}\n\nfunc UnPack(typeByte byte, buffer []byte) (msg Message, err error) ", "output": "{\n\treturn unpack(typeByte, buffer, nil)\n}"} {"input": "package block\n\nimport (\n\t\"github.com/juju/cmd\"\n\n\t\"github.com/juju/juju/apiserver/params\"\n\t\"github.com/juju/juju/cmd/envcmd\"\n)\n\nvar (\n\tBlockClient = &getBlockClientAPI\n\tUnblockClient = &getUnblockClientAPI\n\tListClient = &getBlockListAPI\n\n\tNewDestroyCommand = newDestroyCommand\n\tNewRemoveCommand = newRemoveCommand\n\tNewChangeCommand = newChangeCommand\n\tNewListCommand = newListCommand\n)\n\ntype MockBlockClient struct {\n\tBlockType string\n\tMsg string\n}\n\nfunc (c *MockBlockClient) Close() error {\n\treturn nil\n}\n\nfunc (c *MockBlockClient) SwitchBlockOn(blockType, msg string) error {\n\tc.BlockType = blockType\n\tc.Msg = msg\n\treturn nil\n}\n\nfunc (c *MockBlockClient) SwitchBlockOff(blockType string) error {\n\tc.BlockType = blockType\n\tc.Msg = \"\"\n\treturn nil\n}\n\n\n\nfunc NewUnblockCommandWithClient(client UnblockClientAPI) cmd.Command {\n\treturn envcmd.Wrap(&unblockCommand{client: client})\n}\n\nfunc (c *MockBlockClient) List() ([]params.Block, error) ", "output": "{\n\tif c.BlockType == \"\" {\n\t\treturn []params.Block{}, nil\n\t}\n\n\treturn []params.Block{\n\t\tparams.Block{\n\t\t\tType: c.BlockType,\n\t\t\tMessage: c.Msg,\n\t\t},\n\t}, nil\n}"} {"input": "package sign\n\nimport (\n\t\"dfss\"\n\tcAPI \"dfss/dfssc/api\"\n\tpAPI \"dfss/dfssp/api\"\n\t\"dfss/dfsst/entities\"\n\t\"dfss/net\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc\"\n)\n\ntype clientServer struct {\n\tincomingPromises chan interface{}\n\tincomingSignatures chan interface{}\n}\n\n\n\n\n\n\nfunc (s *clientServer) TreatPromise(ctx context.Context, in *cAPI.Promise) (*pAPI.ErrorCode, error) {\n\tvalid, _, _, _ := entities.IsRequestValid(ctx, []*cAPI.Promise{in})\n\tif !valid {\n\t\treturn &pAPI.ErrorCode{Code: pAPI.ErrorCode_SUCCESS}, nil\n\t}\n\treturn getServerErrorCode(s.incomingPromises, in), nil\n}\n\n\n\n\nfunc (s *clientServer) TreatSignature(ctx context.Context, in *cAPI.Signature) (*pAPI.ErrorCode, error) {\n\treturn getServerErrorCode(s.incomingSignatures, in), nil\n}\n\n\n\n\nfunc (s *clientServer) Discover(ctx context.Context, in *cAPI.Hello) (*cAPI.Hello, error) {\n\treturn &cAPI.Hello{Version: dfss.Version}, nil\n}\n\n\nfunc (m *SignatureManager) GetServer() *grpc.Server {\n\tserver := net.NewServer(m.auth.Cert, m.auth.Key, m.auth.CA)\n\tm.cServerIface = clientServer{}\n\tcAPI.RegisterClientServer(server, &m.cServerIface)\n\treturn server\n}\n\nfunc getServerErrorCode(c chan interface{}, in interface{}) *pAPI.ErrorCode ", "output": "{\n\tif c != nil {\n\t\tc <- in\n\t\treturn &pAPI.ErrorCode{Code: pAPI.ErrorCode_SUCCESS}\n\t}\n\treturn &pAPI.ErrorCode{Code: pAPI.ErrorCode_INTERR} \n}"} {"input": "package internalversion\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\tapi \"k8s.io/kubernetes/pkg/api\"\n)\n\ntype TestgroupInterface interface {\n\tRESTClient() rest.Interface\n\tTestTypesGetter\n}\n\n\ntype TestgroupClient struct {\n\trestClient rest.Interface\n}\n\nfunc (c *TestgroupClient) TestTypes(namespace string) TestTypeInterface {\n\treturn newTestTypes(c, namespace)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*TestgroupClient, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &TestgroupClient{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *TestgroupClient {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *TestgroupClient {\n\treturn &TestgroupClient{c}\n}\n\n\n\n\n\nfunc (c *TestgroupClient) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc setConfigDefaults(config *rest.Config) error ", "output": "{\n\tg, err := api.Registry.Group(\"testgroup.k8s.io\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig.APIPath = \"/apis\"\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\tif config.GroupVersion == nil || config.GroupVersion.Group != g.GroupVersion.Group {\n\t\tcopyGroupVersion := g.GroupVersion\n\t\tconfig.GroupVersion = ©GroupVersion\n\t}\n\tconfig.NegotiatedSerializer = api.Codecs\n\n\tif config.QPS == 0 {\n\t\tconfig.QPS = 5\n\t}\n\tif config.Burst == 0 {\n\t\tconfig.Burst = 10\n\t}\n\treturn nil\n}"} {"input": "package evolve\n\nimport \"sync\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype FitnessCache struct {\n\n\tWrapped Evaluator\n\tcache sync.Map\n}\n\n\n\n\n\n\n\nfunc (c *FitnessCache) Fitness(cand interface{}, pop []interface{}) float64 {\n\tvar fitness float64\n\tval, ok := c.cache.Load(cand)\n\tif ok {\n\t\tfitness = val.(float64)\n\t} else {\n\t\tfitness = c.Wrapped.Fitness(cand, pop)\n\t\tc.cache.Store(cand, fitness)\n\t}\n\treturn fitness\n}\n\n\n\n\n\nfunc (c *FitnessCache) IsNatural() bool ", "output": "{ return c.Wrapped.IsNatural() }"} {"input": "package operations\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n)\n\n\nconst DeleteDeploymentOKCode int = 200\n\n\ntype DeleteDeploymentOK struct {\n}\n\n\nfunc NewDeleteDeploymentOK() *DeleteDeploymentOK {\n\treturn &DeleteDeploymentOK{}\n}\n\n\nfunc (o *DeleteDeploymentOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n}\n\n\nconst DeleteDeploymentUnauthorizedCode int = 401\n\n\ntype DeleteDeploymentUnauthorized struct {\n\tWWWAuthenticate string `json:\"WWW_Authenticate\"`\n}\n\n\nfunc NewDeleteDeploymentUnauthorized() *DeleteDeploymentUnauthorized {\n\treturn &DeleteDeploymentUnauthorized{}\n}\n\n\n\n\n\nfunc (o *DeleteDeploymentUnauthorized) SetWWWAuthenticate(wWWAuthenticate string) {\n\to.WWWAuthenticate = wWWAuthenticate\n}\n\n\nfunc (o *DeleteDeploymentUnauthorized) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\n\twWWAuthenticate := o.WWWAuthenticate\n\tif wWWAuthenticate != \"\" {\n\t\trw.Header().Set(\"WWW_Authenticate\", wWWAuthenticate)\n\t}\n\n\trw.WriteHeader(401)\n}\n\n\nconst DeleteDeploymentNotFoundCode int = 404\n\n\ntype DeleteDeploymentNotFound struct {\n}\n\n\nfunc NewDeleteDeploymentNotFound() *DeleteDeploymentNotFound {\n\treturn &DeleteDeploymentNotFound{}\n}\n\n\nfunc (o *DeleteDeploymentNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(404)\n}\n\n\nconst DeleteDeploymentInternalServerErrorCode int = 500\n\n\ntype DeleteDeploymentInternalServerError struct {\n}\n\n\nfunc NewDeleteDeploymentInternalServerError() *DeleteDeploymentInternalServerError {\n\treturn &DeleteDeploymentInternalServerError{}\n}\n\n\nfunc (o *DeleteDeploymentInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(500)\n}\n\nfunc (o *DeleteDeploymentUnauthorized) WithWWWAuthenticate(wWWAuthenticate string) *DeleteDeploymentUnauthorized ", "output": "{\n\to.WWWAuthenticate = wWWAuthenticate\n\treturn o\n}"} {"input": "package shell_local\n\nimport (\n\t\"bytes\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/packer/packer\"\n)\n\nfunc TestCommunicator_impl(t *testing.T) {\n\tvar _ packer.Communicator = new(Communicator)\n}\n\n\n\nfunc TestCommunicator(t *testing.T) ", "output": "{\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"windows not supported for this test\")\n\t\treturn\n\t}\n\n\tc := &Communicator{}\n\n\tvar buf bytes.Buffer\n\tcmd := &packer.RemoteCmd{\n\t\tCommand: \"/bin/echo foo\",\n\t\tStdout: &buf,\n\t}\n\n\tif err := c.Start(cmd); err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\tcmd.Wait()\n\n\tif cmd.ExitStatus != 0 {\n\t\tt.Fatalf(\"err bad exit status: %d\", cmd.ExitStatus)\n\t}\n\n\tif strings.TrimSpace(buf.String()) != \"foo\" {\n\t\tt.Fatalf(\"bad: %s\", buf.String())\n\t}\n}"} {"input": "package core\n\nimport (\n\t\"runtime\"\n\n\t\"github.com/Tzunami/go-earthdollar/core/types\"\n\t\"github.com/Tzunami/go-earthdollar/pow\"\n)\n\n\ntype nonceCheckResult struct {\n\tindex int \n\tvalid bool \n}\n\n\n\n\nfunc verifyNoncesFromHeaders(checker pow.PoW, headers []*types.Header) (chan<- struct{}, <-chan nonceCheckResult) {\n\titems := make([]pow.Block, len(headers))\n\tfor i, header := range headers {\n\t\titems[i] = types.NewBlockWithHeader(header)\n\t}\n\treturn verifyNonces(checker, items)\n}\n\n\n\n\nfunc verifyNoncesFromBlocks(checker pow.PoW, blocks []*types.Block) (chan<- struct{}, <-chan nonceCheckResult) {\n\titems := make([]pow.Block, len(blocks))\n\tfor i, block := range blocks {\n\t\titems[i] = block\n\t}\n\treturn verifyNonces(checker, items)\n}\n\n\n\n\n\nfunc verifyNonces(checker pow.PoW, items []pow.Block) (chan<- struct{}, <-chan nonceCheckResult) ", "output": "{\n\tworkers := runtime.GOMAXPROCS(0)\n\tif len(items) < workers {\n\t\tworkers = len(items)\n\t}\n\ttasks := make(chan int, workers)\n\tresults := make(chan nonceCheckResult, len(items)) \n\tfor i := 0; i < workers; i++ {\n\t\tgo func() {\n\t\t\tfor index := range tasks {\n\t\t\t\tresults <- nonceCheckResult{index: index, valid: checker.Verify(items[index])}\n\t\t\t}\n\t\t}()\n\t}\n\tabort := make(chan struct{})\n\tgo func() {\n\t\tdefer close(tasks)\n\n\t\tfor i := range items {\n\t\t\tselect {\n\t\t\tcase tasks <- i:\n\t\t\t\tcontinue\n\t\t\tcase <-abort:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\treturn abort, results\n}"} {"input": "package mongo\n\nimport (\n\t\"github.com/peteraba/d5/lib/util\"\n\t\"gopkg.in/mgo.v2\"\n)\n\nvar (\n\tsession *mgo.Session\n\tdb *mgo.Database\n)\n\nfunc SetMgoSession(mgoSession *mgo.Session) {\n\tsession = mgoSession\n}\n\nfunc SetMgoDb(mgoDatabase *mgo.Database) {\n\tdb = mgoDatabase\n}\n\nfunc CreateMgoDbFromEnvs() *mgo.Database {\n\tdbHost, dbName := ParseDbEnvs()\n\n\tmgoDb, err := CreateMgoDb(dbHost, dbName)\n\n\tif err != nil {\n\t\tutil.LogFatalfMsg(err, \"MongoDB database could not be created: %v\", true)\n\t}\n\n\treturn mgoDb\n}\n\nfunc CreateMgoDb(dbHost, dbName string) (*mgo.Database, error) {\n\tsession, err := getMgoSession(dbHost)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn getMgoDb(session, dbName), nil\n}\n\n\n\nfunc getMgoDb(mgoSession *mgo.Session, dbName string) *mgo.Database {\n\tif db != nil {\n\t\treturn db\n\t}\n\n\tmgoSession = mgoSession.Clone()\n\n\tdb = mgoSession.DB(dbName)\n\n\treturn db\n}\n\nfunc getMgoSession(dbHost string) (*mgo.Session, error) ", "output": "{\n\tvar (\n\t\terr error\n\t)\n\n\tif session != nil {\n\t\treturn session, nil\n\t}\n\n\tsession, err = mgo.Dial(dbHost)\n\n\treturn session, err\n}"} {"input": "package session\n\nimport (\n\t\"net\"\n\t\"time\"\n\n\t\"github.com/Sirupsen/logrus\"\n\t\"github.com/pkg/errors\"\n\t\"golang.org/x/net/context\"\n\t\"golang.org/x/net/http2\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/health/grpc_health_v1\"\n)\n\nfunc serve(ctx context.Context, grpcServer *grpc.Server, conn net.Conn) {\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tconn.Close()\n\t}()\n\tlogrus.Debugf(\"serving grpc connection\")\n\t(&http2.Server{}).ServeConn(conn, &http2.ServeConnOpts{Handler: grpcServer})\n}\n\n\n\nfunc monitorHealth(ctx context.Context, cc *grpc.ClientConn, cancelConn func()) {\n\tdefer cancelConn()\n\tdefer cc.Close()\n\n\tticker := time.NewTicker(500 * time.Millisecond)\n\tdefer ticker.Stop()\n\thealthClient := grpc_health_v1.NewHealthClient(cc)\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\t<-ticker.C\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\t\t\t_, err := healthClient.Check(ctx, &grpc_health_v1.HealthCheckRequest{})\n\t\t\tcancel()\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc grpcClientConn(ctx context.Context, conn net.Conn) (context.Context, *grpc.ClientConn, error) ", "output": "{\n\tdialOpt := grpc.WithDialer(func(addr string, d time.Duration) (net.Conn, error) {\n\t\treturn conn, nil\n\t})\n\n\tcc, err := grpc.DialContext(ctx, \"\", dialOpt, grpc.WithInsecure())\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"failed to create grpc client\")\n\t}\n\n\tctx, cancel := context.WithCancel(ctx)\n\tgo monitorHealth(ctx, cc, cancel)\n\n\treturn ctx, cc, nil\n}"} {"input": "package requestutil\n\nimport (\n\t\"bytes\"\n\t\"crypto/tls\"\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"github.com/hashicorp/vault/helper/compressutil\"\n\t\"github.com/hashicorp/vault/helper/jsonutil\"\n)\n\ntype bufCloser struct {\n\t*bytes.Buffer\n}\n\nfunc (b bufCloser) Close() error {\n\tb.Reset()\n\treturn nil\n}\n\ntype ForwardedRequest struct {\n\tMethod string `json:\"method\"`\n\n\tURL *url.URL `json:\"url\"`\n\n\tHeader http.Header `json:\"header\"`\n\n\tBody []byte `json:\"body\"`\n\n\tHost string `json:\"host\"`\n\n\tRemoteAddr string `json:\"remote_addr\"`\n\n\tConnectionState *tls.ConnectionState `json:\"connection_state\"`\n}\n\n\n\n\n\n\n\n\nfunc ParseForwardedRequest(req *http.Request) (*http.Request, error) {\n\tbuf := bufCloser{\n\t\tBuffer: bytes.NewBuffer(nil),\n\t}\n\t_, err := buf.ReadFrom(req.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar fq ForwardedRequest\n\terr = jsonutil.DecodeJSON(buf.Bytes(), &fq)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbuf.Reset()\n\t_, err = buf.Write(fq.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret := &http.Request{\n\t\tMethod: fq.Method,\n\t\tURL: fq.URL,\n\t\tHeader: fq.Header,\n\t\tBody: buf,\n\t\tHost: fq.Host,\n\t\tRemoteAddr: fq.RemoteAddr,\n\t\tTLS: fq.ConnectionState,\n\t}\n\n\treturn ret, nil\n}\n\nfunc GenerateForwardedRequest(req *http.Request, addr string) (*http.Request, error) ", "output": "{\n\tfq := ForwardedRequest{\n\t\tMethod: req.Method,\n\t\tURL: req.URL,\n\t\tHeader: req.Header,\n\t\tHost: req.Host,\n\t\tRemoteAddr: req.RemoteAddr,\n\t\tConnectionState: req.TLS,\n\t}\n\n\tbuf := bytes.NewBuffer(nil)\n\t_, err := buf.ReadFrom(req.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfq.Body = buf.Bytes()\n\n\tnewBody, err := jsonutil.EncodeJSONAndCompress(&fq, &compressutil.CompressionConfig{\n\t\tType: compressutil.CompressionTypeLzw,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret, err := http.NewRequest(\"POST\", addr, bytes.NewBuffer(newBody))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ret, nil\n}"} {"input": "package ipns\n\nimport (\n\t\"context\"\n\n\t\"github.com/ipfs/go-ipfs/core\"\n\tnsys \"github.com/ipfs/go-ipfs/namesys\"\n\tci \"gx/ipfs/QmPvyPwuCgJ7pDmrKDxRtsScJgBaM5h4EpRL2qQJsmXf4n/go-libp2p-crypto\"\n\tpath \"gx/ipfs/QmT3rzed1ppXefourpmoZ7tyVQfsGPQZ1pHDngLmCvXxd3/go-path\"\n\tft \"gx/ipfs/QmfB3oNXGGq9S4B2a9YeCajoATms3Zw2VvDm8fK7VeLSV8/go-unixfs\"\n)\n\n\n\n\n\nfunc InitializeKeyspace(n *core.IpfsNode, key ci.PrivKey) error ", "output": "{\n\tctx, cancel := context.WithCancel(n.Context())\n\tdefer cancel()\n\n\temptyDir := ft.EmptyDirNode()\n\n\terr := n.Pinning.Pin(ctx, emptyDir, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = n.Pinning.Flush()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpub := nsys.NewIpnsPublisher(n.Routing, n.Repo.Datastore())\n\n\treturn pub.Publish(ctx, key, path.FromCid(emptyDir.Cid()))\n}"} {"input": "package retry\n\nimport (\n\t\"errors\"\n\t\"testing\"\n)\n\n\n\n\nfunc TestErrorGenerator(t *testing.T) {\n\terrors := 3\n\tf := errorGenerator(errors, false)\n\tfor i := 0; i < errors-1; i++ {\n\t\tif err := f(); err == nil {\n\t\t\tt.Fatalf(\"Error should have been thrown at iteration %v\", i)\n\t\t}\n\t}\n\tif err := f(); err == nil {\n\t\tt.Fatalf(\"Error should not have been thrown this call!\")\n\t}\n}\n\nfunc errorGenerator(n int, retryable bool) func() error ", "output": "{\n\terrorCount := 0\n\treturn func() (err error) {\n\t\tif errorCount < n {\n\t\t\terrorCount++\n\t\t\te := errors.New(\"Error\")\n\t\t\tif retryable {\n\t\t\t\treturn &RetriableError{Err: e}\n\t\t\t}\n\t\t\treturn e\n\n\t\t}\n\n\t\treturn nil\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\thyperclient \"github.com/Cloud-Foundations/Dominator/hypervisor/client\"\n\t\"github.com/Cloud-Foundations/Dominator/lib/log\"\n)\n\n\n\nfunc connectToVmConsole(vmHostname string, logger log.DebugLogger) error {\n\tif vmIP, hypervisor, err := lookupVmAndHypervisor(vmHostname); err != nil {\n\t\treturn err\n\t} else {\n\t\treturn connectToVmConsoleOnHypervisor(hypervisor, vmIP, logger)\n\t}\n}\n\nfunc connectToVmConsoleOnHypervisor(hypervisor string, ipAddr net.IP,\n\tlogger log.DebugLogger) error {\n\tclient, err := dialHypervisor(hypervisor)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer client.Close()\n\treturn hyperclient.ConnectToVmConsole(client, ipAddr, *vncViewer, logger)\n}\n\nfunc connectToVmConsoleSubcommand(args []string,\n\tlogger log.DebugLogger) error ", "output": "{\n\tif err := connectToVmConsole(args[0], logger); err != nil {\n\t\treturn fmt.Errorf(\"Error connecting to VM console: %s\", err)\n\t}\n\treturn nil\n}"} {"input": "package raft\n\nimport (\n\t\"github.com/iketheadore/raft/comm\"\n\t\"github.com/iketheadore/raft/logic\"\n)\n\ntype Raft struct {\n\tlocalServ logic.Server\n\tlistener comm.Listener\n\tsender comm.Sender\n\tlogic *logic.Logic\n}\n\nfunc New(addr string) *Raft {\n\tr := &Raft{localServ: logic.Server{Addr: addr, Role: logic.Follower}, listener: comm.NewListener(addr)}\n\tr.listener.Run()\n\tr.logic = logic.New(r.localServ)\n\tr.logic.Subscribe(r.listener)\n\treturn r\n}\n\n\n\nfunc (r *Raft) Run() {\n\tr.logic.Run()\n}\n\nfunc (r *Raft) ReplicateCmd(cmd comm.Command) {\n\tr.logic.ReplicateCmd(cmd)\n}\n\nfunc (r *Raft) Connect(addr string) error ", "output": "{\n\treturn r.logic.Connect(logic.Server{Addr: addr, Role: logic.Follower})\n}"} {"input": "package integration\n\nimport (\n\t\"context\"\n\t\"testing\"\n)\n\n\n\nfunc TestActivityFieldsService_List(t *testing.T) ", "output": "{\n\tresult, _, err := client.ActivityFields.List(context.Background())\n\n\tif err != nil {\n\t\tt.Errorf(\"Could not get results: %v\", err)\n\t}\n\n\tif result.Success != true {\n\t\tt.Error(\"Got invalid result\")\n\t}\n}"} {"input": "package named\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestNamedSelector(t *testing.T) ", "output": "{\n\tdata := []string{\"foo\", \"bar\", \"baz\"}\n\n\ts := NewSelector()\n\n\tfor _, name := range data {\n\t\tnext, err := s.Select(name)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tfor i := 0; i < 3; i++ {\n\t\t\tnode, err := next()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tif node.Address != name {\n\t\t\t\tt.Fatalf(\"got %s expected %s\", node.Address, name)\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package common\n\nimport (\n\t\"os/exec\"\n)\n\nfunc IsExecWorking(commandName string, args ...string) bool {\n\tout, err := CheckExec(commandName, args...)\n\treturn err == nil && len(out) > 0\n}\n\n\n\nfunc CheckExec(commandName string, args ...string) (string, error) ", "output": "{\n\tb, err := exec.Command(commandName, args...).CombinedOutput()\n\treturn string(b), err\n}"} {"input": "package goparser\n\nimport (\n\t\"go/ast\"\n\t\"testing\"\n)\n\nfunc testCmtAgainstExpt(t *testing.T, text, expected string) {\n\tcmt := ast.Comment{\n\t\tText: text,\n\t}\n\n\tresult := CmtToStr(&cmt)\n\n\tif expected != result {\n\t\tt.Errorf(\"Result doesn't match expectation\")\n\t\tt.Errorf(\"Expected:\\n%s\", expected)\n\t\tt.Errorf(\"Get:\\n%s\", result)\n\t}\n}\n\n\nfunc TestCmtToStr1(t *testing.T) {\n\ttestCmtAgainstExpt(t,\n\t\t\"//\\n\"+\n\t\t\t\" // testing line 1\\n\"+\n\t\t\t\"//testing line 2\\n\"+\n\t\t\t\"// testing line 3\",\n\t\t\"testing line 1\\n\"+\n\t\t\t\"testing line 2\\n\"+\n\t\t\t\"testing line 3\\n\")\n}\n\n\nfunc TestCmtToStr2(t *testing.T) {\n\ttestCmtAgainstExpt(t,\n\t\t\"/**\\n\"+\n\t\t\t\" * testing line 1\\n\"+\n\t\t\t\"* testing line 2\\n\"+\n\t\t\t\" * testing line 3\\n\"+\n\t\t\t\" */\",\n\t\t\" testing line 1\\n\"+\n\t\t\t\" testing line 2\\n\"+\n\t\t\t\" testing line 3\\n\")\n}\n\n\n\n\nfunc TestCmtToStr3(t *testing.T) ", "output": "{\n\ttestCmtAgainstExpt(t,\n\t\t\"/*\\n\"+\n\t\t\t\" testing line 1\\n\"+\n\t\t\t\" testing line 2\\n\"+\n\t\t\t\" testing line 3\\n\"+\n\t\t\t\"*/\",\n\t\t\" testing line 1\\n\"+\n\t\t\t\" testing line 2\\n\"+\n\t\t\t\" testing line 3\\n\")\n}"} {"input": "package nes\n\nimport \"log\"\n\ntype Mapper2 struct {\n\t*Cartridge\n\tprgBank1 int\n\tprgBank2 int\n}\n\nfunc NewMapper2(cartridge *Cartridge) Mapper {\n\tprgBanks := len(cartridge.PRG) / 0x4000\n\tprgBank1 := 0\n\tprgBank2 := prgBanks - 1\n\treturn &Mapper2{cartridge, prgBank1, prgBank2}\n}\n\nfunc (m *Mapper2) Step() {\n}\n\n\n\nfunc (m *Mapper2) Write(address uint16, value byte) {\n\tswitch {\n\tcase address < 0x2000:\n\t\tm.CHR[address] = value\n\tcase address >= 0x8000:\n\t\tm.prgBank1 = int(value)\n\tcase address >= 0x6000:\n\t\tindex := int(address) - 0x6000\n\t\tm.SRAM[index] = value\n\tdefault:\n\t\tlog.Fatalf(\"unhandled mapper2 write at address: 0x%04X\", address)\n\t}\n}\n\nfunc (m *Mapper2) Read(address uint16) byte ", "output": "{\n\tswitch {\n\tcase address < 0x2000:\n\t\treturn m.CHR[address]\n\tcase address >= 0xC000:\n\t\tindex := m.prgBank2*0x4000 + int(address-0xC000)\n\t\treturn m.PRG[index]\n\tcase address >= 0x8000:\n\t\tindex := m.prgBank1*0x4000 + int(address-0x8000)\n\t\treturn m.PRG[index]\n\tcase address >= 0x6000:\n\t\tindex := int(address) - 0x6000\n\t\treturn m.SRAM[index]\n\tdefault:\n\t\tlog.Fatalf(\"unhandled mapper2 read at address: 0x%04X\", address)\n\t}\n\treturn 0\n}"} {"input": "package testclient\n\nimport (\n\tkapi \"k8s.io/kubernetes/pkg/api\"\n\tktestclient \"k8s.io/kubernetes/pkg/client/unversioned/testclient\"\n\n\t\"github.com/openshift/origin/pkg/client\"\n\timageapi \"github.com/openshift/origin/pkg/image/api\"\n)\n\n\n\n\ntype FakeImages struct {\n\tFake *Fake\n}\n\nvar _ client.ImageInterface = &FakeImages{}\n\nfunc (c *FakeImages) Get(name string) (*imageapi.Image, error) {\n\tobj, err := c.Fake.Invokes(ktestclient.NewRootGetAction(\"images\", name), &imageapi.Image{})\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*imageapi.Image), err\n}\n\nfunc (c *FakeImages) List(opts kapi.ListOptions) (*imageapi.ImageList, error) {\n\tobj, err := c.Fake.Invokes(ktestclient.NewRootListAction(\"images\", opts), &imageapi.ImageList{})\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*imageapi.ImageList), err\n}\n\n\n\nfunc (c *FakeImages) Delete(name string) error {\n\t_, err := c.Fake.Invokes(ktestclient.NewRootDeleteAction(\"images\", name), &imageapi.Image{})\n\treturn err\n}\n\nfunc (c *FakeImages) Create(inObj *imageapi.Image) (*imageapi.Image, error) ", "output": "{\n\tobj, err := c.Fake.Invokes(ktestclient.NewRootCreateAction(\"images\", inObj), inObj)\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*imageapi.Image), err\n}"} {"input": "package gull\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n)\n\ntype Up struct {\n\tEnvironment string\n\tSourceDirectory string\n\tMigrateTarget MigrationTarget\n\tMigrations *Migrations\n}\n\nfunc NewUp(source string, target MigrationTarget) *Up {\n\treturn &Up{\n\t\tEnvironment: target.GetEnvironment(),\n\t\tMigrateTarget: target,\n\t\tSourceDirectory: source,\n\t\tMigrations: NewMigrations(),\n\t}\n}\n\nfunc (u *Up) Migrate() error {\n\terr := u.Ingest()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif u.MigrateTarget.IsPerformingFullMigration() {\n\t\tu.MigrateTarget.GetLogger().Info(\"Deleting configuration for [%v]/[%v]\", u.MigrateTarget.GetApplication(), u.MigrateTarget.GetEnvironment())\n\t\t_ = u.MigrateTarget.DeleteEnvironment()\n\t}\n\treturn u.Migrations.Apply(u.MigrateTarget)\n}\n\nfunc (u *Up) Ingest() error {\n\treturn filepath.Walk(u.SourceDirectory, u.IngestFile)\n}\n\n\n\nfunc (u *Up) IngestFile(path string, f os.FileInfo, err error) error ", "output": "{\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !f.IsDir() {\n\t\tmigration, err := NewMigrationFromGullFile(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = u.Migrations.Add(migration)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package btcec\n\nimport (\n\tsecp \"github.com/decred/dcrd/dcrec/secp256k1/v4\"\n)\n\n\n\ntype JacobianPoint = secp.JacobianPoint\n\n\n\nfunc MakeJacobianPoint(x, y, z *FieldVal) JacobianPoint {\n\treturn secp.MakeJacobianPoint(x, y, z)\n}\n\n\n\nfunc AddNonConst(p1, p2, result *JacobianPoint) {\n\tsecp.AddNonConst(p1, p2, result)\n}\n\n\n\n\n\n\n\n\nfunc DecompressY(x *FieldVal, odd bool, resultY *FieldVal) bool {\n\treturn secp.DecompressY(x, odd, resultY)\n}\n\n\n\n\n\n\nfunc DoubleNonConst(p, result *JacobianPoint) {\n\tsecp.DoubleNonConst(p, result)\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc ScalarMultNonConst(k *ModNScalar, point, result *JacobianPoint) {\n\tsecp.ScalarMultNonConst(k, point, result)\n}\n\nfunc ScalarBaseMultNonConst(k *ModNScalar, result *JacobianPoint) ", "output": "{\n\tsecp.ScalarBaseMultNonConst(k, result)\n}"} {"input": "package v2\n\nimport (\n\t\"os\"\n\n\t\"code.cloudfoundry.org/cli/cf/cmd\"\n\t\"code.cloudfoundry.org/cli/commands\"\n\t\"code.cloudfoundry.org/cli/commands/flags\"\n)\n\ntype DeleteRouteCommand struct {\n\tRequiredArgs flags.Domain `positional-args:\"yes\"`\n\tForce bool `short:\"f\" description:\"Force deletion without confirmation\"`\n\tHostname string `long:\"hostname\" short:\"n\" description:\"Hostname used to identify the HTTP route\"`\n\tPath string `long:\"path\" description:\"Path used to identify the HTTP route\"`\n\tPort int `long:\"port\" description:\"Port used to identify the TCP route\"`\n\tusage interface{} `usage:\"Delete an HTTP route:\\n CF_NAME delete-route DOMAIN [--hostname HOSTNAME] [--path PATH] [-f]\\n\\n Delete a TCP route:\\n CF_NAME delete-route DOMAIN --port PORT [-f]\\n\\nEXAMPLES:\\n CF_NAME delete-route example.com # example.com\\n CF_NAME delete-route example.com --hostname myhost # myhost.example.com\\n CF_NAME delete-route example.com --hostname myhost --path foo # myhost.example.com/foo\\n CF_NAME delete-route example.com --port 5000 # example.com:5000\"`\n\trelatedCommands interface{} `related_commands:\"delete-orphaned-routes, routes, unmap-route\"`\n}\n\n\n\nfunc (_ DeleteRouteCommand) Execute(args []string) error {\n\tcmd.Main(os.Getenv(\"CF_TRACE\"), os.Args)\n\treturn nil\n}\n\nfunc (_ DeleteRouteCommand) Setup(config commands.Config, ui commands.UI) error ", "output": "{\n\treturn nil\n}"} {"input": "package route\n\nimport (\n\t\"app/controller\"\n\t\"net/http\"\n)\n\nfunc Api(c *controller.Context) http.Handler {\n\treturn &apiHandler{c: c}\n}\n\ntype apiHandler struct {\n\tc *controller.Context\n}\n\n\n\nfunc (h apiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tswitch {\n\tcase r.Method == http.MethodPost && r.URL.Path == \"/org/get\":\n\t\th.c.OrgGetApi(w, r)\n\tcase r.Method == http.MethodPost && r.URL.Path == \"/org/create\":\n\t\th.c.OrgCreateApi(w, r)\n\tcase r.Method == http.MethodPost && r.URL.Path == \"/session/get\":\n\t\th.c.SessionGetApi(w, r)\n\tcase r.Method == http.MethodPost && r.URL.Path == \"/session/create\":\n\t\th.c.SessionCreateApi(w, r)\n\tdefault:\n\t\th.c.NotFoundApi(w, r)\n\t}\n}"} {"input": "package configmap\n\nimport (\n\t\"testing\"\n\n\tgenericapirequest \"k8s.io/apiserver/pkg/request\"\n\t\"k8s.io/kubernetes/pkg/api\"\n\tapitesting \"k8s.io/kubernetes/pkg/api/testing\"\n)\n\nfunc TestConfigMapStrategy(t *testing.T) {\n\tctx := genericapirequest.NewDefaultContext()\n\tif !Strategy.NamespaceScoped() {\n\t\tt.Errorf(\"ConfigMap must be namespace scoped\")\n\t}\n\tif Strategy.AllowCreateOnUpdate() {\n\t\tt.Errorf(\"ConfigMap should not allow create on update\")\n\t}\n\n\tcfg := &api.ConfigMap{\n\t\tObjectMeta: api.ObjectMeta{\n\t\t\tName: \"valid-config-data\",\n\t\t\tNamespace: api.NamespaceDefault,\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"foo\": \"bar\",\n\t\t},\n\t}\n\n\tStrategy.PrepareForCreate(ctx, cfg)\n\n\terrs := Strategy.Validate(ctx, cfg)\n\tif len(errs) != 0 {\n\t\tt.Errorf(\"unexpected error validating %v\", errs)\n\t}\n\n\tnewCfg := &api.ConfigMap{\n\t\tObjectMeta: api.ObjectMeta{\n\t\t\tName: \"valid-config-data-2\",\n\t\t\tNamespace: api.NamespaceDefault,\n\t\t\tResourceVersion: \"4\",\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"invalidKey\": \"updatedValue\",\n\t\t},\n\t}\n\n\tStrategy.PrepareForUpdate(ctx, newCfg, cfg)\n\n\terrs = Strategy.ValidateUpdate(ctx, newCfg, cfg)\n\tif len(errs) == 0 {\n\t\tt.Errorf(\"Expected a validation error\")\n\t}\n}\n\n\n\nfunc TestSelectableFieldLabelConversions(t *testing.T) ", "output": "{\n\tapitesting.TestSelectableFieldLabelConversionsOfKind(t,\n\t\tapi.Registry.GroupOrDie(api.GroupName).GroupVersion.String(),\n\t\t\"ConfigMap\",\n\t\tConfigMapToSelectableFields(&api.ConfigMap{}),\n\t\tnil,\n\t)\n}"} {"input": "package models\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com/dchest/uniuri\"\n\t\"github.com/koding/bongo\"\n\t\"github.com/stvp/slug\"\n)\n\n\nfunc Slugify(message *ChannelMessage) (*ChannelMessage, error) {\n\n\tif message.TypeConstant != ChannelMessage_TYPE_POST {\n\t\treturn message, nil\n\t}\n\n\tslug.Replacement = '-'\n\tres := NewChannelMessage()\n\n\tsuggestedSlug := slug.Clean(message.Body)\n\tif len(suggestedSlug) > 80 {\n\t\tsuggestedSlug = suggestedSlug[:79]\n\t}\n\n\tquery := map[string]interface{}{\n\t\t\"slug\": suggestedSlug,\n\t}\n\n\trand.Seed(time.Now().UnixNano())\n\n\tfor tryCount := 0; tryCount < 10; tryCount++ {\n\t\tif err := res.One(bongo.NewQS(query)); err != nil {\n\t\t\tif err != bongo.RecordNotFound {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tmessage.Slug = suggestedSlug\n\t\t\treturn message, nil\n\t\t}\n\t\tsuggestedSlug = suggestedSlug + \"-\" + strconv.Itoa(rand.Intn(1000000000))\n\t\tquery[\"slug\"] = suggestedSlug\n\t}\n\n\treturn nil, fmt.Errorf(\"couldnt generate unique slug:%s\", message.Slug)\n}\n\nfunc RandomName() string {\n\treturn uniuri.New()\n}\n\n\n\nfunc ZeroDate() time.Time {\n\treturn time.Date(1, time.January, 1, 0, 0, 0, 0, time.UTC)\n}\n\nfunc RandomGroupName() string ", "output": "{\n\trand.Seed(time.Now().UnixNano())\n\treturn \"group\" + strconv.FormatInt(rand.Int63(), 10)\n}"} {"input": "package triegen\n\n\n\nimport \"io\"\n\n\n\n\n\ntype Compacter interface {\n\tSize(v []uint64) (sz int, ok bool)\n\n\tStore(v []uint64) uint32\n\n\tPrint(w io.Writer) error\n\n\tHandler() string\n}\n\n\n\ntype simpleCompacter builder\n\nfunc (b *simpleCompacter) Size([]uint64) (sz int, ok bool) {\n\treturn blockSize * b.ValueSize, true\n}\n\nfunc (b *simpleCompacter) Store(v []uint64) uint32 {\n\th := uint32(len(b.ValueBlocks) - blockOffset)\n\tb.ValueBlocks = append(b.ValueBlocks, v)\n\treturn h\n}\n\nfunc (b *simpleCompacter) Print(io.Writer) error {\n\treturn nil\n}\n\n\n\nfunc (b *simpleCompacter) Handler() string ", "output": "{\n\tpanic(\"Handler should be special-cased for this Compacter\")\n}"} {"input": "package configfiles\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\n\t\"k8s.io/apimachinery/pkg/runtime/serializer\"\n\t\"k8s.io/kubernetes/pkg/kubelet/apis/kubeletconfig\"\n\tkubeletscheme \"k8s.io/kubernetes/pkg/kubelet/apis/kubeletconfig/scheme\"\n\tutilcodec \"k8s.io/kubernetes/pkg/kubelet/kubeletconfig/util/codec\"\n\tutilfs \"k8s.io/kubernetes/pkg/util/filesystem\"\n)\n\nconst kubeletFile = \"kubelet\"\n\n\ntype Loader interface {\n\tLoad() (*kubeletconfig.KubeletConfiguration, error)\n}\n\n\ntype fsLoader struct {\n\tfs utilfs.Filesystem\n\tkubeletCodecs *serializer.CodecFactory\n\tconfigDir string\n}\n\n\nfunc NewFsLoader(fs utilfs.Filesystem, configDir string) (Loader, error) {\n\t_, kubeletCodecs, err := kubeletscheme.NewSchemeAndCodecs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &fsLoader{\n\t\tfs: fs,\n\t\tkubeletCodecs: kubeletCodecs,\n\t\tconfigDir: configDir,\n\t}, nil\n}\n\n\n\n\nfunc resolveRelativePaths(paths []*string, root string) {\n\tfor _, path := range paths {\n\t\tif len(*path) > 0 && !filepath.IsAbs(*path) {\n\t\t\t*path = filepath.Join(root, *path)\n\t\t}\n\t}\n}\n\nfunc (loader *fsLoader) Load() (*kubeletconfig.KubeletConfiguration, error) ", "output": "{\n\tpath := filepath.Join(loader.configDir, kubeletFile)\n\tdata, err := loader.fs.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read init config file %q, error: %v\", path, err)\n\t}\n\n\tif len(data) == 0 {\n\t\treturn nil, fmt.Errorf(\"init config file %q was empty, but some parameters are required\", path)\n\t}\n\n\tkc, err := utilcodec.DecodeKubeletConfiguration(loader.kubeletCodecs, data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresolveRelativePaths(kubeletconfig.KubeletConfigurationPathRefs(kc), loader.configDir)\n\treturn kc, nil\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"time\"\n\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/kubernetes\"\n\t\"k8s.io/client-go/pkg/api/v1\"\n\t\"k8s.io/client-go/tools/clientcmd\"\n)\n\n\nfunc getPods(lbls map[string]string, namespace string) (*v1.PodList, error) {\n\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", *kubeconfig)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tselector := labels.SelectorFromSet(labels.Set(lbls)).String()\n\treturn clientset.CoreV1().Pods(namespace).List(metav1.ListOptions{\n\t\tLabelSelector: selector,\n\t})\n\n}\n\n\ntype PodMetrics struct {\n\tMetrics []PodMetricsInfo `json:\"metrics\"`\n\tLatestTimestamp time.Time `json:\"latestTimestamp\"`\n\tContainer string\n\tPod string\n}\n\ntype PodMetricsInfo struct {\n\tTimestamp string `json:\"timestamp`\n\tValue int64 `json:\"value\"`\n}\n\n\n\n\n\nfunc getJSON(url string, target interface{}) error {\n\tmyClient := &http.Client{Timeout: 10 * time.Second}\n\tfmt.Println(url)\n\tr, err := myClient.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(r.Body)\n\tdefer r.Body.Close()\n\treturn json.NewDecoder(r.Body).Decode(target)\n}\n\nfunc getMetricsByPodName(podName string, namespace string) (*PodMetrics, time.Time, error) ", "output": "{\n\n\theapsterHost := \"http://localhost:8082\" \n\ttarget := fmt.Sprintf(\"%s/api/v1/model/namespaces/%s/pods/%s/metrics/cpu/usage_rate\", heapsterHost, namespace, podName)\n\tvar metrics PodMetrics\n\terr := getJSON(target, &metrics)\n\tif err != nil {\n\t\treturn nil, time.Time{}, fmt.Errorf(\"failed to unmarshal heapster response: %v\", err)\n\t}\n\tmetrics.Pod = podName\n\treturn &metrics, time.Time{}, nil\n}"} {"input": "package main\n\nimport (\n\t\"github.com/go-martini/martini\"\n\t\"github.com/martini-contrib/render\"\n)\n\nfunc main() {\n\n\tm := martini.Classic()\n\n\tStaticOptions := martini.StaticOptions{Prefix: \"public\"}\n\tm.Use(martini.Static(\"public\", StaticOptions))\n\tm.Use(martini.Static(\"public\", StaticOptions))\n\tm.Use(martini.Static(\"public\", StaticOptions))\n\tm.Use(martini.Static(\"public\", StaticOptions))\n\n\tm.Use(render.Renderer(render.Options{\n\t\tDirectory: \"templates\", \n\t\tLayout: \"layout\", \n\t\tExtensions: []string{\".tmpl\"}, \n\t\tCharset: \"UTF-8\", \n\t}))\n\n\tm.Get(\"/\", IndexRouter)\n\tm.Get(\"/about\", AboutRoute)\n\tm.Get(\"/contact\", ContactRoute)\n\tm.Get(\"/signin\", SigninRoute)\n\tm.Get(\"/signup\", SignupRoute)\n\n\tm.Run()\n}\n\n\n\nfunc AboutRoute(r render.Render) {\n\tr.HTML(200, \"home/about\", nil)\n}\n\nfunc ContactRoute(r render.Render) {\n\tr.HTML(200, \"home/contact\", nil)\n}\n\nfunc SigninRoute(r render.Render) {\n\tr.HTML(200, \"account/signin\", nil)\n}\n\nfunc SignupRoute(r render.Render) {\n\tr.HTML(200, \"account/signup\", nil)\n}\n\nfunc IndexRouter(r render.Render) ", "output": "{\n\tr.HTML(200, \"home/index\", nil)\n}"} {"input": "package bunyan\n\nimport \"fmt\"\n\n\ntype Logger struct {\n\tsink Sink\n\trecord Record\n}\n\n\nfunc NewLogger(target Sink) *Logger {\n\treturn &Logger{target, NewRecord()}\n}\n\n\n\nfunc (l *Logger) Write(record Record) error {\n\trecord.TemplateMerge(l.record)\n\treturn l.sink.Write(record)\n}\n\n\n\nfunc (l *Logger) Include(info Info) Log {\n\treturn NewLogger(InfoSink(l, info))\n}\n\n\n\nfunc (l *Logger) Record(key string, value interface{}) Log {\n\tbuilder := NewLogger(l)\n\tbuilder.record[key] = value\n\treturn builder\n}\n\n\n\nfunc (l *Logger) Recordf(key, value string, args ...interface{}) Log {\n\treturn l.Record(key, fmt.Sprintf(value, args...))\n}\n\n\n\nfunc (l *Logger) Child() Log {\n\treturn NewLogger(l)\n}\n\nfunc (l *Logger) Tracef(msg string, args ...interface{}) { l.send(TRACE, msg, args...) }\n\nfunc (l *Logger) Infof(msg string, args ...interface{}) { l.send(INFO, msg, args...) }\nfunc (l *Logger) Warnf(msg string, args ...interface{}) { l.send(WARN, msg, args...) }\nfunc (l *Logger) Errorf(msg string, args ...interface{}) { l.send(ERROR, msg, args...) }\nfunc (l *Logger) Fatalf(msg string, args ...interface{}) { l.send(FATAL, msg, args...) }\n\nfunc (l *Logger) send(level Level, msg string, args ...interface{}) {\n\trecord := NewRecord()\n\trecord.SetMessagef(level, msg, args...)\n\te := l.Write(record)\n\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}\n\nfunc (l *Logger) Debugf(msg string, args ...interface{}) ", "output": "{ l.send(DEBUG, msg, args...) }"} {"input": "package airac\n\nimport (\n\t\"math\"\n\t\"testing\"\n\n\t\"github.com/jwkohnen/airac/proto\"\n)\n\nfunc TestProto(t *testing.T) {\n\tfor want := AIRAC(0); want < FromStringMust(\"9213\"); want++ {\n\t\tp := want.Proto()\n\t\tgot := FromProto(p)\n\t\tif want != got {\n\t\t\tt.Errorf(\"Want %v, got %x\", want, got)\n\t\t}\n\t}\n}\n\n\n\nfunc TestProtoOverflow(t *testing.T) ", "output": "{\n\twant := AIRAC(0)\n\tp := proto.AiracMessage{Airac19010110: math.MaxUint16 + 1}\n\tgot := FromProto(p)\n\tif got != want {\n\t\tt.Errorf(\"Want %s, got %s\", want, got)\n\t}\n}"} {"input": "package api2go\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\n\ntype APIContextAllocatorFunc func(*API) APIContexter\n\n\ntype APIContexter interface {\n\tcontext.Context\n\tSet(key string, value interface{})\n\tGet(key string) (interface{}, bool)\n\tReset()\n}\n\n\ntype APIContext struct {\n\tkeys map[string]interface{}\n}\n\n\nfunc (c *APIContext) Set(key string, value interface{}) {\n\tif c.keys == nil {\n\t\tc.keys = make(map[string]interface{})\n\t}\n\tc.keys[key] = value\n}\n\n\nfunc (c *APIContext) Get(key string) (value interface{}, exists bool) {\n\tif c.keys != nil {\n\t\tvalue, exists = c.keys[key]\n\t}\n\treturn\n}\n\n\nfunc (c *APIContext) Reset() {\n\tc.keys = nil\n}\n\n\nfunc (c *APIContext) Deadline() (deadline time.Time, ok bool) {\n\treturn\n}\n\n\nfunc (c *APIContext) Done() <-chan struct{} {\n\treturn nil\n}\n\n\nfunc (c *APIContext) Err() error {\n\treturn nil\n}\n\n\nfunc (c *APIContext) Value(key interface{}) interface{} {\n\tif keyAsString, ok := key.(string); ok {\n\t\tval, _ := c.Get(keyAsString)\n\t\treturn val\n\t}\n\treturn nil\n}\n\n\nvar _ APIContexter = &APIContext{}\n\n\n\n\nfunc ContextQueryParams(c *APIContext) map[string][]string ", "output": "{\n\tqp, ok := c.Get(\"QueryParams\")\n\tif ok == false {\n\t\tqp = make(map[string][]string)\n\t\tc.Set(\"QueryParams\", qp)\n\t}\n\treturn qp.(map[string][]string)\n}"} {"input": "package alert\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/opsgenie/opsgenie-go-sdk-v2/client\"\n\t\"github.com/pkg/errors\"\n)\n\ntype DeleteAttachmentRequest struct {\n\tclient.BaseRequest\n\tIdentifierType AlertIdentifier\n\tIdentifierValue string\n\tAttachmentId string\n\tUser string\n}\n\n\n\nfunc (r *DeleteAttachmentRequest) ResourcePath() string {\n\n\treturn \"/v2/alerts/\" + r.IdentifierValue + \"/attachments/\" + r.AttachmentId\n}\n\nfunc (r *DeleteAttachmentRequest) Method() string {\n\treturn http.MethodDelete\n}\n\nfunc (r *DeleteAttachmentRequest) RequestParams() map[string]string {\n\n\tparams := make(map[string]string)\n\n\tif r.IdentifierType == ALIAS {\n\t\tparams[\"alertIdentifierType\"] = \"alias\"\n\n\t} else if r.IdentifierType == TINYID {\n\t\tparams[\"alertIdentifierType\"] = \"tiny\"\n\n\t} else {\n\t\tparams[\"alertIdentifierType\"] = \"id\"\n\n\t}\n\n\tif r.User != \"\" {\n\t\tparams[\"user\"] = r.User\n\t}\n\n\treturn params\n}\n\nfunc (r *DeleteAttachmentRequest) Validate() error ", "output": "{\n\tif r.AttachmentId == \"\" {\n\t\treturn errors.New(\"AttachmentId can not be empty\")\n\t}\n\n\tif r.IdentifierValue == \"\" {\n\t\treturn errors.New(\"Identifier can not be empty\")\n\t}\n\treturn nil\n}"} {"input": "package bridge\n\nimport \"github.com/vishvananda/netlink\"\n\nfunc setupVerifyAndReconcile(config *NetworkConfiguration, i *bridgeInterface) error {\n\taddrv4, addrsv6, err := i.addresses()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif addrv4.IPNet == nil {\n\t\treturn ErrNoIPAddr\n\t}\n\n\tif config.AddressIPv4 != nil && !addrv4.IP.Equal(config.AddressIPv4.IP) {\n\t\treturn &IPv4AddrNoMatchError{ip: addrv4.IP, cfgIP: config.AddressIPv4.IP}\n\t}\n\n\tif config.EnableIPv6 && !findIPv6Address(netlink.Addr{IPNet: bridgeIPv6}, addrsv6) {\n\t\treturn (*IPv6AddrNoMatchError)(bridgeIPv6)\n\t}\n\n\ti.bridgeIPv4 = addrv4.IPNet\n\ti.bridgeIPv6 = bridgeIPv6\n\n\treturn nil\n}\n\n\n\nfunc findIPv6Address(addr netlink.Addr, addresses []netlink.Addr) bool ", "output": "{\n\tfor _, addrv6 := range addresses {\n\t\tif addrv6.String() == addr.String() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package eureka\n\nimport (\n\t\"encoding/xml\"\n\t\"strings\"\n)\n\nfunc (c *Client) GetApplications() (*Applications, error) {\n\tresponse, err := c.Get(\"apps\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar applications *Applications = new(Applications)\n\terr = xml.Unmarshal(response.Body, applications)\n\treturn applications, err\n}\n\nfunc (c *Client) GetApplication(appId string) (*Application, error) {\n\tvalues := []string{\"apps\", appId}\n\tpath := strings.Join(values, \"/\")\n\tresponse, err := c.Get(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar application *Application = new(Application)\n\terr = xml.Unmarshal(response.Body, application)\n\treturn application, err\n}\n\nfunc (c *Client) GetInstance(appId, instanceId string) (*InstanceInfo, error) {\n\tvalues := []string{\"apps\", appId, instanceId}\n\tpath := strings.Join(values, \"/\")\n\tresponse, err := c.Get(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar instance *InstanceInfo = new(InstanceInfo)\n\terr = xml.Unmarshal(response.Body, instance)\n\treturn instance, err\n}\n\n\n\nfunc (c *Client) GetSVIP(svipId string) (*Applications, error) {\n\tvalues := []string{\"svips\", svipId}\n\tpath := strings.Join(values, \"/\")\n\tresponse, err := c.Get(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar applications *Applications = new(Applications)\n\terr = xml.Unmarshal(response.Body, applications)\n\treturn applications, err\n}\n\nfunc (c *Client) GetVIP(vipId string) (*Applications, error) ", "output": "{\n\tvalues := []string{\"vips\", vipId}\n\tpath := strings.Join(values, \"/\")\n\tresponse, err := c.Get(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar applications *Applications = new(Applications)\n\terr = xml.Unmarshal(response.Body, applications)\n\treturn applications, err\n}"} {"input": "package godecode\n\nimport \"testing\"\n\n\nfunc TestInitals(t *testing.T) {\n\tvar gd GoDecode\n\tgd.Init(\"data\")\n\tm := make(map[string]string)\n\tm[\"Hello world.\"] = \"Hw\"\n\tm[\"南无阿弥陀佛\"] = \"NWAMTF\"\n\tm[\"Κνωσός\"] = \"K\"\n\tm[\"あみだにょらい\"] = \"a\"\n\tm[\"小小姑娘\\n清早起床\\n\\r提着花篮\\t上市场。\"] = \"XXGN\\nQZQC\\n\\rTZHL\\tSSC\"\n\tfor k, v := range m {\n\t\tif gd.Initials(k) != v {\n\t\t\tt.Errorf(\"[ %s ] Error: [ %s ] != [ %s ]\", k, v, gd.Initials(k))\n\t\t}\n\t}\n}\n\nfunc TestDecode(t *testing.T) ", "output": "{\n\tvar gd GoDecode\n\tgd.Init(\"data\")\n\tm := make(map[string]string)\n\tm[\"hello world\"] = \"hello world\"\n\tm[\"南无阿弥陀佛\"] = \"Nan Wu A Mi Tuo Fo\"\n\tm[\"Κνωσός\"] = \"Knosos\"\n\tm[\"あみだにょらい\"] = \"amidaniyorai\"\n\tfor k, v := range m {\n\t\tif gd.Decode(k) != v {\n\t\t\tt.Errorf(\"[ %s ] Error: [ %s ] != [ %s ]\", k, v, gd.Decode(k))\n\t\t}\n\t}\n}"} {"input": "package lht\n\nimport \"testing\"\n\n\n\nfunc Test_findLHS(t *testing.T) ", "output": "{\n\tnums := []int{1, 3, 2, 2, 5, 2, 3, 7}\n\tif r := findLHS(nums); r != 5 {\n\t\tt.Fatal(nums, r)\n\t}\n}"} {"input": "package db\n\nimport (\n\t\"github.com/couchbase/go-couchbase\"\n\n\t\"github.com/couchbase/sync_gateway/base\"\n)\n\n\n\n\n\n\nfunc (c *DatabaseContext) assimilate(docid string) {\n\tbase.LogTo(\"CRUD\", \"Importing new doc %q\", docid)\n\tdb := Database{DatabaseContext: c, user: nil}\n\t_, err := db.updateDoc(docid, true, func(doc *document) (Body, error) {\n\t\tif doc.hasValidSyncData(c.writeSequences()) {\n\t\t\treturn nil, couchbase.UpdateCancel \n\t\t}\n\t\tif err := db.initializeSyncData(doc); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn doc.body, nil\n\t})\n\tif err != nil && err != couchbase.UpdateCancel {\n\t\tbase.Warn(\"Failed to import new doc %q: %v\", docid, err)\n\t}\n}\n\nfunc (c *DatabaseContext) watchDocChanges() ", "output": "{\n\tif c.tapListener.DocChannel == nil {\n\t\treturn\n\t}\n\tbase.LogTo(\"Shadow\", \"Watching doc changes...\")\n\tfor event := range c.tapListener.DocChannel {\n\t\tdoc, err := unmarshalDocument(string(event.Key), event.Value)\n\t\tif err == nil {\n\t\t\tif doc.hasValidSyncData(c.writeSequences()) {\n\t\t\t\tif c.Shadower != nil {\n\t\t\t\t\tc.Shadower.PushRevision(doc)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif c.autoImport {\n\t\t\t\t\tgo c.assimilate(doc.ID)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"context\"\n\n\t\"github.com/go-openapi/strfmt\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\n\ntype Ddns struct {\n\n\tEnabled *bool `json:\"enabled,omitempty\"`\n\n\tFqdn string `json:\"fqdn,omitempty\"`\n\n\tSkipFqdnValidation *bool `json:\"skip_fqdn_validation,omitempty\"`\n\n\tTimeToLive *string `json:\"time_to_live,omitempty\"`\n\n\tUseSecure *bool `json:\"use_secure,omitempty\"`\n}\n\n\n\n\n\nfunc (m *Ddns) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}\n\n\nfunc (m *Ddns) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\nfunc (m *Ddns) UnmarshalBinary(b []byte) error {\n\tvar res Ddns\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *Ddns) Validate(formats strfmt.Registry) error ", "output": "{\n\treturn nil\n}"} {"input": "package personal\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n)\n\ntype FriendsArray []Friend\n\nfunc (self FriendsArray) String() (s string) {\n\ts = \"[\"\n\ti := 0\n\tm := len(self)\n\tfor _, f := range self {\n\t\tt := fmt.Sprintf(\n\t\t\t`{\"expertise\":\"%s\", \"name\":\"%s\", \"userid\":%d, \"gender\":%d, \"portrait\" : \"%s\"}`,\n\t\t\tf.Expertise, f.Name, f.UserId, f.Gender, f.Portrait)\n\t\ts += t\n\t\tif i != m-1 {\n\t\t\ts += \",\"\n\t\t}\n\t\ti++\n\t}\n\ts += \"]\"\n\n\treturn\n}\n\ntype FriendsList struct {\n\tXMLName xml.Name `xml:\"oschina\"`\n\tFriends Friends `xml:\"friends\"`\n}\n\ntype Friends struct {\n\tFriendsArray FriendsArray `xml:\"friend\"`\n}\n\n\n\ntype Friend struct {\n\tExpertise string `xml:\"expertise\"`\n\tName string `xml:\"name\"`\n\tUserId int `xml:\"userid\"`\n\tGender int `xml:\"gender\"` \n\tPortrait string `xml:\"portrait\"`\n}\n\nfunc (self Friend) String() (s string) {\n\tjson, _ := xml.Marshal(&self)\n\ts = string(json)\n\treturn\n}\n\nfunc (self FriendsList) StringFriendsArray() (s string) ", "output": "{\n\treturn self.Friends.FriendsArray.String()\n}"} {"input": "package retry\n\nimport (\n\t\"time\"\n)\n\ntype strategyFunc func(now time.Time) Timer\n\n\nfunc (f strategyFunc) NewTimer(now time.Time) Timer {\n\treturn f(now)\n}\n\n\n\n\nfunc LimitCount(n int, strategy Strategy) Strategy {\n\treturn strategyFunc(func(now time.Time) Timer {\n\t\treturn &countLimitTimer{\n\t\t\ttimer: strategy.NewTimer(now),\n\t\t\tremain: n,\n\t\t}\n\t})\n}\n\ntype countLimitTimer struct {\n\ttimer Timer\n\tremain int\n}\n\n\n\n\n\nfunc LimitTime(limit time.Duration, strategy Strategy) Strategy {\n\treturn strategyFunc(func(now time.Time) Timer {\n\t\treturn &timeLimitTimer{\n\t\t\ttimer: strategy.NewTimer(now),\n\t\t\tend: now.Add(limit),\n\t\t}\n\t})\n}\n\ntype timeLimitTimer struct {\n\ttimer Timer\n\tend time.Time\n}\n\nfunc (t *timeLimitTimer) NextSleep(now time.Time) (time.Duration, bool) {\n\tsleep, ok := t.timer.NextSleep(now)\n\tif ok && now.Add(sleep).After(t.end) {\n\t\treturn 0, false\n\t}\n\treturn sleep, ok\n}\n\nfunc (t *countLimitTimer) NextSleep(now time.Time) (time.Duration, bool) ", "output": "{\n\tif t.remain--; t.remain <= 0 {\n\t\treturn 0, false\n\t}\n\treturn t.timer.NextSleep(now)\n}"} {"input": "package gobacktest\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestTickPrice(t *testing.T) ", "output": "{\n\tvar testCases = []struct {\n\t\tmsg string\n\t\ttick Tick\n\t\texp float64\n\t}{\n\t\t{\"Empty Tick:\",\n\t\t\tTick{Bid: 0, Ask: 0},\n\t\t\t0,\n\t\t},\n\t\t{\"Standard Tick:\",\n\t\t\tTick{Bid: 10, Ask: 5},\n\t\t\t7.5,\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tfloat := tc.tick.Price()\n\t\tif float != tc.exp {\n\t\t\tt.Errorf(\"%v LatestPrice(): \\nexpected %#v, \\nactual %#v\", tc.msg, tc.exp, float)\n\t\t}\n\t}\n}"} {"input": "package safepackets\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\n\t\"github.com/mark-rushakoff/go_tftpd/packets\"\n)\n\ntype SafeError struct {\n\tCode packets.ErrorCode\n\tMessage string\n}\n\nfunc NewFileNotFoundError() *SafeError {\n\treturn &SafeError{\n\t\tCode: packets.FileNotFound,\n\t\tMessage: \"File not found\",\n\t}\n}\n\nfunc NewAccessViolationError(message string) *SafeError {\n\treturn &SafeError{\n\t\tCode: packets.AccessViolation,\n\t\tMessage: message,\n\t}\n}\n\nfunc NewAncientAckError() *SafeError {\n\treturn &SafeError{\n\t\tCode: packets.Undefined,\n\t\tMessage: \"Received unexpectedly old Ack\",\n\t}\n}\n\n\n\nfunc (e *SafeError) Bytes() []byte {\n\tbuf := &bytes.Buffer{}\n\tbinary.Write(buf, binary.BigEndian, packets.ErrorOpcode)\n\tbinary.Write(buf, binary.BigEndian, e.Code)\n\tbuf.WriteString(e.Message)\n\tbuf.WriteByte(0)\n\treturn buf.Bytes()\n}\n\nfunc (e *SafeError) Equals(other *SafeError) bool ", "output": "{\n\treturn e.Code == other.Code && e.Message == other.Message\n}"} {"input": "package runtime\n\nimport _ \"unsafe\" \n\nfunc cmpstring(s1, s2 string) int {\n\tl := len(s1)\n\tif len(s2) < l {\n\t\tl = len(s2)\n\t}\n\tfor i := 0; i < l; i++ {\n\t\tc1, c2 := s1[i], s2[i]\n\t\tif c1 < c2 {\n\t\t\treturn -1\n\t\t}\n\t\tif c1 > c2 {\n\t\t\treturn +1\n\t\t}\n\t}\n\tif len(s1) < len(s2) {\n\t\treturn -1\n\t}\n\tif len(s1) > len(s2) {\n\t\treturn +1\n\t}\n\treturn 0\n}\n\n\n\n\nfunc bytes_Compare(s1, s2 []byte) int ", "output": "{\n\tl := len(s1)\n\tif len(s2) < l {\n\t\tl = len(s2)\n\t}\n\tif l == 0 || &s1[0] == &s2[0] {\n\t\tgoto samebytes\n\t}\n\tfor i := 0; i < l; i++ {\n\t\tc1, c2 := s1[i], s2[i]\n\t\tif c1 < c2 {\n\t\t\treturn -1\n\t\t}\n\t\tif c1 > c2 {\n\t\t\treturn +1\n\t\t}\n\t}\nsamebytes:\n\tif len(s1) < len(s2) {\n\t\treturn -1\n\t}\n\tif len(s1) > len(s2) {\n\t\treturn +1\n\t}\n\treturn 0\n}"} {"input": "package stats\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"sync\"\n\n\tmultierror \"github.com/hashicorp/go-multierror\"\n\t\"github.com/shirou/gopsutil/cpu\"\n)\n\nvar (\n\tcpuMhzPerCore float64\n\tcpuModelName string\n\tcpuNumCores int\n\tcpuTotalTicks float64\n\n\tinitErr error\n\tonceLer sync.Once\n)\n\nfunc Init() error {\n\tonceLer.Do(func() {\n\t\tvar merrs *multierror.Error\n\t\tvar err error\n\t\tif cpuNumCores, err = cpu.Counts(true); err != nil {\n\t\t\tmerrs = multierror.Append(merrs, fmt.Errorf(\"Unable to determine the number of CPU cores available: %v\", err))\n\t\t}\n\n\t\tvar cpuInfo []cpu.InfoStat\n\t\tif cpuInfo, err = cpu.Info(); err != nil {\n\t\t\tmerrs = multierror.Append(merrs, fmt.Errorf(\"Unable to obtain CPU information: %v\", initErr))\n\t\t}\n\n\t\tfor _, cpu := range cpuInfo {\n\t\t\tcpuModelName = cpu.ModelName\n\t\t\tcpuMhzPerCore = cpu.Mhz\n\t\t\tbreak\n\t\t}\n\n\t\tcpuMhzPerCore = math.Floor(cpuMhzPerCore)\n\t\tcpuTotalTicks = math.Floor(float64(cpuNumCores) * cpuMhzPerCore)\n\n\t\tinitErr = merrs.ErrorOrNil()\n\t})\n\treturn initErr\n}\n\n\n\n\n\nfunc CPUMHzPerCore() float64 {\n\treturn cpuMhzPerCore\n}\n\n\nfunc CPUModelName() string {\n\treturn cpuModelName\n}\n\n\nfunc TotalTicksAvailable() float64 {\n\treturn cpuTotalTicks\n}\n\nfunc CPUNumCores() int ", "output": "{\n\treturn cpuNumCores\n}"} {"input": "package state\n\nimport (\n\t\"time\"\n\n\t\"github.com/juju/errors\"\n\t\"gopkg.in/juju/names.v2\"\n\n\t\"github.com/juju/juju/core/lease\"\n)\n\n\n\n\n\n\n\n\n\ntype singularSecretary struct {\n\tuuid string\n}\n\n\nfunc (s singularSecretary) CheckLease(name string) error {\n\tif name != s.uuid {\n\t\treturn errors.New(\"expected environ UUID\")\n\t}\n\treturn nil\n}\n\n\nfunc (s singularSecretary) CheckHolder(name string) error {\n\tif _, err := names.ParseMachineTag(name); err != nil {\n\t\treturn errors.New(\"expected machine tag\")\n\t}\n\treturn nil\n}\n\n\nfunc (s singularSecretary) CheckDuration(duration time.Duration) error {\n\tif duration <= 0 {\n\t\treturn errors.NewNotValid(nil, \"non-positive\")\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc (st *State) SingularClaimer() lease.Claimer ", "output": "{\n\treturn st.workers.singularManager()\n}"} {"input": "package wkb\n\nimport (\n\t\"encoding/binary\"\n\t\"github.com/foobaz/geom\"\n\t\"io\"\n)\n\n\n\nfunc writeMultiPoint(w io.Writer, byteOrder binary.ByteOrder, axes uint32, multiPoint geom.MultiPoint) error {\n\tif err := binary.Write(w, byteOrder, uint32(len(multiPoint))); err != nil {\n\t\treturn err\n\t}\n\tfor _, point := range multiPoint {\n\t\tif err := Write(w, byteOrder, axes, point); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc multiPointReader(r io.Reader, byteOrder binary.ByteOrder, dimension int) (geom.T, error) ", "output": "{\n\tvar numPoints uint32\n\tif err := binary.Read(r, byteOrder, &numPoints); err != nil {\n\t\treturn nil, err\n\t}\n\tpoints := make([]geom.Point, numPoints)\n\tfor i := range points {\n\t\tif g, err := Read(r); err == nil {\n\t\t\tvar ok bool\n\t\t\tpoints[i], ok = g.(geom.Point)\n\t\t\tif !ok {\n\t\t\t\treturn nil, &UnexpectedGeometryError{g}\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn geom.MultiPoint(points), nil\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"math\"\n)\n\nfunc main() {\n\tfmt.Print(\"First example with -1: \")\n\tret1, err1 := MySqrt(-1)\n\tif err1 != nil {\n\t\tfmt.Println(\"Error! Return values are: \", ret1, err1)\n\t} else {\n\t\tfmt.Println(\"It's ok! Return values are: \", ret1, err1)\n\t}\n\n\tfmt.Print(\"Second example with 5: \")\n\tif ret2, err2 := MySqrt(5); err2 != nil {\n\t\tfmt.Println(\"Error! Return values are: \", ret2, err2)\n\t} else {\n\t\tfmt.Println(\"It's ok! Return values are: \", ret2, err2)\n\t}\n\tfmt.Println(MySqrt2(5))\n}\n\n\n\n\nfunc MySqrt2(f float64) (ret float64, err error) {\n\tif f < 0 {\n\t\tret = float64(math.NaN())\n\t\terr = errors.New(\"I won't be able to do a sqrt of negative number!\")\n\t} else {\n\t\tret = math.Sqrt(f)\n\t}\n\treturn\n}\n\nfunc MySqrt(f float64) (float64, error) ", "output": "{\n\tif f < 0 {\n\t\treturn float64(math.NaN()), errors.New(\"I won't be able to do a sqrt of negative number!\")\n\t}\n\treturn math.Sqrt(f), nil\n}"} {"input": "package wire_test\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n\n\ntype fixedWriter struct {\n\tb []byte\n\tpos int\n}\n\n\n\n\n\n\nfunc (w *fixedWriter) Write(p []byte) (n int, err error) {\n\tlenp := len(p)\n\tif w.pos+lenp > cap(w.b) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\tn = lenp\n\tw.pos += copy(w.b[w.pos:], p)\n\treturn\n}\n\n\nfunc (w *fixedWriter) Bytes() []byte {\n\treturn w.b\n}\n\n\n\nfunc newFixedWriter(max int) io.Writer {\n\tb := make([]byte, max, max)\n\tfw := fixedWriter{b, 0}\n\treturn &fw\n}\n\n\n\ntype fixedReader struct {\n\tbuf []byte\n\tpos int\n\tiobuf *bytes.Buffer\n}\n\n\n\n\n\n\n\n\n\n\nfunc newFixedReader(max int, buf []byte) io.Reader {\n\tb := make([]byte, max, max)\n\tif buf != nil {\n\t\tcopy(b[:], buf)\n\t}\n\n\tiobuf := bytes.NewBuffer(b)\n\tfr := fixedReader{b, 0, iobuf}\n\treturn &fr\n}\n\nfunc (fr *fixedReader) Read(p []byte) (n int, err error) ", "output": "{\n\tn, err = fr.iobuf.Read(p)\n\tfr.pos += n\n\treturn\n}"} {"input": "package disk\n\nimport (\n\t\"context\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\n\n\n\n\n\nfunc UsageWithContext(ctx context.Context, path string) (*UsageStat, error) {\n\tstat := unix.Statfs_t{}\n\terr := unix.Statfs(path, &stat)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbsize := stat.Bsize\n\n\tret := &UsageStat{\n\t\tPath: path,\n\t\tFstype: getFsType(stat),\n\t\tTotal: (uint64(stat.Blocks) * uint64(bsize)),\n\t\tFree: (uint64(stat.Bavail) * uint64(bsize)),\n\t\tInodesTotal: (uint64(stat.Files)),\n\t\tInodesFree: (uint64(stat.Ffree)),\n\t}\n\n\tif ret.InodesTotal < ret.InodesFree {\n\t\treturn ret, nil\n\t}\n\n\tret.InodesUsed = (ret.InodesTotal - ret.InodesFree)\n\tret.Used = (uint64(stat.Blocks) - uint64(stat.Bfree)) * uint64(bsize)\n\n\tif ret.InodesTotal == 0 {\n\t\tret.InodesUsedPercent = 0\n\t} else {\n\t\tret.InodesUsedPercent = (float64(ret.InodesUsed) / float64(ret.InodesTotal)) * 100.0\n\t}\n\n\tif ret.Total == 0 {\n\t\tret.UsedPercent = 0\n\t} else {\n\t\tret.UsedPercent = (float64(ret.Used) / float64(ret.Total)) * 100.0\n\t}\n\n\treturn ret, nil\n}\n\nfunc Usage(path string) (*UsageStat, error) ", "output": "{\n\treturn UsageWithContext(context.Background(), path)\n}"} {"input": "package main\n\nimport (\n\t\"github.com/robert-chiniquy/goose/lib/goose\"\n\t\"log\"\n)\n\nvar downCmd = &Command{\n\tName: \"down\",\n\tUsage: \"\",\n\tSummary: \"Roll back the version by 1\",\n\tHelp: `down extended help here...`,\n\tRun: downRun,\n}\n\n\n\nfunc downRun(cmd *Command, args ...string) ", "output": "{\n\n\tconf, err := dbConfFromFlags()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tcurrent, err := goose.GetDBVersion(conf)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tprevious, err := goose.GetPreviousDBVersion(conf.MigrationsDir, current)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif err = goose.RunMigrations(conf, conf.MigrationsDir, previous); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}"} {"input": "package collaboration\n\nimport \"sync\"\n\n\n\n\ntype memoryStorage struct {\n\tusers map[string]*Option\n\tsync.Mutex\n}\n\nfunc (m *memoryStorage) Get(username string) (*Option, error) {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\toption, ok := m.users[username]\n\tif !ok {\n\t\treturn nil, ErrUserNotFound\n\t}\n\n\treturn option, nil\n}\n\nfunc (m *memoryStorage) GetAll() (map[string]*Option, error) {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\treturn m.users, nil\n}\n\nfunc (m *memoryStorage) Set(username string, value *Option) error {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tm.users[username] = value\n\treturn nil\n}\n\nfunc (m *memoryStorage) Delete(username string) error {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tdelete(m.users, username)\n\treturn nil\n}\n\nfunc (m *memoryStorage) Close() error {\n\treturn nil\n}\n\nfunc NewMemoryStorage() *memoryStorage ", "output": "{\n\treturn &memoryStorage{\n\t\tusers: make(map[string]*Option),\n\t}\n}"} {"input": "package sample\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n)\n\ntype sampleState struct {\n\trate uint64\n\tseed int64\n\tsampleCount uint64\n\ttrueCount uint64\n\trnd *rand.Rand\n}\n\n\ntype Sampler interface {\n\tSample() bool\n\tSampleFrom(probe uint64) bool\n\tState\n}\n\n\ntype State interface {\n\tReset()\n\tString() string\n\tRate() uint64\n\tCalls() uint64\n\tCount() uint64\n}\n\nfunc (state *sampleState) Rate() uint64 {\n\tif state != nil {\n\t\treturn state.rate\n\t}\n\treturn 0\n}\n\nfunc (state *sampleState) Calls() uint64 {\n\tif state != nil {\n\t\treturn state.sampleCount\n\t}\n\treturn 0\n}\n\nfunc (state *sampleState) Count() uint64 {\n\tif state != nil {\n\t\treturn state.trueCount\n\t}\n\treturn 0\n}\n\nfunc (state *sampleState) Reset() {\n\tstate.rnd.Seed(state.seed)\n\tstate.sampleCount = 0\n\tstate.trueCount = 0\n}\n\nfunc (state *sampleState) String() string {\n\ttype X *sampleState\n\tx := X(state)\n\treturn fmt.Sprintf(\"%+v\", x)\n}\n\n\n\n\n\nfunc Stats(state State) string {\n\tif state != nil {\n\t\treturn fmt.Sprintf(\"Rate: %d, SampleCount: %d, TrueCount: %d, Deviation: %.4f%%\", state.Rate(), state.Calls(), state.Count(), Deviation(state)*100.0)\n\t}\n\treturn \"No state provided\"\n}\n\nfunc Deviation(state State) (deviation float64) ", "output": "{\n\tif state != nil && state.Count() > 0 {\n\t\tdeviation = 1.0 - 1.0/float64(state.Rate())*(float64(state.Calls())/float64(state.Count()))\n\t} else {\n\t\tdeviation = 1.0\n\t}\n\n\treturn\n}"} {"input": "package logrus\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\t\"runtime\"\n)\n\n\nfunc (logger *Logger) Writer() *io.PipeWriter {\n\treturn logger.WriterLevel(InfoLevel)\n}\n\n\n\n\n\n\nfunc (logger *Logger) WriterLevel(level Level) *io.PipeWriter {\n\treturn NewEntry(logger).WriterLevel(level)\n}\n\nfunc (entry *Entry) Writer() *io.PipeWriter {\n\treturn entry.WriterLevel(InfoLevel)\n}\n\n\n\nfunc (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) {\n\tscanner := bufio.NewScanner(reader)\n\tfor scanner.Scan() {\n\t\tprintFunc(scanner.Text())\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\tentry.Errorf(\"Error while reading from Writer: %s\", err)\n\t}\n\treader.Close()\n}\n\nfunc writerFinalizer(writer *io.PipeWriter) {\n\twriter.Close()\n}\n\nfunc (entry *Entry) WriterLevel(level Level) *io.PipeWriter ", "output": "{\n\treader, writer := io.Pipe()\n\n\tvar printFunc func(args ...interface{})\n\n\tswitch level {\n\tcase TraceLevel:\n\t\tprintFunc = entry.Trace\n\tcase DebugLevel:\n\t\tprintFunc = entry.Debug\n\tcase InfoLevel:\n\t\tprintFunc = entry.Info\n\tcase WarnLevel:\n\t\tprintFunc = entry.Warn\n\tcase ErrorLevel:\n\t\tprintFunc = entry.Error\n\tcase FatalLevel:\n\t\tprintFunc = entry.Fatal\n\tcase PanicLevel:\n\t\tprintFunc = entry.Panic\n\tdefault:\n\t\tprintFunc = entry.Print\n\t}\n\n\tgo entry.writerScanner(reader, printFunc)\n\truntime.SetFinalizer(writer, writerFinalizer)\n\n\treturn writer\n}"} {"input": "package common\n\nimport (\n\t\"github.com/pkg/errors\"\n)\n\ntype Backend interface {\n\tRenderAllScrolls() (numScrolls int, errors []error)\n\n\tRenderScrollsByID(ids []ID) (renderedScrollIDs []ID, errors []error)\n\n\tParse(id, doc string) Scroll\n}\n\n\n\n\n\nfunc FindMatchingScrolls(query string) ([]ID, int, error) {\n\tindex, err := OpenExistingIndex()\n\tif err != nil {\n\t\treturn []ID{}, 0, err\n\t}\n\tdefer index.Close()\n\n\tnewQuery := translatePlusMinusTildePrefixes(query)\n\tsearchResults, err := performQuery(index, newQuery)\n\ttotalMatches := int(searchResults.Total)\n\tif err != nil {\n\t\tif err.Error() == \"syntax error\" {\n\t\t\terr = errors.Wrapf(err, \"invalid query string: '%v'\", newQuery)\n\t\t} else {\n\t\t\terr = errors.Wrap(err, \"perform query\")\n\t\t}\n\t\treturn []ID{}, totalMatches, err\n\t}\n\n\tvar ids []ID\n\tfor _, match := range searchResults.Hits {\n\t\tid := ID(match.ID)\n\t\tids = append(ids, id)\n\t}\n\n\treturn ids, totalMatches, nil\n}\n\nfunc UpdateIndex(b Backend) error {\n\treturn updateIndex(b)\n}\n\nfunc ComputeStatistics() (Statistics, error) {\n\treturn computeStatistics()\n}\n\n\n\nfunc LoadScrolls(b Backend, ids []ID) ([]Scroll, error) ", "output": "{\n\tresult := make([]Scroll, len(ids))\n\tfor i, id := range ids {\n\t\tscroll, err := loadAndParseScrollContentByID(b, id)\n\t\tif err != nil {\n\t\t\treturn result, err\n\t\t}\n\t\tresult[i] = scroll\n\t}\n\treturn result, nil\n}"} {"input": "package metrics\n\nimport (\n\t\"sync\"\n\n\tprom \"github.com/prometheus/client_golang/prometheus\"\n\tlog \"github.com/sirupsen/logrus\"\n)\n\nconst (\n\tsandboxGuageName = \"bundlelib_sandbox\"\n)\n\nvar (\n\tonce sync.Once\n\tcollector *Collector\n)\n\n\ntype Collector struct {\n\tSandbox prom.Gauge\n}\n\n\n\n\nfunc recoverMetricPanic() {\n\tif r := recover(); r != nil {\n\t\tlog.Errorf(\"Recovering from metric function - %v\", r)\n\t}\n}\n\n\n\n\n\n\nfunc SandboxCreated() {\n\tdefer recoverMetricPanic()\n\tcollector.Sandbox.Inc()\n}\n\n\nfunc SandboxDeleted() {\n\tdefer recoverMetricPanic()\n\tcollector.Sandbox.Dec()\n}\n\n\nfunc (c Collector) Describe(ch chan<- *prom.Desc) {\n\tc.Sandbox.Describe(ch)\n}\n\n\nfunc (c Collector) Collect(ch chan<- prom.Metric) {\n\tc.Sandbox.Collect(ch)\n}\n\nfunc RegisterCollector() ", "output": "{\n\tonce.Do(func() {\n\t\tcollector = &Collector{\n\t\t\tSandbox: prom.NewGauge(prom.GaugeOpts{\n\t\t\t\tName: sandboxGuageName,\n\t\t\t\tHelp: \"Guage of all sandbox namespaces that are active.\",\n\t\t\t}),\n\t\t}\n\n\t\terr := prom.Register(collector)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"unable to register collector with prometheus: %v\", err)\n\t\t}\n\t})\n}"} {"input": "package util\n\nimport (\n\t\"crypto/rand\"\n)\n\n\n\n\nfunc RandString(n int) string ", "output": "{\n\tconst alphanum = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n\tvar bytes = make([]byte, n)\n\trand.Read(bytes)\n\tfor i, b := range bytes {\n\t\tbytes[i] = alphanum[b%byte(len(alphanum))]\n\t}\n\treturn string(bytes)\n}"} {"input": "package commands_test\n\nimport (\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/zetamatta/nyagos/commands\"\n)\n\n\n\nfunc TestFixPathCase(t *testing.T) {\n\torgPath, err := os.Getwd()\n\tif err != nil {\n\t\tt.Errorf(\"os.Getwd(): %v\", err)\n\t}\n\tchgPath := strings.ToUpper(orgPath)\n\tactPath := testFixPathCase(t, chgPath)\n\tif actPath != orgPath {\n\t\tt.Fatalf(\"CorrectCase('%s') == %s\", chgPath, actPath)\n\t}\n\tactPath = testFixPathCase(t, \"c:\\\\\")\n\tif actPath != `C:\\` {\n\t\tt.Fatalf(\"CorrectCase('c:\\\\') == '%s'\", actPath)\n\t}\n}\n\nfunc testFixPathCase(t *testing.T, path string) string ", "output": "{\n\tnewpath, err := commands.CorrectCase(path)\n\tif err != nil {\n\t\tt.Fatalf(\"CorrectCase: %v\", err.Error())\n\t}\n\treturn newpath\n}"} {"input": "package data\n\nimport (\n \"github.com/twitchyliquid64/CNC/registry/syscomponents\"\n)\n\nvar trackerObj DatabaseComponent\n\ntype DatabaseComponent struct{\n err error\n}\n\nfunc (d *DatabaseComponent)Name() string{\n return \"Database\"\n}\nfunc (d *DatabaseComponent)IconStr() string{\n return \"list\"\n}\nfunc (d *DatabaseComponent)IsNominal()bool{\n return d.err == nil\n}\nfunc (d *DatabaseComponent)IsDisabled()bool{\n return false\n}\nfunc (d *DatabaseComponent)IsFault()bool{\n return d.err != nil\n}\nfunc (d *DatabaseComponent)Error()string{\n if d.err == nil{\n return \"\"\n }\n return d.err.Error()\n}\nfunc (d *DatabaseComponent)SetError(e error){\n d.err = e\n}\n\nfunc trackingSetup(){\n trackerObj = DatabaseComponent{}\n syscomponents.Register(&trackerObj)\n}\n\n\n\nfunc tracking_notifyFault(err error)", "output": "{\n syscomponents.SetError(trackerObj.Name(), err)\n}"} {"input": "package thrift\n\nimport (\n\t\"net\"\n)\n\n\ntype socketConn struct {\n\tnet.Conn\n\n\tbuffer [1]byte\n}\n\nvar _ net.Conn = (*socketConn)(nil)\n\n\n\nfunc createSocketConnFromReturn(conn net.Conn, err error) (*socketConn, error) {\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &socketConn{\n\t\tConn: conn,\n\t}, nil\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc (sc *socketConn) isValid() bool {\n\treturn sc != nil && sc.Conn != nil\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc (sc *socketConn) IsOpen() bool {\n\tif !sc.isValid() {\n\t\treturn false\n\t}\n\treturn sc.checkConn() == nil\n}\n\n\n\n\n\n\n\n\n\n\nfunc (sc *socketConn) Read(p []byte) (n int, err error) {\n\tif len(p) == 0 {\n\t\treturn 0, sc.read0()\n\t}\n\n\treturn sc.Conn.Read(p)\n}\n\nfunc wrapSocketConn(conn net.Conn) *socketConn ", "output": "{\n\tif sc, ok := conn.(*socketConn); ok {\n\t\treturn sc\n\t}\n\n\treturn &socketConn{\n\t\tConn: conn,\n\t}\n}"} {"input": "package libra\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n)\n\ntype validator struct {\n\tname string\n\tprogram\n\tstdin io.Reader\n}\n\nfunc (v validator) Name() string {\n\treturn v.name\n}\n\n\n\ntype valJob struct {\n\tabstractJob\n\tinputs []Input\n}\n\n\ntype Input interface {\n\tName() string\n\tReader() io.Reader\n}\n\nfunc (job valJob) Subtasks() []Task {\n\tret := make([]Task, len(job.inputs))\n\tfor i, v := range job.inputs {\n\t\tprog, _ := newProgram(job.src.Exec)\n\t\tret[i] = validator{name: v.Name(), program: prog, stdin: v.Reader()}\n\t}\n\treturn ret\n}\n\n\nfunc ValJob(src Src, inputs []Input) Job {\n\tret := valJob{}\n\tret.src = src\n\tret.inputs = inputs\n\treturn ret\n}\n\nfunc (v validator) Run() Status ", "output": "{\n\tstdout := new(bytes.Buffer)\n\tstderr := new(bytes.Buffer)\n\tv.program.cmd.Stdin = v.stdin\n\tv.program.cmd.Stdout = stdout\n\tv.program.cmd.Stderr = stderr\n\tres := v.program.Run()\n\tif res.Code != OK {\n\t\treturn Status{\n\t\t\tCode: RE,\n\t\t\tMsg: fmt.Sprintf(\"%v\", stderr.String()),\n\t\t}\n\t}\n\treturn res\n}"} {"input": "package iso20022\n\n\ntype DeadlineCode4Choice struct {\n\n\tCode *CorporateActionDeadline1Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification47 `xml:\"Prtry\"`\n}\n\n\n\nfunc (d *DeadlineCode4Choice) AddProprietary() *GenericIdentification47 {\n\td.Proprietary = new(GenericIdentification47)\n\treturn d.Proprietary\n}\n\nfunc (d *DeadlineCode4Choice) SetCode(value string) ", "output": "{\n\td.Code = (*CorporateActionDeadline1Code)(&value)\n}"} {"input": "package main\n\nimport (\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n)\n\nfunc setupSignalHandlers() {\n\tsignalChan := make(chan os.Signal, 1)\n\tsignal.Notify(signalChan, os.Interrupt, os.Kill, syscall.SIGTERM)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase signal := <-signalChan:\n\t\t\t\tcui.ln(\"Received\", signal, \"- exiting...\")\n\t\t\t\tos.Exit(0)\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc fatalWithErr(desc string, err error) {\n\tcui.ln(desc)\n\tcui.ln(\"Reason:\", err)\n\tcui.ln(\"Bye...\")\n\tcui.ln(\"\")\n\tos.Exit(1)\n}\n\n\n\nfunc fatal(desc string) ", "output": "{\n\tcui.ln(desc)\n\tcui.ln(\"Bye...\")\n\tcui.ln(\"\")\n\tos.Exit(1)\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\nfunc TestPerimeter(t *testing.T) {\n\trectangle := Rectangle{10.0, 10.0}\n\tgot := Perimeter(rectangle)\n\twant := 40.0\n\n\tif got != want {\n\t\tt.Errorf(\"got %.2f want %.2f\", got, want)\n\t}\n}\n\n\n\nfunc TestArea(t *testing.T) ", "output": "{\n\n\tareaTests := []struct {\n\t\tshape Shape\n\t\twant float64\n\t}{\n\t\t{Rectangle{12, 6}, 72.0},\n\t\t{Circle{10}, 314.1592653589793},\n\t\t{Triangle{12, 6}, 36.0},\n\t}\n\n\tfor _, tt := range areaTests {\n\t\tgot := tt.shape.Area()\n\t\tif got != tt.want {\n\t\t\tt.Errorf(\"got %.2f want %.2f\", got, tt.want)\n\t\t}\n\t}\n\n}"} {"input": "package artifacts\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype RepositoryCollection struct {\n\n\tItems []RepositorySummary `mandatory:\"true\" json:\"items\"`\n}\n\nfunc (m RepositoryCollection) String() string {\n\treturn common.PointerString(m)\n}\n\n\n\n\nfunc (m *RepositoryCollection) UnmarshalJSON(data []byte) (e error) ", "output": "{\n\tmodel := struct {\n\t\tItems []repositorysummary `json:\"items\"`\n\t}{}\n\n\te = json.Unmarshal(data, &model)\n\tif e != nil {\n\t\treturn\n\t}\n\tvar nn interface{}\n\tm.Items = make([]RepositorySummary, len(model.Items))\n\tfor i, n := range model.Items {\n\t\tnn, e = n.UnmarshalPolymorphicJSON(n.JsonData)\n\t\tif e != nil {\n\t\t\treturn e\n\t\t}\n\t\tif nn != nil {\n\t\t\tm.Items[i] = nn.(RepositorySummary)\n\t\t} else {\n\t\t\tm.Items[i] = nil\n\t\t}\n\t}\n\n\treturn\n}"} {"input": "package public\n\nimport (\n . \"logger\"\n \"os\"\n \"os/signal\"\n \"sync\"\n)\n\nvar gLock=sync.Mutex{}\n\n\nfunc WaitForSig(exit chan bool) {\n defer (func(){\n exit<-false\n })()\n\n c:=make(chan os.Signal, 1)\n signal.Notify(c, os.Interrupt, os.Kill)\n\n for sig:=range c {\n if !OnSignaled(sig) {\n return\n }\n }\n}\n\nfunc OnSignaled(sig os.Signal) bool ", "output": "{\n gLock.Lock()\n \n Secretary.Log(\"mainpkg::Terminated\", \"Receive signal \"+sig.String())\n\n return false\n}"} {"input": "package registry\n\nimport (\n \"github.com/twitchyliquid64/CNC/plugin/exec\"\n)\n\n\nvar dispatchMethod func(string, interface{})bool = nil\nvar deregisterPluginMethod func (plugin *exec.Plugin) = nil\n\nfunc SetupDispatchMethod(in func(string, interface{})bool) {\n dispatchMethod = in\n}\n\nfunc SetupDeregisterMethod(in func (plugin *exec.Plugin)){\n deregisterPluginMethod = in\n}\n\nfunc DeregisterPluginMethod(plugin *exec.Plugin){\n if deregisterPluginMethod == nil{\n panic(\"deregisterPluginMethod == nil\")\n }\n deregisterPluginMethod(plugin)\n}\n\n\n\nfunc DispatchEvent(typ string, data interface{})bool", "output": "{\n if dispatchMethod != nil {\n return dispatchMethod(typ, data)\n }\n return false\n}"} {"input": "package client_test\n\nimport (\n\t\"github.com/jdextraze/go-gesclient/client\"\n\t\"testing\"\n)\n\nfunc TestWrongExpectedVersion_Error(t *testing.T) {\n\tif client.WrongExpectedVersion.Error() != \"Wrong expected version\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestStreamDeleted_Error(t *testing.T) {\n\tif client.StreamDeleted.Error() != \"Stream deleted\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestInvalidTransaction_Error(t *testing.T) {\n\tif client.InvalidTransaction.Error() != \"Invalid transaction\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestAccessDenied_Error(t *testing.T) {\n\tif client.AccessDenied.Error() != \"Access denied\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestAuthenticationError_Error(t *testing.T) {\n\tif client.AuthenticationError.Error() != \"Authentication error\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestBadRequest_Error(t *testing.T) {\n\tif client.BadRequest.Error() != \"Bad request\" {\n\t\tt.FailNow()\n\t}\n}\n\n\n\nfunc TestNotModified_Error(t *testing.T) {\n\terr := client.NewNotModified(\"test\")\n\tif err.Error() != \"Stream not modified: test\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestServerError_Error(t *testing.T) ", "output": "{\n\terr := client.NewServerError(\"\")\n\tif err.Error() != \"Unexpected error on server: \" {\n\t\tt.FailNow()\n\t}\n\n\terr = client.NewServerError(\"test\")\n\tif err.Error() != \"Unexpected error on server: test\" {\n\t\tt.FailNow()\n\t}\n}"} {"input": "package vanity\n\nimport (\n\t\"github.com/gogo/protobuf/gogoproto\"\n\t\"github.com/gogo/protobuf/proto\"\n\tdescriptor \"github.com/gogo/protobuf/protoc-gen-gogo/descriptor\"\n)\n\nfunc EnumHasBoolExtension(enum *descriptor.EnumDescriptorProto, extension *proto.ExtensionDesc) bool {\n\tif enum.Options == nil {\n\t\treturn false\n\t}\n\tvalue, err := proto.GetExtension(enum.Options, extension)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif value == nil {\n\t\treturn false\n\t}\n\tif value.(*bool) == nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\n\nfunc TurnOffGoEnumPrefix(enum *descriptor.EnumDescriptorProto) {\n\tSetBoolEnumOption(gogoproto.E_GoprotoEnumPrefix, false)(enum)\n}\n\nfunc TurnOffGoEnumStringer(enum *descriptor.EnumDescriptorProto) {\n\tSetBoolEnumOption(gogoproto.E_GoprotoEnumStringer, false)(enum)\n}\n\nfunc TurnOnEnumStringer(enum *descriptor.EnumDescriptorProto) {\n\tSetBoolEnumOption(gogoproto.E_EnumStringer, true)(enum)\n}\n\nfunc SetBoolEnumOption(extension *proto.ExtensionDesc, value bool) func(enum *descriptor.EnumDescriptorProto) ", "output": "{\n\treturn func(enum *descriptor.EnumDescriptorProto) {\n\t\tif EnumHasBoolExtension(enum, extension) {\n\t\t\treturn\n\t\t}\n\t\tif enum.Options == nil {\n\t\t\tenum.Options = &descriptor.EnumOptions{}\n\t\t}\n\t\tif err := proto.SetExtension(enum.Options, extension, &value); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}"} {"input": "package sc\n\n\n\n\n\n\n\n\n\ntype Gendy3 struct {\n\tAmpDist Input\n\n\tDurDist Input\n\n\tADParam Input\n\n\tDDParam Input\n\n\tFreq Input\n\n\tAmpScale Input\n\n\tDurScale Input\n\n\tInitCPs Input\n\n\tKNum Input\n}\n\nfunc (g *Gendy3) defaults() {\n\tif g.AmpDist == nil {\n\t\tg.AmpDist = DistCauchy\n\t}\n\tif g.DurDist == nil {\n\t\tg.DurDist = DistCauchy\n\t}\n\tif g.ADParam == nil {\n\t\tg.ADParam = C(1)\n\t}\n\tif g.DDParam == nil {\n\t\tg.DDParam = C(1)\n\t}\n\tif g.Freq == nil {\n\t\tg.Freq = C(440)\n\t}\n\tif g.AmpScale == nil {\n\t\tg.AmpScale = C(0.5)\n\t}\n\tif g.DurScale == nil {\n\t\tg.DurScale = C(0.5)\n\t}\n\tif g.InitCPs == nil {\n\t\tg.InitCPs = C(12)\n\t}\n\tif g.KNum == nil {\n\t\tg.KNum = C(12)\n\t}\n}\n\n\n\n\n\nfunc (g Gendy3) Rate(rate int8) Input ", "output": "{\n\tCheckRate(rate)\n\t(&g).defaults()\n\treturn NewInput(\"Gendy3\", rate, 0, 1, g.AmpDist, g.DurDist, g.ADParam, g.DDParam, g.Freq, g.AmpScale, g.DurScale, g.InitCPs, g.KNum)\n}"} {"input": "package main\n\nimport \"fmt\"\n\nconst (\n\tBig = 1 << 100\n\tSmall = Big >> 99\n)\n\nfunc needInt(x int) int {\n\treturn x*10 + 1\n}\n\n\n\nfunc main() {\n\tfmt.Println(needInt(Small))\n\tfmt.Println(needFloat(Small))\n\tfmt.Println(needFloat(Big))\n}\n\nfunc needFloat(x float64) float64 ", "output": "{\n\treturn x * 0.1\n}"} {"input": "package jsonbuilder\n\nimport (\n\t\"bytes\"\n\t\"encoding/gob\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n)\n\n\n\nfunc UnmarshalIntArray(ba []byte) []int {\n\tbuffer := bytes.NewBuffer(ba)\n\tvar inta = new([]int)\n\td := gob.NewDecoder(buffer)\n\terr := d.Decode(&inta)\n\tif err != nil {\n\t\tfmt.Println(\"Failed to unmarshal \", ba, err)\n\t}\n\treturn *inta\n}\n\nfunc ReadData(r io.Reader, intf interface{}) error {\n\tdata, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(data, &intf)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc WriteData(w io.Writer, intf interface{}) error {\n\tb, err := json.Marshal(intf)\n\tfmt.Println(len(b), string(b))\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t}\n\n\ti, err := w.Write(b)\n\tif i != len(b) || err != nil {\n\t\tfmt.Println(\"Nothing to write\", i, err)\n\t}\n\treturn err\n}\n\nfunc MarshalIntArray(inta []int) []byte ", "output": "{\n\tbuffer := new(bytes.Buffer)\n\te := gob.NewEncoder(buffer)\n\terr := e.Encode(inta)\n\tif err != nil {\n\t\tfmt.Println(\"Failed to marshal \", err)\n\t}\n\treturn buffer.Bytes()\n}"} {"input": "package web\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"github.com/gravitational/teleport/lib/httplib\"\n\n\t\"github.com/gravitational/roundtrip\"\n\t\"github.com/gravitational/trace\"\n)\n\nfunc newInsecureClient() *http.Client {\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t},\n\t}\n}\n\nfunc newClientWithPool(pool *x509.CertPool) *http.Client {\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{RootCAs: pool},\n\t\t},\n\t}\n}\n\n\n\n\n\ntype webClient struct {\n\t*roundtrip.Client\n}\n\nfunc (w *webClient) PostJSON(\n\tendpoint string, val interface{}) (*roundtrip.Response, error) {\n\treturn httplib.ConvertResponse(w.Client.PostJSON(endpoint, val))\n}\n\nfunc (w *webClient) PutJSON(\n\tendpoint string, val interface{}) (*roundtrip.Response, error) {\n\treturn httplib.ConvertResponse(w.Client.PutJSON(endpoint, val))\n}\n\nfunc (w *webClient) Get(endpoint string, val url.Values) (*roundtrip.Response, error) {\n\treturn httplib.ConvertResponse(w.Client.Get(endpoint, val))\n}\n\nfunc (w *webClient) Delete(endpoint string) (*roundtrip.Response, error) {\n\treturn httplib.ConvertResponse(w.Client.Delete(endpoint))\n}\n\nfunc newWebClient(url string, opts ...roundtrip.ClientParam) (*webClient, error) ", "output": "{\n\tclt, err := roundtrip.NewClient(url, APIVersion, opts...)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\treturn &webClient{clt}, nil\n}"} {"input": "package triangle\n\nimport (\n\t\"math\"\n)\n\nconst (\n\tEqu = iota \n\tIso \n\tSca \n\tNaT \n)\n\ntype Kind int\n\n\n\nfunc areNaN(vals ...float64) bool {\n\tfor _, v := range vals {\n\t\tif math.IsNaN(v) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc areInf(vals ...float64) bool {\n\tfor _, v := range vals {\n\t\tif math.IsInf(v, 1) || math.IsInf(v, -1) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc KindFromSides(a, b, c float64) Kind ", "output": "{\n\tif a+b <= c || a+c <= b || b+c <= a {\n\t\treturn NaT\n\t}\n\n\tswitch {\n\tcase areNaN(a, b, c): \n\t\tfallthrough\n\tcase areInf(a, b, c): \n\t\tfallthrough\n\tcase a == 0 && b == 0 && c == 0: \n\t\treturn NaT\n\n\tcase a == b && b == c: \n\t\treturn Equ\n\tcase a == b || b == c || a == c: \n\t\treturn Iso\n\tdefault: \n\t\treturn Sca\n\t}\n}"} {"input": "package ctxhttp_test\n\nimport (\n\t\"net/http\"\n\t\"testing\"\n\n\t\"errors\"\n\t\"github.com/corestoreio/csfw/net/ctxhttp\"\n\t\"github.com/juju/errgo\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestNewErrorFromErrors(t *testing.T) {\n\ttests := []struct {\n\t\tcode int\n\t\terrs []error\n\t\twantError string\n\t}{\n\t\t{http.StatusBadGateway, nil, http.StatusText(http.StatusBadGateway)},\n\t\t{http.StatusTeapot, []error{errors.New(\"No coffee pot\"), errors.New(\"Not even a milk pot\")}, \"No coffee pot\\nNot even a milk pot\"},\n\t\t{http.StatusConflict, []error{errgo.New(\"Now a coffee pot\"), errgo.New(\"Not even close to a milk pot\")}, \"error_test.go\"},\n\t}\n\tfor _, test := range tests {\n\t\the := ctxhttp.NewErrorFromErrors(test.code, test.errs...)\n\t\tassert.Exactly(t, test.code, he.Code)\n\t\tassert.Contains(t, he.Error(), test.wantError)\n\t}\n}\n\nfunc TestNewError(t *testing.T) ", "output": "{\n\ttests := []struct {\n\t\tcode int\n\t\tmsg []string\n\t\twantError string\n\t}{\n\t\t{http.StatusBadGateway, nil, http.StatusText(http.StatusBadGateway)},\n\t\t{http.StatusTeapot, []string{\"No coffee pot\", \"ignored\"}, \"No coffee pot\"},\n\t}\n\tfor _, test := range tests {\n\t\the := ctxhttp.NewError(test.code, test.msg...)\n\t\tassert.Exactly(t, test.code, he.Code)\n\t\tassert.Exactly(t, test.wantError, he.Error())\n\t}\n}"} {"input": "package main\n\nimport \"strings\"\n\ntype code_section interface {\n\tCode() bool\n}\n\ntype para string\n\nfunc (para) Code() bool {\n\treturn false\n}\n\ntype code string\n\nfunc (code) Code() bool {\n\treturn true\n}\n\ntype Article struct {\n\tTitle string\n\tIntro []para\n\tGoCode, ReflectCode []code_section\n\tUses, Tags []string\n\tslug string\n}\n\nfunc (a *Article) Slug() string {\n\tif a.slug == \"\" {\n\t\ta.slug = strings.ToLower(strings.Replace(a.Title, \" \", \"-\", -1))\n\t}\n\treturn a.slug\n}\n\ntype Articles []*Article\n\nfunc (a *Articles) Add(ao *Article) {\n\t*a = append(*a, ao)\n}\n\n\n\nfunc (a Articles) Swap(i, j int) {\n\ta[j], a[i] = a[i], a[j]\n}\n\nfunc (a Articles) Less(i, j int) bool {\n\treturn a[i].Title < a[j].Title\n}\n\nfunc (a Articles) Len() int ", "output": "{\n\treturn len(a)\n}"} {"input": "package db\n\nimport \"testing\"\n\nfunc TestObjectToJSON(t *testing.T) {\n\tv := &SurveyVar{\n\t\tName: \"test\",\n\t\tTitle: \"Test\",\n\t}\n\ts := ObjectToJSON(v)\n\tif s == nil || *s != \"{\\\"name\\\":\\\"test\\\",\\\"title\\\":\\\"Test\\\",\\\"required\\\":false,\\\"type\\\":\\\"\\\",\\\"description\\\":\\\"\\\"}\" {\n\t\tt.Fail()\n\t}\n}\n\n\n\nfunc TestObjectToJSON3(t *testing.T) {\n\tv := SurveyVar{\n\t\tName: \"test\",\n\t\tTitle: \"Test\",\n\t}\n\ts := ObjectToJSON(v)\n\tif s == nil || *s != \"{\\\"name\\\":\\\"test\\\",\\\"title\\\":\\\"Test\\\",\\\"required\\\":false,\\\"type\\\":\\\"\\\",\\\"description\\\":\\\"\\\"}\" {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestObjectToJSON2(t *testing.T) ", "output": "{\n\tvar v *SurveyVar = nil\n\ts := ObjectToJSON(v)\n\tif s != nil {\n\t\tt.Fail()\n\t}\n}"} {"input": "package task\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/docker/swarm/cluster\"\n\t\"github.com/samalba/dockerclient\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype testLauncher struct {\n\tcount int\n}\n\nfunc (t *testLauncher) LaunchTask(_ *Task) bool {\n\tt.count = t.count - 1\n\treturn t.count == 0\n}\n\n\n\nfunc TestRemove(t *testing.T) {\n\tq := NewTasks(&testLauncher{count: 2})\n\ttask1, _ := NewTask(cluster.BuildContainerConfig(dockerclient.ContainerConfig{\n\t\tImage: \"test-image\",\n\t\tCpuShares: 42,\n\t\tMemory: 2097152,\n\t\tCmd: []string{\"ls\", \"foo\", \"bar\"},\n\t}), \"name1\", 5*time.Second)\n\n\tq.Add(task1)\n\tassert.Equal(t, len(q.Tasks), 1)\n\tq.Remove(task1)\n\tassert.Equal(t, len(q.Tasks), 0)\n\n}\n\nfunc TestProcess(t *testing.T) {\n\tq := NewTasks(&testLauncher{count: 3})\n\ttask1, _ := NewTask(cluster.BuildContainerConfig(dockerclient.ContainerConfig{\n\t\tImage: \"test-image\",\n\t\tCpuShares: 42,\n\t\tMemory: 2097152,\n\t\tCmd: []string{\"ls\", \"foo\", \"bar\"},\n\t}), \"name1\", 5*time.Second)\n\n\tq.Add(task1)\n\tassert.Equal(t, len(q.Tasks), 1)\n\tq.Process()\n\tassert.Equal(t, len(q.Tasks), 1)\n\tq.Process()\n\tassert.Equal(t, len(q.Tasks), 0)\n\n}\n\nfunc TestAdd(t *testing.T) ", "output": "{\n\tq := NewTasks(&testLauncher{count: 1})\n\n\ttask1, _ := NewTask(cluster.BuildContainerConfig(dockerclient.ContainerConfig{\n\t\tImage: \"test-image\",\n\t\tCpuShares: 42,\n\t\tMemory: 2097152,\n\t\tCmd: []string{\"ls\", \"foo\", \"bar\"},\n\t}), \"name1\", 5*time.Second)\n\n\ttask2, _ := NewTask(cluster.BuildContainerConfig(dockerclient.ContainerConfig{\n\t\tImage: \"test-image\",\n\t\tCpuShares: 42,\n\t\tMemory: 2097152,\n\t\tCmd: []string{\"ls\", \"foo\", \"bar\"},\n\t}), \"name2\", 5*time.Second)\n\tq.Add(task1)\n\tassert.Equal(t, len(q.Tasks), 0)\n\n\tq.Add(task2)\n\tassert.Equal(t, len(q.Tasks), 1)\n\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/bitantics/amerigo/crawler\"\n\t\"github.com/bitantics/amerigo/page\"\n)\n\n\nfunc main() {\n\tflag.Parse()\n\tif flag.NArg() == 0 {\n\t\treturn\n\t}\n\tsite := flag.Arg(0)\n\n\tc, err := crawler.New(site)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tc.Start(32)\n\n\tfmt.Println(\"[\")\n\tdefer fmt.Println(\"\\n]\")\n\n\tfirstPage := true\n\ncrawl:\n\tfor {\n\t\tselect {\n\t\tcase pg := <-c.Pages:\n\t\t\tif pg != nil {\n\t\t\t\tif firstPage {\n\t\t\t\t\tfirstPage = false\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Println(\",\")\n\t\t\t\t}\n\n\t\t\t\tprintPage(pg)\n\t\t\t}\n\t\tcase err = <-c.Errors:\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\tcase <-c.Done:\n\t\t\tbreak crawl\n\t\t}\n\t}\n\n}\n\n\n\nfunc printPage(p *page.Page) error ", "output": "{\n\tpg, err := json.MarshalIndent(p, \"\", \"\\t\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Print(string(pg))\n\treturn nil\n}"} {"input": "package dosingdecision\n\nimport (\n\t\"time\"\n\n\t\"github.com/tidepool-org/platform/structure\"\n)\n\nconst (\n\tCarbohydratesOnBoardAmountMaximum = 1000\n\tCarbohydratesOnBoardAmountMinimum = 0\n)\n\ntype CarbohydratesOnBoard struct {\n\tTime *time.Time `json:\"time,omitempty\" bson:\"time,omitempty\"`\n\tAmount *float64 `json:\"amount,omitempty\" bson:\"amount,omitempty\"`\n}\n\nfunc ParseCarbohydratesOnBoard(parser structure.ObjectParser) *CarbohydratesOnBoard {\n\tif !parser.Exists() {\n\t\treturn nil\n\t}\n\tdatum := NewCarbohydratesOnBoard()\n\tparser.Parse(datum)\n\treturn datum\n}\n\nfunc NewCarbohydratesOnBoard() *CarbohydratesOnBoard {\n\treturn &CarbohydratesOnBoard{}\n}\n\nfunc (c *CarbohydratesOnBoard) Parse(parser structure.ObjectParser) {\n\tc.Time = parser.Time(\"time\", time.RFC3339Nano)\n\tc.Amount = parser.Float64(\"amount\")\n}\n\n\n\nfunc (c *CarbohydratesOnBoard) Validate(validator structure.Validator) ", "output": "{\n\tvalidator.Float64(\"amount\", c.Amount).Exists().InRange(CarbohydratesOnBoardAmountMinimum, CarbohydratesOnBoardAmountMaximum)\n}"} {"input": "package packr\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com/gobuffalo/envy\"\n\t\"github.com/gobuffalo/packr/v2/plog\"\n)\n\nfunc construct(name string, path string) *Box {\n\treturn &Box{\n\t\tPath:\t\tpath,\n\t\tName:\t\tname,\n\t\tResolutionDir:\tresolutionDir(path),\n\t\tresolvers:\tresolversMap{},\n\t\tdirs:\t\tdirsMap{},\n\t}\n}\n\n\n\nfunc resolutionDirExists(s, og string) bool {\n\t_, err := os.Stat(s)\n\tif err != nil {\n\t\treturn false\n\t}\n\tplog.Debug(\"packr\", \"resolutionDir\", \"original\", og, \"resolved\", s)\n\treturn true\n}\n\nfunc resolutionDir(og string) string {\n\tng, _ := filepath.Abs(og)\n\n\tif resolutionDirExists(ng, og) {\n\t\treturn ng\n\t}\n\n\t_, filename, _, _ := runtime.Caller(3)\n\tng, ok := resolutionDirTestFilename(filename, og)\n\tif ok {\n\t\treturn ng\n\t}\n\n\t_, filename, _, _ = runtime.Caller(4)\n\tng, ok = resolutionDirTestFilename(filename, og)\n\tif ok {\n\t\treturn ng\n\t}\n\n\treturn og\n}\n\nfunc resolutionDirTestFilename(filename, og string) (string, bool) ", "output": "{\n\tng := filepath.Join(filepath.Dir(filename), og)\n\n\tcov := filepath.Join(\"_test\", \"_obj_test\")\n\tng = strings.Replace(ng, string(filepath.Separator)+cov, \"\", 1)\n\n\tif resolutionDirExists(ng, og) {\n\t\treturn ng, true\n\t}\n\n\tng = filepath.Join(envy.GoPath(), \"src\", ng)\n\tif resolutionDirExists(ng, og) {\n\t\treturn ng, true\n\t}\n\n\treturn og, false\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"gopkg.in/ini.v1\"\n)\n\nfunc DrawClock(r Renderer, f Font) {\n\th, m, _ := time.Now().Local().Clock()\n\n\tstr := fmt.Sprintf(\"%02d:%02d\", h, m)\n\n\tw, h := f.Measure(str)\n\tf.Render(r, (r.Width()-w)/2, (r.Height()-h)/2, str)\n}\n\n\n\nvar weekdayNames = make(map[time.Weekday]string)\n\nfunc InitializeClock() error {\n\tbytes, err := Asset(\"res/res.ini\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfile, err := ini.Load(bytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsection := file.Section(\"\")\n\tweekdayNames[time.Monday] = section.Key(\"Monday\").Value()\n\tweekdayNames[time.Tuesday] = section.Key(\"Tuesday\").Value()\n\tweekdayNames[time.Wednesday] = section.Key(\"Wednesday\").Value()\n\tweekdayNames[time.Thursday] = section.Key(\"Thursday\").Value()\n\tweekdayNames[time.Friday] = section.Key(\"Friday\").Value()\n\tweekdayNames[time.Saturday] = section.Key(\"Saturday\").Value()\n\tweekdayNames[time.Sunday] = section.Key(\"Sunday\").Value()\n\n\treturn nil\n}\n\nfunc GetDayOfWeek(w time.Weekday) string {\n\tstr, exists := weekdayNames[w]\n\tif !exists {\n\t\treturn \"?\"\n\t}\n\n\treturn str\n}\n\nfunc DrawDate(r Renderer, f Font) ", "output": "{\n\t_, month, day := time.Now().Local().Date()\n\tdayOfWeek := GetDayOfWeek(time.Now().Local().Weekday())\n\tstr := fmt.Sprintf(\"%s %2d.%02d\", dayOfWeek, month, day)\n\n\tw, _ := f.Measure(str)\n\tf.Render(r, (r.Width()-w)/2, 1, str)\n}"} {"input": "package subscriptions\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/status-im/status-go/rpc\"\n)\n\ntype ethFilter struct {\n\tid string\n\trpcClient *rpc.Client\n}\n\nfunc installEthFilter(rpcClient *rpc.Client, method string, args []interface{}) (*ethFilter, error) {\n\n\tif err := validateEthMethod(method); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result string\n\n\terr := rpcClient.Call(&result, rpcClient.UpstreamChainID, method, args...)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfilter := ðFilter{\n\t\tid: result,\n\t\trpcClient: rpcClient,\n\t}\n\n\treturn filter, nil\n\n}\n\n\n\nfunc (ef *ethFilter) getChanges() ([]interface{}, error) {\n\tvar result []interface{}\n\n\terr := ef.rpcClient.Call(&result, ef.rpcClient.UpstreamChainID, \"eth_getFilterChanges\", ef.getID())\n\n\treturn result, err\n}\n\nfunc (ef *ethFilter) uninstall() error {\n\treturn ef.rpcClient.Call(nil, ef.rpcClient.UpstreamChainID, \"eth_uninstallFilter\", ef.getID())\n}\n\nfunc validateEthMethod(method string) error {\n\tfor _, allowedMethod := range []string{\n\t\t\"eth_newFilter\",\n\t\t\"eth_newBlockFilter\",\n\t\t\"eth_newPendingTransactionFilter\",\n\t} {\n\t\tif method == allowedMethod {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"unexpected filter method: %s\", method)\n}\n\nfunc (ef *ethFilter) getID() string ", "output": "{\n\treturn ef.id\n}"} {"input": "package cloudtail\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\n\n\nfunc TestPipeFromReader(t *testing.T) ", "output": "{\n\tConvey(\"Works\", t, func() {\n\t\tclient := &fakeClient{}\n\t\tbuf := NewPushBuffer(PushBufferOptions{Client: client})\n\n\t\tbody := `\n line\n another\n\n last one\n `\n\n\t\tPipeFromReader(strings.NewReader(body), NullParser(), buf, nil)\n\t\tSo(buf.Stop(nil), ShouldBeNil)\n\n\t\ttext := []string{}\n\t\tfor _, e := range client.getEntries() {\n\t\t\ttext = append(text, e.TextPayload)\n\t\t}\n\t\tSo(text, ShouldResemble, []string{\"line\", \"another\", \"last one\"})\n\t})\n}"} {"input": "package load\n\nimport (\n\t\"github.com/Ericsson/ericsson-hds-agent/agent/collectors\"\n)\n\n\n\n\nfunc Run() ([]*collectors.MetricResult, error) ", "output": "{\n\n\tdata, err := loader()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn preformatter(data)\n}"} {"input": "package progress\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"testing\"\n)\n\nfunc TestOutputOnPrematureClose(t *testing.T) {\n\tcontent := []byte(\"TESTING\")\n\treader := ioutil.NopCloser(bytes.NewReader(content))\n\tprogressChan := make(chan Progress, 10)\n\n\tpr := NewProgressReader(reader, ChanOutput(progressChan), int64(len(content)), \"Test\", \"Read\")\n\n\tpart := make([]byte, 4, 4)\n\t_, err := io.ReadFull(pr, part)\n\tif err != nil {\n\t\tpr.Close()\n\t\tt.Fatal(err)\n\t}\n\ndrainLoop:\n\tfor {\n\t\tselect {\n\t\tcase <-progressChan:\n\t\tdefault:\n\t\t\tbreak drainLoop\n\t\t}\n\t}\n\n\tpr.Close()\n\n\tselect {\n\tcase <-progressChan:\n\tdefault:\n\t\tt.Fatalf(\"Expected some output when closing prematurely\")\n\t}\n}\n\n\n\nfunc TestCompleteSilently(t *testing.T) ", "output": "{\n\tcontent := []byte(\"TESTING\")\n\treader := ioutil.NopCloser(bytes.NewReader(content))\n\tprogressChan := make(chan Progress, 10)\n\n\tpr := NewProgressReader(reader, ChanOutput(progressChan), int64(len(content)), \"Test\", \"Read\")\n\n\tout, err := ioutil.ReadAll(pr)\n\tif err != nil {\n\t\tpr.Close()\n\t\tt.Fatal(err)\n\t}\n\tif string(out) != \"TESTING\" {\n\t\tpr.Close()\n\t\tt.Fatalf(\"Unexpected output %q from reader\", string(out))\n\t}\n\ndrainLoop:\n\tfor {\n\t\tselect {\n\t\tcase <-progressChan:\n\t\tdefault:\n\t\t\tbreak drainLoop\n\t\t}\n\t}\n\n\tpr.Close()\n\n\tselect {\n\tcase <-progressChan:\n\t\tt.Fatalf(\"Should have closed silently when read is complete\")\n\tdefault:\n\t}\n}"} {"input": "package term\n\nimport (\n\t\"github.com/lmorg/murex/lang/stdio\"\n\t\"github.com/lmorg/murex/utils\"\n)\n\n\n\n\ntype Err struct {\n\tterm\n}\n\n\n\n\n\nfunc (t *Err) Writeln(b []byte) (int, error) {\n\treturn t.Write(appendBytes(b, utils.NewLineByte...))\n}\n\n\nfunc (t *Err) WriteArray(dataType string) (stdio.ArrayWriter, error) {\n\treturn stdio.WriteArray(t, dataType)\n}\n\nfunc (t *Err) Write(b []byte) (int, error) ", "output": "{\n\tt.mutex.Lock()\n\tt.bWritten += uint64(len(b))\n\tt.mutex.Unlock()\n\n\tvtermWrite([]rune(string(b)))\n\n\treturn len(b), nil\n}"} {"input": "package connlimit\n\nimport (\n\t\"github.com/mailgun/vulcand/Godeps/_workspace/src/github.com/codegangsta/cli\"\n\t. \"github.com/mailgun/vulcand/Godeps/_workspace/src/gopkg.in/check.v1\"\n\t\"github.com/mailgun/vulcand/plugin\"\n\t\"testing\"\n)\n\nfunc TestCL(t *testing.T) { TestingT(t) }\n\ntype ConnLimitSuite struct {\n}\n\nvar _ = Suite(&ConnLimitSuite{})\n\n\n\nfunc (s *ConnLimitSuite) TestSpecIsOK(c *C) {\n\tc.Assert(plugin.NewRegistry().AddSpec(GetSpec()), IsNil)\n}\n\nfunc (s *ConnLimitSuite) TestNewConnLimitSuccess(c *C) {\n\tcl, err := NewConnLimit(10, \"client.ip\")\n\tc.Assert(cl, NotNil)\n\tc.Assert(err, IsNil)\n\n\tc.Assert(cl.String(), Not(Equals), \"\")\n\n\tout, err := cl.NewMiddleware()\n\tc.Assert(out, NotNil)\n\tc.Assert(err, IsNil)\n}\n\nfunc (s *ConnLimitSuite) TestNewConnLimitBadParams(c *C) {\n\t_, err := NewConnLimit(10, \"client ip\")\n\tc.Assert(err, NotNil)\n\n\t_, err = NewConnLimit(-10, \"client.ip\")\n\tc.Assert(err, NotNil)\n}\n\nfunc (s *ConnLimitSuite) TestNewConnLimitFromOther(c *C) {\n\tcl, err := NewConnLimit(10, \"client.ip\")\n\tc.Assert(cl, NotNil)\n\tc.Assert(err, IsNil)\n\n\tout, err := FromOther(*cl)\n\tc.Assert(err, IsNil)\n\tc.Assert(out, DeepEquals, cl)\n}\n\n\n\nfunc (s *ConnLimitSuite) TestNewConnLimitFromCli(c *C) ", "output": "{\n\tapp := cli.NewApp()\n\tapp.Name = \"test\"\n\texecuted := false\n\tapp.Action = func(ctx *cli.Context) {\n\t\texecuted = true\n\t\tout, err := FromCli(ctx)\n\t\tc.Assert(out, NotNil)\n\t\tc.Assert(err, IsNil)\n\n\t\tcl := out.(*ConnLimit)\n\t\tc.Assert(cl.Variable, Equals, \"client.ip\")\n\t\tc.Assert(cl.Connections, Equals, int64(10))\n\t}\n\tapp.Flags = CliFlags()\n\tapp.Run([]string{\"test\", \"--var=client.ip\", \"--connections=10\"})\n\tc.Assert(executed, Equals, true)\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"os\"\n\t\"os/signal\"\n\n\t\"github.com/caiofilipini/got/bot\"\n\t\"github.com/caiofilipini/got/command\"\n\t\"github.com/caiofilipini/got/irc\"\n)\n\nvar (\n\tserver *string\n\tport *int\n\tchannel *string\n\tuser *string\n\tpasswd *string\n\tlogFilePath *string\n)\n\n\n\nfunc setupLogging() *os.File {\n\tif *logFilePath != \"\" {\n\t\tfile, err := os.OpenFile(*logFilePath, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tlog.SetOutput(file)\n\t\treturn file\n\t}\n\n\treturn nil\n}\n\nfunc main() {\n\tlogFile := setupLogging()\n\tif logFile != nil {\n\t\tdefer logFile.Close()\n\t}\n\n\tconn := irc.NewIRC(*server, *port, *channel)\n\tdefer conn.Close()\n\n\tbot := bot.NewBot(conn, *user, *passwd)\n\tdefer bot.Shutdown()\n\n\tbot.Register(command.Swear())\n\tbot.Register(command.Greet())\n\tbot.Register(command.Image())\n\tbot.Register(command.GIF())\n\tbot.Register(command.Video())\n\tbot.Register(command.XKCD())\n\tbot.Register(command.BeerOClock())\n\tbot.Register(command.Weather())\n\tbot.Register(command.Luca()) \n\n\tbot.Start()\n\tgo bot.Listen()\n\n\tsignals := make(chan os.Signal, 1)\n\tsignal.Notify(signals, os.Interrupt)\n\n\tfor _ = range signals {\n\t\tlog.Println(\"KTHXBAI.\")\n\t\tos.Exit(0)\n\t}\n}\n\nfunc init() ", "output": "{\n\tserver = flag.String(\"s\", \"irc.freenode.org\", \"IRC server host\")\n\tport = flag.Int(\"p\", 6667, \"IRC server port\")\n\tuser = flag.String(\"u\", \"gotgotgot\", \"bot username\")\n\tchannel = flag.String(\"c\", \"\", \"channel to connect\")\n\tpasswd = flag.String(\"k\", \"\", \"channel secret key\")\n\tlogFilePath = flag.String(\"l\", \"\", \"log file location; if empty, stdout will be used\")\n\n\tflag.Parse()\n\n\tif *channel == \"\" {\n\t\tlog.Println(\"No channel specified, aborting!\")\n\t\tflag.PrintDefaults()\n\t\tos.Exit(1)\n\t}\n}"} {"input": "package sessions\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/keratin/authn-server/app\"\n\t\"github.com/keratin/authn-server/app/data\"\n\t\"github.com/pkg/errors\"\n\tjose \"gopkg.in/square/go-jose.v2\"\n\tjwt \"gopkg.in/square/go-jose.v2/jwt\"\n)\n\nconst scope = \"refresh\"\n\ntype Claims struct {\n\tScope string `json:\"scope\"`\n\tAzp string `json:\"azp\"`\n\tjwt.Claims\n}\n\nfunc (c *Claims) Sign(hmacKey []byte) (string, error) {\n\tsigner, err := jose.NewSigner(\n\t\tjose.SigningKey{Algorithm: jose.HS256, Key: hmacKey},\n\t\t(&jose.SignerOptions{}).WithType(\"JWT\"),\n\t)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"NewSigner\")\n\t}\n\treturn jwt.Signed(signer).Claims(c).CompactSerialize()\n}\n\n\n\nfunc New(store data.RefreshTokenStore, cfg *app.Config, accountID int, authorizedAudience string) (*Claims, error) {\n\trefreshToken, err := store.Create(accountID)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Create\")\n\t}\n\n\treturn &Claims{\n\t\tScope: scope,\n\t\tAzp: authorizedAudience,\n\t\tClaims: jwt.Claims{\n\t\t\tIssuer: cfg.AuthNURL.String(),\n\t\t\tSubject: string(refreshToken),\n\t\t\tAudience: jwt.Audience{cfg.AuthNURL.String()},\n\t\t\tIssuedAt: jwt.NewNumericDate(time.Now()),\n\t\t},\n\t}, nil\n}\n\nfunc Parse(tokenStr string, cfg *app.Config) (*Claims, error) ", "output": "{\n\ttoken, err := jwt.ParseSigned(tokenStr)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"ParseSigned\")\n\t}\n\n\tclaims := Claims{}\n\terr = token.Claims(cfg.SessionSigningKey, &claims)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Claims\")\n\t}\n\n\terr = claims.Claims.Validate(jwt.Expected{\n\t\tAudience: jwt.Audience{cfg.AuthNURL.String()},\n\t\tIssuer: cfg.AuthNURL.String(),\n\t})\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Validate\")\n\t}\n\tif claims.Scope != scope {\n\t\treturn nil, fmt.Errorf(\"token scope not valid\")\n\t}\n\n\treturn &claims, nil\n}"} {"input": "package gol\n\nimport (\n\t\"errors\"\n\n\t\"github.com/philchia/gol/adapter\"\n)\n\n\nfunc (l *gollog) AddLogAdapter(name string, adp adapter.Adapter) error {\n\tif adp == nil {\n\t\treturn errors.New(\"nil adapter\")\n\t}\n\tif _, ok := l.adapters[name]; ok {\n\n\t\treturn errors.New(\"Adapter already exists\")\n\t}\n\n\ttmpAdapters := make(map[string]adapter.Adapter, len(l.adapters)+1)\n\n\tfor k, v := range l.adapters {\n\t\ttmpAdapters[k] = v\n\t}\n\n\ttmpAdapters[name] = adp\n\tl.adapters = tmpAdapters\n\n\treturn nil\n}\n\n\n\n\nfunc (l *gollog) RemoveAdapter(name string) error ", "output": "{\n\tif _, ok := l.adapters[name]; !ok {\n\t\treturn errors.New(\"Adapter not exists\")\n\t}\n\n\ttmpAdapters := make(map[string]adapter.Adapter, len(l.adapters)-1)\n\n\tfor k, v := range l.adapters {\n\t\tif k != name {\n\t\t\ttmpAdapters[k] = v\n\t\t}\n\t}\n\n\tl.adapters = tmpAdapters\n\n\treturn nil\n}"} {"input": "package tsmt\n\nimport (\n\t\"encoding/xml\"\n\n\t\"github.com/fgrid/iso20022\"\n)\n\ntype Document05500101 struct {\n\tXMLName xml.Name `xml:\"urn:iso:std:iso:20022:tech:xsd:tsmt.055.001.01 Document\"`\n\tMessage *PartyEventAdviceV01 `xml:\"PtyEvtAdvc\"`\n}\n\nfunc (d *Document05500101) AddMessage() *PartyEventAdviceV01 {\n\td.Message = new(PartyEventAdviceV01)\n\treturn d.Message\n}\n\n\n\n\n\ntype PartyEventAdviceV01 struct {\n\n\tHeader *iso20022.BusinessLetter1 `xml:\"Hdr\"`\n\n\tEventNotice []*iso20022.EventDescription1 `xml:\"EvtNtce\"`\n\n\tEventCount *iso20022.Max15NumericText `xml:\"EvtCnt,omitempty\"`\n\n\tAttachedMessage []*iso20022.EncapsulatedBusinessMessage1 `xml:\"AttchdMsg,omitempty\"`\n}\n\n\n\nfunc (p *PartyEventAdviceV01) AddEventNotice() *iso20022.EventDescription1 {\n\tnewValue := new(iso20022.EventDescription1)\n\tp.EventNotice = append(p.EventNotice, newValue)\n\treturn newValue\n}\n\nfunc (p *PartyEventAdviceV01) SetEventCount(value string) {\n\tp.EventCount = (*iso20022.Max15NumericText)(&value)\n}\n\nfunc (p *PartyEventAdviceV01) AddAttachedMessage() *iso20022.EncapsulatedBusinessMessage1 {\n\tnewValue := new(iso20022.EncapsulatedBusinessMessage1)\n\tp.AttachedMessage = append(p.AttachedMessage, newValue)\n\treturn newValue\n}\n\nfunc (p *PartyEventAdviceV01) AddHeader() *iso20022.BusinessLetter1 ", "output": "{\n\tp.Header = new(iso20022.BusinessLetter1)\n\treturn p.Header\n}"} {"input": "package client\n\nimport (\n\t\"fmt\"\n\t\"github.com/keybase/cli\"\n\t\"github.com/keybase/client/go/libcmdline\"\n\t\"github.com/keybase/client/go/libkb\"\n\tkeybase1 \"github.com/keybase/client/go/protocol/keybase1\"\n\t\"github.com/keybase/go-framed-msgpack-rpc/rpc\"\n\t\"golang.org/x/net/context\"\n)\n\ntype CmdFakeTrackingChanged struct {\n\tlibkb.Contextified\n\targ keybase1.FakeTrackingChangedArg\n}\n\n\n\nfunc (c *CmdFakeTrackingChanged) Run() (err error) {\n\tcli, err := GetTrackClient(c.G())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprotocols := []rpc.Protocol{}\n\tif err = RegisterProtocolsWithContext(protocols, c.G()); err != nil {\n\t\treturn err\n\t}\n\n\terr = cli.FakeTrackingChanged(context.TODO(), c.arg)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc NewCmdFakeTrackingChanged(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command {\n\treturn cli.Command{\n\t\tName: \"fake-following-changed\",\n\t\tFlags: []cli.Flag{},\n\t\tAction: func(c *cli.Context) {\n\t\t\tcl.ChooseCommand(NewCmdFakeTrackingChangedRunner(g), \"fake-following-changed\", c)\n\t\t},\n\t}\n}\n\nfunc NewCmdFakeTrackingChangedRunner(g *libkb.GlobalContext) *CmdFakeTrackingChanged {\n\treturn &CmdFakeTrackingChanged{Contextified: libkb.NewContextified(g)}\n}\n\nfunc (c *CmdFakeTrackingChanged) GetUsage() libkb.Usage {\n\treturn libkb.Usage{\n\t\tConfig: true,\n\t\tAPI: true,\n\t}\n}\n\nfunc (c *CmdFakeTrackingChanged) ParseArgv(ctx *cli.Context) error ", "output": "{\n\tif len(ctx.Args()) != 1 {\n\t\treturn fmt.Errorf(\"Must provide exactly one username.\")\n\t}\n\tc.arg.Username = ctx.Args()[0]\n\treturn nil\n}"} {"input": "package sign\n\nimport (\n\t\"dfss\"\n\tcAPI \"dfss/dfssc/api\"\n\tpAPI \"dfss/dfssp/api\"\n\t\"dfss/dfsst/entities\"\n\t\"dfss/net\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc\"\n)\n\ntype clientServer struct {\n\tincomingPromises chan interface{}\n\tincomingSignatures chan interface{}\n}\n\nfunc getServerErrorCode(c chan interface{}, in interface{}) *pAPI.ErrorCode {\n\tif c != nil {\n\t\tc <- in\n\t\treturn &pAPI.ErrorCode{Code: pAPI.ErrorCode_SUCCESS}\n\t}\n\treturn &pAPI.ErrorCode{Code: pAPI.ErrorCode_INTERR} \n}\n\n\n\n\nfunc (s *clientServer) TreatPromise(ctx context.Context, in *cAPI.Promise) (*pAPI.ErrorCode, error) {\n\tvalid, _, _, _ := entities.IsRequestValid(ctx, []*cAPI.Promise{in})\n\tif !valid {\n\t\treturn &pAPI.ErrorCode{Code: pAPI.ErrorCode_SUCCESS}, nil\n\t}\n\treturn getServerErrorCode(s.incomingPromises, in), nil\n}\n\n\n\n\nfunc (s *clientServer) TreatSignature(ctx context.Context, in *cAPI.Signature) (*pAPI.ErrorCode, error) {\n\treturn getServerErrorCode(s.incomingSignatures, in), nil\n}\n\n\n\n\nfunc (s *clientServer) Discover(ctx context.Context, in *cAPI.Hello) (*cAPI.Hello, error) {\n\treturn &cAPI.Hello{Version: dfss.Version}, nil\n}\n\n\n\n\nfunc (m *SignatureManager) GetServer() *grpc.Server ", "output": "{\n\tserver := net.NewServer(m.auth.Cert, m.auth.Key, m.auth.CA)\n\tm.cServerIface = clientServer{}\n\tcAPI.RegisterClientServer(server, &m.cServerIface)\n\treturn server\n}"} {"input": "package dbutil\n\nimport (\n\t\"log\"\n\t\"testing\"\n\t\"time\"\n\n\tConfig \"../config\"\n\t_ \"github.com/lib/pq\"\n)\n\nfunc dbOperation(dbHost, dbUser, dbPasswd, dbName string, t *testing.T) {\n\tconn := New(dbHost, dbUser, dbPasswd, dbName)\n\tdefer conn.Close()\n\n\tusers := conn.Rows(\"users\", \"id, openid, nickname, created\")\n\tdefer users.Close()\n\tfor users.Next() {\n\t\tvar id, openid, nickname string\n\t\tvar created time.Time\n\t\tif err := users.Scan(&id, &openid, &nickname, &created); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tlog.Println(id, openid, nickname, created.Format(time.RFC3339))\n\t}\n}\n\nfunc TestDBWithYaml(t *testing.T) {\n\tlog.Println(\"[test yaml]\")\n\t_, err := Config.GetConfig(\"../config/database.yml\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n}\n\n\n\nfunc TestDBWithToml(t *testing.T) ", "output": "{\n\tlog.Println(\"[test toml]\")\n\tcfg, err := Config.GetTomlConfig(\"../config/database.toml\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tdev := cfg.Env[\"development\"]\n\tdbOperation(dev.Host, dev.Username, dev.Password, dev.Database, t)\n}"} {"input": "package core\n\nimport (\n \"errors\"\n \"fmt\"\n \"image\"\n \"image/jpeg\"\n \"io\"\n \"os\"\n \"os/exec\"\n)\n\ntype JPEGHandler struct {\n}\n\nfunc (j *JPEGHandler) ImageType() string {\n return \"image/png\"\n}\n\nfunc (j *JPEGHandler) Decode(reader io.Reader) (image.Image, error) {\n return jpeg.Decode(reader)\n}\n\nfunc (j *JPEGHandler) Encode(newImgFile *os.File, newImage image.Image) error {\n return jpeg.Encode(newImgFile, newImage, nil)\n}\n\n\n\nfunc (j *JPEGHandler) Convert(newImageTempPath string, quality uint) error ", "output": "{\n args := []string{fmt.Sprintf(\"--max=%d\", quality), newImageTempPath}\n cmd := exec.Command(\"jpegoptim\", args...)\n err := cmd.Run()\n if err != nil {\n return errors.New(\"Jpegoptim command not working\")\n }\n\n return nil\n}"} {"input": "package database\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ChangeDatabaseSoftwareImageCompartmentRequest struct {\n\n\tChangeCompartmentDetails `contributesTo:\"body\"`\n\n\tDatabaseSoftwareImageId *string `mandatory:\"true\" contributesTo:\"path\" name:\"databaseSoftwareImageId\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ChangeDatabaseSoftwareImageCompartmentRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ChangeDatabaseSoftwareImageCompartmentRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\n\n\n\nfunc (request ChangeDatabaseSoftwareImageCompartmentRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ChangeDatabaseSoftwareImageCompartmentResponse struct {\n\n\tRawResponse *http.Response\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ChangeDatabaseSoftwareImageCompartmentResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ChangeDatabaseSoftwareImageCompartmentResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ChangeDatabaseSoftwareImageCompartmentRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\n}"} {"input": "package migrations\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/RichardKnop/example-api/log\"\n\t\"github.com/jinzhu/gorm\"\n)\n\n\ntype MigrationStage struct {\n\tName string\n\tFunction func(db *gorm.DB, name string) error\n}\n\n\n\n\n\n\nfunc MigrateAll(db *gorm.DB, migrationFunctions []func(*gorm.DB) error) {\n\tif err := Bootstrap(db); err != nil {\n\t\tlog.ERROR.Print(err)\n\t}\n\n\tfor _, m := range migrationFunctions {\n\t\tif err := m(db); err != nil {\n\t\t\tlog.ERROR.Print(err)\n\t\t}\n\t}\n}\n\n\nfunc MigrationExists(db *gorm.DB, migrationName string) bool {\n\tmigration := new(Migration)\n\tfound := !db.Where(\"name = ?\", migrationName).First(migration).RecordNotFound()\n\n\tif found {\n\t\tlog.INFO.Printf(\"Skipping %s migration\", migrationName)\n\t} else {\n\t\tlog.INFO.Printf(\"Running %s migration\", migrationName)\n\t}\n\n\treturn found\n}\n\n\nfunc SaveMigration(db *gorm.DB, migrationName string) error {\n\tmigration := new(Migration)\n\tmigration.Name = migrationName\n\n\tif err := db.Create(migration).Error; err != nil {\n\t\tlog.ERROR.Printf(\"Error saving record to migrations table: %s\", err)\n\t\treturn fmt.Errorf(\"Error saving record to migrations table: %s\", err)\n\t}\n\n\treturn nil\n}\n\nfunc Migrate(db *gorm.DB, migrations []MigrationStage) error ", "output": "{\n\tfor _, m := range migrations {\n\t\tif MigrationExists(db, m.Name) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := m.Function(db, m.Name); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := SaveMigration(db, m.Name); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"os\"\n\n\t\"github.com/olekukonko/tablewriter\"\n)\n\ntype tblWriter struct {\n\t*tablewriter.Table\n}\n\nfunc NewTableWriter() *tblWriter {\n\treturn &tblWriter{tablewriter.NewWriter(os.Stdout)}\n}\n\n\n\nfunc (table *tblWriter) WriteData(header []string, data [][]string) error ", "output": "{\n\ttable.SetHeader(header)\n\ttable.AppendBulk(data)\n\ttable.Render()\n\treturn nil\n}"} {"input": "package s2\n\n\nvar (\n\t_ Shape = (*PointVector)(nil)\n)\n\n\n\n\n\n\n\n\ntype PointVector []Point\n\nfunc (p *PointVector) NumEdges() int { return len(*p) }\nfunc (p *PointVector) Edge(i int) Edge { return Edge{(*p)[i], (*p)[i]} }\nfunc (p *PointVector) ReferencePoint() ReferencePoint { return OriginReferencePoint(false) }\nfunc (p *PointVector) NumChains() int { return len(*p) }\nfunc (p *PointVector) Chain(i int) Chain { return Chain{i, 1} }\nfunc (p *PointVector) ChainEdge(i, j int) Edge { return Edge{(*p)[i], (*p)[j]} }\nfunc (p *PointVector) ChainPosition(e int) ChainPosition { return ChainPosition{e, 0} }\nfunc (p *PointVector) Dimension() int { return 0 }\nfunc (p *PointVector) IsEmpty() bool { return defaultShapeIsEmpty(p) }\n\nfunc (p *PointVector) typeTag() typeTag { return typeTagPointVector }\nfunc (p *PointVector) privateInterface() {}\n\nfunc (p *PointVector) IsFull() bool ", "output": "{ return defaultShapeIsFull(p) }"} {"input": "package alert\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/opsgenie/opsgenie-go-sdk-v2/client\"\n\t\"github.com/pkg/errors\"\n)\n\ntype DeleteAttachmentRequest struct {\n\tclient.BaseRequest\n\tIdentifierType AlertIdentifier\n\tIdentifierValue string\n\tAttachmentId string\n\tUser string\n}\n\nfunc (r *DeleteAttachmentRequest) Validate() error {\n\tif r.AttachmentId == \"\" {\n\t\treturn errors.New(\"AttachmentId can not be empty\")\n\t}\n\n\tif r.IdentifierValue == \"\" {\n\t\treturn errors.New(\"Identifier can not be empty\")\n\t}\n\treturn nil\n}\n\nfunc (r *DeleteAttachmentRequest) ResourcePath() string {\n\n\treturn \"/v2/alerts/\" + r.IdentifierValue + \"/attachments/\" + r.AttachmentId\n}\n\nfunc (r *DeleteAttachmentRequest) Method() string {\n\treturn http.MethodDelete\n}\n\n\n\nfunc (r *DeleteAttachmentRequest) RequestParams() map[string]string ", "output": "{\n\n\tparams := make(map[string]string)\n\n\tif r.IdentifierType == ALIAS {\n\t\tparams[\"alertIdentifierType\"] = \"alias\"\n\n\t} else if r.IdentifierType == TINYID {\n\t\tparams[\"alertIdentifierType\"] = \"tiny\"\n\n\t} else {\n\t\tparams[\"alertIdentifierType\"] = \"id\"\n\n\t}\n\n\tif r.User != \"\" {\n\t\tparams[\"user\"] = r.User\n\t}\n\n\treturn params\n}"} {"input": "package jwt\n\nfunc verifyPrincipals(pcpls, auds []string) bool {\n\n\tfound := -1\n\tfor i, p := range pcpls {\n\t\tfor _, v := range auds {\n\t\t\tif p == v {\n\t\t\t\tfound++\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif found != i {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\n\n\n\n\n\nfunc ValidAudience(a, b interface{}) bool ", "output": "{\n\ts1, ok := a.(string)\n\tif ok {\n\t\tif s2, ok := b.(string); ok {\n\t\t\treturn s1 == s2\n\t\t}\n\t\ta2, ok := b.([]string)\n\t\treturn ok && verifyPrincipals([]string{s1}, a2)\n\t}\n\n\ta1, ok := a.([]string)\n\tif !ok {\n\t\treturn false\n\t}\n\tif a2, ok := b.([]string); ok {\n\t\treturn verifyPrincipals(a1, a2)\n\t}\n\ts2, ok := b.(string)\n\treturn ok && len(a1) == 1 && a1[0] == s2\n}"} {"input": "package iso20022\n\n\ntype TransactionIdentifications3 struct {\n\n\tAccountOwnerTransactionIdentification *Max35Text `xml:\"AcctOwnrTxId\"`\n\n\tAccountServicerTransactionIdentification *Max35Text `xml:\"AcctSvcrTxId,omitempty\"`\n\n\tMarketInfrastructureTransactionIdentification *Max35Text `xml:\"MktInfrstrctrTxId,omitempty\"`\n}\n\nfunc (t *TransactionIdentifications3) SetAccountOwnerTransactionIdentification(value string) {\n\tt.AccountOwnerTransactionIdentification = (*Max35Text)(&value)\n}\n\n\n\nfunc (t *TransactionIdentifications3) SetMarketInfrastructureTransactionIdentification(value string) {\n\tt.MarketInfrastructureTransactionIdentification = (*Max35Text)(&value)\n}\n\nfunc (t *TransactionIdentifications3) SetAccountServicerTransactionIdentification(value string) ", "output": "{\n\tt.AccountServicerTransactionIdentification = (*Max35Text)(&value)\n}"} {"input": "package ig\n\nimport \"fmt\"\n\n\nfunc (ic *IntelliClimate) SetTempTarget(target float64) error {\n\treturn fmt.Errorf(\"not implemented\")\n}\n\n\nfunc (ic *IntelliClimate) SetCO2Target(target float64) error {\n\treturn fmt.Errorf(\"not implemented\")\n}\n\n\nfunc (ic *IntelliClimate) SetRHTarget(target float64) error {\n\treturn fmt.Errorf(\"not implemented\")\n}\n\n\n\n\n\nfunc (ic *IntelliClimate) DisableCO2Dosing() error {\n\treturn fmt.Errorf(\"not implemented\")\n}\n\nfunc (ic *IntelliClimate) EnableCO2Dosing() error ", "output": "{\n\treturn fmt.Errorf(\"not implemented\")\n}"} {"input": "package echo\n\ntype (\n\tGroup struct {\n\t\techo Echo\n\t}\n)\n\nfunc (g *Group) Use(m ...Middleware) {\n\tfor _, h := range m {\n\t\tg.echo.middleware = append(g.echo.middleware, wrapMiddleware(h))\n\t}\n}\n\nfunc (g *Group) Connect(path string, h Handler) {\n\tg.echo.Connect(path, h)\n}\n\nfunc (g *Group) Delete(path string, h Handler) {\n\tg.echo.Delete(path, h)\n}\n\nfunc (g *Group) Get(path string, h Handler) {\n\tg.echo.Get(path, h)\n}\n\n\n\nfunc (g *Group) Options(path string, h Handler) {\n\tg.echo.Options(path, h)\n}\n\nfunc (g *Group) Patch(path string, h Handler) {\n\tg.echo.Patch(path, h)\n}\n\nfunc (g *Group) Post(path string, h Handler) {\n\tg.echo.Post(path, h)\n}\n\nfunc (g *Group) Put(path string, h Handler) {\n\tg.echo.Put(path, h)\n}\n\nfunc (g *Group) Trace(path string, h Handler) {\n\tg.echo.Trace(path, h)\n}\n\nfunc (g *Group) WebSocket(path string, h HandlerFunc) {\n\tg.echo.WebSocket(path, h)\n}\n\nfunc (g *Group) Static(path, root string) {\n\tg.echo.Static(path, root)\n}\n\nfunc (g *Group) ServeDir(path, root string) {\n\tg.echo.ServeDir(path, root)\n}\n\nfunc (g *Group) ServeFile(path, file string) {\n\tg.echo.ServeFile(path, file)\n}\n\nfunc (g *Group) Group(prefix string, m ...Middleware) *Group {\n\treturn g.echo.Group(prefix, m...)\n}\n\nfunc (g *Group) Head(path string, h Handler) ", "output": "{\n\tg.echo.Head(path, h)\n}"} {"input": "package cmd\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/ghodss/yaml\"\n\t\"github.com/spf13/cobra\"\n)\n\n\nfunc NameFromCommandArgs(cmd *cobra.Command, args []string, noNameRequired bool) (string, error) {\n\tif len(args) == 0 {\n\n\t\treturn \"\", getErrorForNoName(noNameRequired)\n\t}\n\treturn args[0], nil\n}\n\nfunc getErrorForNoName(noNameRequired bool) error {\n\tif noNameRequired {\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"NAME is required\")\n}\n\nfunc prettyprint(b []byte) ([]byte, error) {\n\tvar out bytes.Buffer\n\terr := json.Indent(&out, b, \"\", \" \")\n\treturn out.Bytes(), err\n}\n\n\n\nfunc PrintOutput(format string, object interface{}) error ", "output": "{\n\tvar msg string\n\ttmpCluster := object\n\tif format == \"yaml\" {\n\t\ty, err := yaml.Marshal(tmpCluster)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmsg += string(y)\n\t\tfmt.Printf(msg)\n\t} else if format == \"json\" {\n\t\ty, err := json.Marshal(tmpCluster)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpmsg, err := prettyprint(y)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmsg += string(pmsg)\n\t\tfmt.Printf(msg)\n\t}\n\treturn nil\n}"} {"input": "package flag\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/hashicorp/errwrap\"\n)\n\n\ntype OptionList struct {\n\tOptions []string\n\tallOptions []string\n\tpermissible map[string]struct{}\n\ttypeName string\n}\n\n\n\n\n\n\nfunc (ol *OptionList) Set(s string) error {\n\tol.Options = nil\n\tif s == \"\" {\n\t\treturn nil\n\t}\n\toptions := strings.Split(strings.ToLower(s), \",\")\n\tseen := map[string]struct{}{}\n\tfor _, o := range options {\n\t\tif _, ok := ol.permissible[o]; !ok {\n\t\t\treturn fmt.Errorf(\"unknown option %q\", o)\n\t\t}\n\t\tif _, ok := seen[o]; ok {\n\t\t\treturn fmt.Errorf(\"duplicated option %q\", o)\n\t\t}\n\t\tol.Options = append(ol.Options, o)\n\t\tseen[o] = struct{}{}\n\t}\n\n\treturn nil\n}\n\nfunc (ol *OptionList) String() string {\n\treturn strings.Join(ol.Options, \",\")\n}\n\nfunc (ol *OptionList) Type() string {\n\treturn ol.typeName\n}\n\nfunc (ol *OptionList) PermissibleString() string {\n\treturn fmt.Sprintf(`\"%s\"`, strings.Join(ol.allOptions, `\", \"`))\n}\n\nfunc NewOptionList(permissibleOptions []string, defaultOptions string) (*OptionList, error) ", "output": "{\n\tpermissible := make(map[string]struct{})\n\tol := &OptionList{\n\t\tallOptions: permissibleOptions,\n\t\tpermissible: permissible,\n\t\ttypeName: \"OptionList\",\n\t}\n\n\tfor _, o := range permissibleOptions {\n\t\tol.permissible[o] = struct{}{}\n\t}\n\n\tif err := ol.Set(defaultOptions); err != nil {\n\t\treturn nil, errwrap.Wrap(errors.New(\"problem setting defaults\"), err)\n\t}\n\n\treturn ol, nil\n}"} {"input": "package cmd\n\nimport (\n\t\"github.com/cloudfoundry/bosh-init/director/template\"\n\tboshui \"github.com/cloudfoundry/bosh-init/ui\"\n)\n\ntype BuildManifestCmd struct {\n\tui boshui.UI\n}\n\nfunc NewBuildManifestCmd(ui boshui.UI) BuildManifestCmd {\n\treturn BuildManifestCmd{\n\t\tui: ui,\n\t}\n}\n\n\n\nfunc (c BuildManifestCmd) Run(opts BuildManifestOpts) error ", "output": "{\n\tvariables := opts.VarFlags.AsVariables()\n\n\ttemplate := template.NewTemplate(opts.Args.Manifest.Bytes)\n\n\tevaluatedManifest, err := template.Evaluate(variables)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.ui.PrintBlock(string(evaluatedManifest))\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/keybase/client/go/kbfs/env\"\n\t\"github.com/keybase/client/go/kbfs/fsrpc\"\n\t\"github.com/keybase/client/go/kbfs/libgit\"\n\t\"github.com/keybase/client/go/kbfs/libkbfs\"\n\t\"github.com/keybase/client/go/protocol/keybase1\"\n\t\"golang.org/x/net/context\"\n)\n\nconst gitRenameUsageStr = `Usage:\n kbfstool git rename /keybase/tlf/path oldName newName\n`\n\nfunc doGitRename(ctx context.Context,\n\trpcHandler *libgit.RPCHandler, tlfStr, oldName, newName string) error {\n\tp, err := fsrpc.NewPath(tlfStr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif p.PathType != fsrpc.TLFPathType {\n\t\treturn fmt.Errorf(\"%q is not a TLF path\", tlfStr)\n\t}\n\tif len(p.TLFComponents) > 0 {\n\t\treturn fmt.Errorf(\"%q is not the root path of a TLF\", tlfStr)\n\t}\n\tfolder := keybase1.FolderHandle{\n\t\tName: p.TLFName,\n\t\tFolderType: p.TLFType.FolderType(),\n\t}\n\n\treturn rpcHandler.RenameRepo(ctx, folder, oldName, newName)\n}\n\n\n\nfunc gitRename(ctx context.Context, config libkbfs.Config, args []string) (exitStatus int) ", "output": "{\n\tflags := flag.NewFlagSet(\"kbfs git rename\", flag.ContinueOnError)\n\terr := flags.Parse(args)\n\tif err != nil {\n\t\tprintError(\"git rename\", err)\n\t\treturn 1\n\t}\n\n\tinputs := flags.Args()\n\tif len(inputs) != 3 {\n\t\tfmt.Print(gitRenameUsageStr)\n\t\treturn 1\n\t}\n\n\tkbfsCtx := env.NewContext()\n\trpcHandler, shutdown := libgit.NewRPCHandlerWithCtx(kbfsCtx, config, nil)\n\tdefer shutdown()\n\n\terr = doGitRename(ctx, rpcHandler, inputs[0], inputs[1], inputs[2])\n\tif err != nil {\n\t\tprintError(\"git rename\", err)\n\t\treturn 1\n\t}\n\n\treturn 0\n}"} {"input": "package textures\n\nimport \"github.com/fileformats/graphics/jt/model\"\n\n\ntype TextureV1 struct {\n\tTextureType int32\n\n\tTextureEnvironment TextureEnvironment\n\tTextureChannel uint32\n\tReserved uint32\n\tInlineImageStorageFlag uint8\n\tImageCount int32\n}\n\n\n\nfunc (n *TextureV1) Read(c *model.Context) error ", "output": "{\n\tif c.Version.Equal(model.V8) {\n\n\t}\n\tif c.Version.Equal(model.V9) {\n\n\t}\n\treturn c.Data.GetError()\n}"} {"input": "package main\n\nimport (\n\t\"encoding/hex\"\n\t\"errors\"\n)\n\n\n\n\n\ntype User struct {\n\tId uint32\n\tName string\n\tPassword string\n\tCertHash string\n\tEmail string\n\tTextureBlob string\n\tCommentBlob string\n\tLastChannelId int\n\tLastActive uint64\n}\n\n\nfunc NewUser(id uint32, name string) (user *User, err error) {\n\tif id < 0 {\n\t\treturn nil, errors.New(\"Invalid user id\")\n\t}\n\tif len(name) == 0 {\n\t\treturn nil, errors.New(\"Invalid username\")\n\t}\n\n\treturn &User{\n\t\tId: id,\n\t\tName: name,\n\t}, nil\n}\n\n\nfunc (user *User) HasComment() bool {\n\treturn len(user.CommentBlob) > 0\n}\n\n\n\n\n\n\nfunc (user *User) HasTexture() bool {\n\treturn len(user.TextureBlob) > 0\n}\n\n\n\nfunc (user *User) TextureBlobHashBytes() (buf []byte) {\n\tbuf, err := hex.DecodeString(user.TextureBlob)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn buf\n}\n\nfunc (user *User) CommentBlobHashBytes() (buf []byte) ", "output": "{\n\tbuf, err := hex.DecodeString(user.CommentBlob)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn buf\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"os/signal\"\n\n\t\"github.com/codegangsta/cli\"\n\t\"github.com/opsee/zuul/registration\"\n)\n\nconst (\n\tversion = \"0.0.1\"\n)\n\n\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"connect\"\n\tapp.Version = version\n\tapp.Usage = \"Consume connected messages and persist the data to Etcd\"\n\tapp.Action = connect\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName: \"etcd-address\",\n\t\t\tValue: os.Getenv(\"ETCD_ADDRESS\"),\n\t\t},\n\t\tcli.StringSliceFlag{\n\t\t\tName: \"nsqlookupd-tcp-address\",\n\t\t\tValue: &cli.StringSlice{},\n\t\t},\n\t\tcli.IntFlag{\n\t\t\tName: \"consumer-concurrency\",\n\t\t\tValue: 10,\n\t\t},\n\t}\n\n\tapp.Run(os.Args)\n}\n\nfunc connect(c *cli.Context) ", "output": "{\n\tetcd := c.String(\"etcd-address\")\n\tnsq := c.StringSlice(\"nsqlookupd-tcp-address\")\n\n\tsvc, err := registration.NewConsumer(\"connected\", etcd, nsq, c.Int(\"consumer-concurrency\"), 11)\n\tif err != nil {\n\t\tlog.Println(\"Unable to create consumer: etcd =\", etcd, \"nsq = \", nsq)\n\t\tlog.Fatal(err)\n\t}\n\n\tsigs := make(chan os.Signal, 1)\n\tsignal.Notify(sigs, os.Interrupt, os.Kill)\n\n\tsvc.Start()\n\n\ts := <-sigs\n\tsvc.Stop() \n\tlog.Println(\"Got signal, exiting:\", s)\n}"} {"input": "package v3_4_experimental\n\nimport (\n\t\"github.com/coreos/ignition/v2/config/merge\"\n\t\"github.com/coreos/ignition/v2/config/shared/errors\"\n\t\"github.com/coreos/ignition/v2/config/util\"\n\tprev \"github.com/coreos/ignition/v2/config/v3_3\"\n\t\"github.com/coreos/ignition/v2/config/v3_4_experimental/translate\"\n\t\"github.com/coreos/ignition/v2/config/v3_4_experimental/types\"\n\t\"github.com/coreos/ignition/v2/config/validate\"\n\n\t\"github.com/coreos/go-semver/semver\"\n\t\"github.com/coreos/vcontext/report\"\n)\n\nfunc Merge(parent, child types.Config) types.Config {\n\tres, _ := merge.MergeStructTranscribe(parent, child)\n\treturn res.(types.Config)\n}\n\n\n\n\n\n\n\n\nfunc ParseCompatibleVersion(raw []byte) (types.Config, report.Report, error) {\n\tversion, rpt, err := util.GetConfigVersion(raw)\n\tif err != nil {\n\t\treturn types.Config{}, rpt, err\n\t}\n\n\tif version == types.MaxVersion {\n\t\treturn Parse(raw)\n\t}\n\tprevCfg, r, err := prev.ParseCompatibleVersion(raw)\n\tif err != nil {\n\t\treturn types.Config{}, r, err\n\t}\n\treturn translate.Translate(prevCfg), r, nil\n}\n\nfunc Parse(rawConfig []byte) (types.Config, report.Report, error) ", "output": "{\n\tif len(rawConfig) == 0 {\n\t\treturn types.Config{}, report.Report{}, errors.ErrEmpty\n\t}\n\n\tvar config types.Config\n\tif rpt, err := util.HandleParseErrors(rawConfig, &config); err != nil {\n\t\treturn types.Config{}, rpt, err\n\t}\n\n\tversion, err := semver.NewVersion(config.Ignition.Version)\n\n\tif err != nil || *version != types.MaxVersion {\n\t\treturn types.Config{}, report.Report{}, errors.ErrUnknownVersion\n\t}\n\n\trpt := validate.ValidateWithContext(config, rawConfig)\n\tif rpt.IsFatal() {\n\t\treturn types.Config{}, rpt, errors.ErrInvalid\n\t}\n\n\treturn config, rpt, nil\n}"} {"input": "package graphql\n\nimport (\n\t\"errors\"\n\n\t\"github.com/equinux/graphql/gqlerrors\"\n\t\"github.com/equinux/graphql/language/ast\"\n)\n\n\n\nfunc NewLocatedErrorWithPath(err interface{}, nodes []ast.Node, path []interface{}) *gqlerrors.Error {\n\treturn newLocatedError(err, nodes, path)\n}\n\nfunc newLocatedError(err interface{}, nodes []ast.Node, path []interface{}) *gqlerrors.Error {\n\tif err, ok := err.(*gqlerrors.Error); ok {\n\t\treturn err\n\t}\n\n\tvar origError error\n\tmessage := \"An unknown error occurred.\"\n\tif err, ok := err.(error); ok {\n\t\tmessage = err.Error()\n\t\torigError = err\n\t}\n\tif err, ok := err.(string); ok {\n\t\tmessage = err\n\t\torigError = errors.New(err)\n\t}\n\tstack := message\n\treturn gqlerrors.NewErrorWithPath(\n\t\tmessage,\n\t\tnodes,\n\t\tstack,\n\t\tnil,\n\t\t[]int{},\n\t\tpath,\n\t\torigError,\n\t)\n}\n\nfunc FieldASTsToNodeASTs(fieldASTs []*ast.Field) []ast.Node {\n\tnodes := []ast.Node{}\n\tfor _, fieldAST := range fieldASTs {\n\t\tnodes = append(nodes, fieldAST)\n\t}\n\treturn nodes\n}\n\nfunc NewLocatedError(err interface{}, nodes []ast.Node) *gqlerrors.Error ", "output": "{\n\treturn newLocatedError(err, nodes, nil)\n}"} {"input": "package wire\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n\n\ntype fixedWriter struct {\n\tb []byte\n\tpos int\n}\n\n\n\n\n\n\nfunc (w *fixedWriter) Write(p []byte) (n int, err error) {\n\tlenp := len(p)\n\tif w.pos+lenp > cap(w.b) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\tn = lenp\n\tw.pos += copy(w.b[w.pos:], p)\n\treturn\n}\n\n\nfunc (w *fixedWriter) Bytes() []byte {\n\treturn w.b\n}\n\n\n\nfunc newFixedWriter(max int) io.Writer {\n\tb := make([]byte, max, max)\n\tfw := fixedWriter{b, 0}\n\treturn &fw\n}\n\n\n\ntype fixedReader struct {\n\tbuf []byte\n\tpos int\n\tiobuf *bytes.Buffer\n}\n\n\n\n\n\n\nfunc (fr *fixedReader) Read(p []byte) (n int, err error) {\n\tn, err = fr.iobuf.Read(p)\n\tfr.pos += n\n\treturn\n}\n\n\n\n\n\nfunc newFixedReader(max int, buf []byte) io.Reader ", "output": "{\n\tb := make([]byte, max, max)\n\tif buf != nil {\n\t\tcopy(b[:], buf)\n\t}\n\n\tiobuf := bytes.NewBuffer(b)\n\tfr := fixedReader{b, 0, iobuf}\n\treturn &fr\n}"} {"input": "package math\n\n\n\n\n\n\n\nfunc Floor(x float64) float64 {\n\tif x == 0 || x != x || x > MaxFloat64 || x < -MaxFloat64 { \n\t\treturn x\n\t}\n\tif x < 0 {\n\t\td, fract := Modf(-x)\n\t\tif fract != 0.0 {\n\t\t\td = d + 1\n\t\t}\n\t\treturn -d\n\t}\n\td, _ := Modf(x)\n\treturn d\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Trunc(x float64) float64 {\n\tif x == 0 || x != x || x > MaxFloat64 || x < -MaxFloat64 { \n\t\treturn x\n\t}\n\td, _ := Modf(x)\n\treturn d\n}\n\nfunc Ceil(x float64) float64 ", "output": "{ return -Floor(-x) }"} {"input": "package distribute\n\nimport (\n \"net/rpc\"\n \"net/http\"\n \"fmt\"\n)\n\ntype Worker struct {\n addr string\n addUrlChannel chan bool\n}\n\nfunc initWorker(addr string) *Worker{\n w := &Worker{}\n w.addr = addr\n w.addUrlChannel = make(chan bool)\n return w\n}\n\nfunc RunWorker(mAddr, wAddr string) {\n fmt.Println(\"=======RunWorker Begin=======\")\n w := initWorker(wAddr)\n \n register(mAddr, w.addr)\n fmt.Println(\"=======RunWorker End=======\")\n \n \n \n \n \n \n \n}\n\n\n\nfunc (w *Worker) Dojob(args *DojobArgs, res *DojobReply) error {\n fmt.Println(\"DoJob: JobType \", args.JobType)\n switch args.JobType {\n case \"Crawl\":\n \n \n \n }\n return nil\n}\n\nfunc startRpcWorker(w *Worker) {\n \n rpc.Register(w)\n rpc.HandleHTTP()\n err := http.ListenAndServe(w.addr, nil)\n fmt.Println(\"RegistrationServer: accept error\", err)\n \n \n \n \n \n \n}\n\nfunc register(mAddr, wAddr string) ", "output": "{\n args := &RegisterArgs{}\n args.Worker = wAddr\n var reply RegisterReply\n call(mAddr, \"Master.Register\", args, &reply)\n}"} {"input": "package json\n\nimport \"encoding/json\"\nimport \"net/http\"\n\n\nfunc String(writer http.ResponseWriter, request *http.Request, data string) {\n\n \n writer.Header().Set(\"Content-Type\", \"application/json\")\n\n \n type SimpleResponse struct {\n Data string\n }\n\n res := SimpleResponse {\n Data: data,\n }\n\n result, error := json.Marshal(res)\n\n if error == nil {\n \n writer.Write([]byte(result))\n } else {\n writer.Write([]byte(\"Error\"))\n }\n}\n\n\n\n\nfunc Struct(writer http.ResponseWriter, request *http.Request, data interface{}, indent bool) ", "output": "{\n\n \n writer.Header().Set(\"Content-Type\", \"application/json\")\n\n \n type SimpleResponse struct {\n Data interface {}\n }\n\n res := SimpleResponse {\n Data: data,\n }\n\n var result []byte\n var error error\n\n if indent {\n result, error = json.MarshalIndent(res, \"\", \"\")\n } else {\n result, error = json.Marshal(res)\n }\n\n if error == nil {\n \n writer.Write([]byte(result))\n } else {\n writer.Write([]byte(\"Error\"))\n }\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\n\tpb \"github.com/hnakamur/hello_grpc_go/helloworld\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc\"\n)\n\nconst (\n\taddress = \"localhost:50051\"\n\tdefaultName = \"world\"\n)\n\nfunc main() {\n\taddr := flag.String(\"addr\", \"localhost:50051\", \"server address\")\n\tname := flag.String(\"name\", defaultName, \"name\")\n\tloop := flag.Bool(\"loop\", false, \"enable loop\")\n\tsleep := flag.Duration(\"sleep\", 10*time.Millisecond, \"sleep time in loop\")\n\tflag.Parse()\n\n\tlog.SetFlags(log.LstdFlags | log.Lmicroseconds)\n\n\tif *loop {\n\t\tfor {\n\t\t\terr := sayHello(*addr, *name)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t}\n\t\t\ttime.Sleep(*sleep)\n\t\t}\n\t} else {\n\t\terr := sayHello(*addr, *name)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n}\n\n\n\nfunc sayHello(address, name string) error ", "output": "{\n\tconn, err := grpc.Dial(address, grpc.WithInsecure())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\tc := pb.NewGreeterClient(conn)\n\n\tr, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not greet: %v\", err)\n\t}\n\tlog.Printf(\"Greeting: %s\", r.Message)\n\treturn nil\n}"} {"input": "package gonum\n\nimport \"gonum.org/v1/gonum/lapack\"\n\n\n\n\ntype Implementation struct{}\n\nvar _ lapack.Float64 = Implementation{}\n\nfunc min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc max(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n\n\n\nconst (\n\tdlamchE = 1.0 / (1 << 53)\n\n\tdlamchB = 2\n\n\tdlamchP = dlamchB * dlamchE\n\n\tdlamchS = 1.0 / (1 << 256) / (1 << 256) / (1 << 256) / (1 << 254)\n)\n\nfunc abs(a int) int ", "output": "{\n\tif a < 0 {\n\t\treturn -a\n\t}\n\treturn a\n}"} {"input": "package treemap\n\nimport (\n\t\"github.com/emirpasic/gods/containers\"\n\trbt \"github.com/emirpasic/gods/trees/redblacktree\"\n)\n\nfunc assertIteratorImplementation() {\n\tvar _ containers.ReverseIteratorWithKey = (*Iterator)(nil)\n}\n\n\ntype Iterator struct {\n\titerator rbt.Iterator\n}\n\n\nfunc (m *Map) Iterator() Iterator {\n\treturn Iterator{iterator: m.tree.Iterator()}\n}\n\n\n\n\n\nfunc (iterator *Iterator) Next() bool {\n\treturn iterator.iterator.Next()\n}\n\n\n\n\nfunc (iterator *Iterator) Prev() bool {\n\treturn iterator.iterator.Prev()\n}\n\n\n\nfunc (iterator *Iterator) Value() interface{} {\n\treturn iterator.iterator.Value()\n}\n\n\n\n\n\n\n\nfunc (iterator *Iterator) Begin() {\n\titerator.iterator.Begin()\n}\n\n\n\nfunc (iterator *Iterator) End() {\n\titerator.iterator.End()\n}\n\n\n\n\nfunc (iterator *Iterator) First() bool {\n\treturn iterator.iterator.First()\n}\n\n\n\n\nfunc (iterator *Iterator) Last() bool {\n\treturn iterator.iterator.Last()\n}\n\nfunc (iterator *Iterator) Key() interface{} ", "output": "{\n\treturn iterator.iterator.Key()\n}"} {"input": "package pdf417\n\nimport \"math\"\n\nconst (\n\tminCols = 2\n\tmaxCols = 30\n\tmaxRows = 30\n\tminRows = 2\n\tmoduleHeight = 2\n\tpreferred_ratio = 3.0\n)\n\nfunc calculateNumberOfRows(m, k, c int) int {\n\tr := ((m + 1 + k) / c) + 1\n\tif c*r >= (m + 1 + k + c) {\n\t\tr--\n\t}\n\treturn r\n}\n\n\n\nfunc calcDimensions(dataWords, eccWords int) (cols, rows int) ", "output": "{\n\tratio := 0.0\n\tcols = 0\n\trows = 0\n\n\tfor c := minCols; c <= maxCols; c++ {\n\t\tr := calculateNumberOfRows(dataWords, eccWords, c)\n\n\t\tif r < minRows {\n\t\t\tbreak\n\t\t}\n\n\t\tif r > maxRows {\n\t\t\tcontinue\n\t\t}\n\n\t\tnewRatio := float64(17*cols+69) / float64(rows*moduleHeight)\n\t\tif rows != 0 && math.Abs(newRatio-preferred_ratio) > math.Abs(ratio-preferred_ratio) {\n\t\t\tcontinue\n\t\t}\n\n\t\tratio = newRatio\n\t\tcols = c\n\t\trows = r\n\t}\n\n\tif rows == 0 {\n\t\tr := calculateNumberOfRows(dataWords, eccWords, minCols)\n\t\tif r < minRows {\n\t\t\trows = minRows\n\t\t\tcols = minCols\n\t\t}\n\t}\n\n\treturn\n}"} {"input": "package operations\n\n\n\n\nimport (\n\t\"net/http\"\n\n\tmiddleware \"github.com/go-openapi/runtime/middleware\"\n)\n\n\ntype DecommissionSiteHandlerFunc func(DecommissionSiteParams) middleware.Responder\n\n\n\n\n\ntype DecommissionSiteHandler interface {\n\tHandle(DecommissionSiteParams) middleware.Responder\n}\n\n\nfunc NewDecommissionSite(ctx *middleware.Context, handler DecommissionSiteHandler) *DecommissionSite {\n\treturn &DecommissionSite{Context: ctx, Handler: handler}\n}\n\n\ntype DecommissionSite struct {\n\tContext *middleware.Context\n\tHandler DecommissionSiteHandler\n}\n\nfunc (o *DecommissionSite) ServeHTTP(rw http.ResponseWriter, r *http.Request) {\n\troute, rCtx, _ := o.Context.RouteInfo(r)\n\tif rCtx != nil {\n\t\tr = rCtx\n\t}\n\tvar Params = NewDecommissionSiteParams()\n\n\tif err := o.Context.BindValidRequest(r, route, &Params); err != nil { \n\t\to.Context.Respond(rw, r, route.Produces, route, err)\n\t\treturn\n\t}\n\n\tres := o.Handler.Handle(Params) \n\n\to.Context.Respond(rw, r, route.Produces, route, res)\n\n}\n\nfunc (fn DecommissionSiteHandlerFunc) Handle(params DecommissionSiteParams) middleware.Responder ", "output": "{\n\treturn fn(params)\n}"} {"input": "package servicelabel\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/namsral/flag\"\n\n\t\"go.ligato.io/cn-infra/v2/infra\"\n\t\"go.ligato.io/cn-infra/v2/logging/logrus\"\n)\n\nvar microserviceLabelFlag string\n\nfunc init() {\n\tflag.StringVar(µserviceLabelFlag, \"microservice-label\", \"vpp1\", fmt.Sprintf(\"microservice label; also set via '%v' env variable.\", MicroserviceLabelEnvVar))\n}\n\n\ntype Plugin struct {\n\tinfra.PluginName\n\tMicroserviceLabel string\n}\n\n\nfunc (p *Plugin) Init() error {\n\tif p.MicroserviceLabel == \"\" {\n\t\tp.MicroserviceLabel = microserviceLabelFlag\n\t}\n\tlogrus.DefaultLogger().Debugf(\"Microservice label is set to %v\", p.MicroserviceLabel)\n\treturn nil\n}\n\n\n\n\n\n\nfunc (p *Plugin) GetAgentLabel() string {\n\treturn p.MicroserviceLabel\n}\n\n\n\nfunc (p *Plugin) GetAgentPrefix() string {\n\treturn agentPrefix + p.MicroserviceLabel + \"/\"\n}\n\n\n\nfunc (p *Plugin) GetDifferentAgentPrefix(microserviceLabel string) string {\n\treturn GetDifferentAgentPrefix(microserviceLabel)\n}\n\n\n\nfunc (p *Plugin) GetAllAgentsPrefix() string {\n\treturn GetAllAgentsPrefix()\n}\n\nfunc (p *Plugin) Close() error ", "output": "{\n\treturn nil\n}"} {"input": "package core\n\nimport \"go/ast\"\n\nfunc resolveIdent(n *ast.Ident, c *Context) bool {\n\tif n.Obj == nil || n.Obj.Kind != ast.Var {\n\t\treturn true\n\t}\n\tif node, ok := n.Obj.Decl.(ast.Node); ok {\n\t\treturn TryResolve(node, c)\n\t}\n\treturn false\n}\n\nfunc resolveAssign(n *ast.AssignStmt, c *Context) bool {\n\tfor _, arg := range n.Rhs {\n\t\tif !TryResolve(arg, c) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\nfunc resolveBinExpr(n *ast.BinaryExpr, c *Context) bool {\n\treturn (TryResolve(n.X, c) && TryResolve(n.Y, c))\n}\n\nfunc resolveCallExpr(n *ast.CallExpr, c *Context) bool {\n\treturn false\n}\n\n\n\n\nfunc TryResolve(n ast.Node, c *Context) bool {\n\tswitch node := n.(type) {\n\tcase *ast.BasicLit:\n\t\treturn true\n\n\tcase *ast.CompositeLit:\n\t\treturn resolveCompLit(node, c)\n\n\tcase *ast.Ident:\n\t\treturn resolveIdent(node, c)\n\n\tcase *ast.AssignStmt:\n\t\treturn resolveAssign(node, c)\n\n\tcase *ast.CallExpr:\n\t\treturn resolveCallExpr(node, c)\n\n\tcase *ast.BinaryExpr:\n\t\treturn resolveBinExpr(node, c)\n\t}\n\n\treturn false\n}\n\nfunc resolveCompLit(n *ast.CompositeLit, c *Context) bool ", "output": "{\n\tfor _, arg := range n.Elts {\n\t\tif !TryResolve(arg, c) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}"} {"input": "package app\n\ntype Page interface {\n\tGetTemplate() string\n\tSetSessionData(u User)\n}\n\ntype PageWeb struct {\n\tTitrePage string\n\tTemplate string\n\tSessIdUser int64\n\tSessNameUser string\n\tSessIsLogged bool\n}\n\nfunc (p *PageWeb) GetTemplate() string {\n\treturn p.Template\n}\n\n\n\nfunc (p *PageWeb) SetSessionData(u User) ", "output": "{\n\tif u.Id != 0 && u.Prenom != \"\" {\n\t\tp.SessIdUser = u.Id\n\t\tp.SessIsLogged = true\n\t\tp.SessNameUser = u.Prenom\n\n\t} else {\n\t\tp.SessIdUser = 0\n\t\tp.SessIsLogged = false\n\t\tp.SessNameUser = \"\"\n\t}\n}"} {"input": "package chatwork\n\nimport (\n\t\"encoding/json\"\n\t\"net/url\"\n\t\"strings\"\n)\n\ntype MessageResult struct {\n\tMessageId int `json:\"message_id\"`\n}\n\nvar format string = \"/rooms/{roomId}/messages\"\n\nfunc (api *Client) PostMessage(roomId, text string) int {\n\ttext = escapeMessage(text)\n\tapiUrl := CHATWORK_API + strings.Replace(format, \"{roomId}\", roomId, 1)\n\n\tvalues := url.Values{}\n\tvalues.Add(\"body\", text)\n\n\tcontents := api.Request(\"POST\", apiUrl, values.Encode())\n\tvar result MessageResult\n\tjson.Unmarshal(contents, &result)\n\treturn result.MessageId\n}\n\n\n\nfunc escapeMessage(message string) string ", "output": "{\n\treplacer := strings.NewReplacer(\"&\", \"&\", \"<\", \"<\", \">\", \">\")\n\treturn replacer.Replace(message)\n}"} {"input": "package main\n\nimport \"testing\"\n\nvar stanzaChordTests = []struct {\n\tin Stanza\n\texpected bool\n}{\n\t{\n\t\tStanza{},\n\t\tfalse,\n\t},\n\t{\n\t\tStanza{Lines: []Line{\n\t\t\tLine{\n\t\t\t\tText: \"Line2\",\n\t\t\t\tChords: []Chord{},\n\t\t\t},\n\t\t\t\t}},\n\t\tfalse,\n\t},\n\t{\n\t\tStanza{Lines: []Line{\n\t\t\tLine{\n\t\t\t\tText: \"Line2\",\n\t\t\t\tChords: []Chord{Chord{}},\n\t\t\t},\n\t\t\t\t}},\n\t\ttrue,\n\t},\n}\n\n\n\n\n\nfunc TestStanzaHasChords(t *testing.T) ", "output": "{\n\tfor i, ct := range stanzaChordTests {\n\t\tactual := ct.in.HasChords()\n\n\t\tif actual != ct.expected {\n\t\t\tt.Errorf(\"Stanza(%d), expected %v, actual %v\", i, ct.expected, actual)\n\t\t}\n\t}\n}"} {"input": "package goblueboxapi\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"testing\"\n)\n\nconst (\n\tcustomerID = \"customer_id\"\n\tapiKey = \"api_key\"\n)\n\nvar (\n\tmux *http.ServeMux\n\tclient *Client\n\tserver *httptest.Server\n)\n\nfunc setup() {\n\tmux = http.NewServeMux()\n\tserver = httptest.NewServer(mux)\n\n\tclient = NewClient(customerID, apiKey)\n\tclient.BaseURL, _ = url.Parse(server.URL)\n}\n\nfunc teardown() {\n\tserver.Close()\n}\n\n\n\nfunc testMethod(t *testing.T, r *http.Request, want string) ", "output": "{\n\tif want != r.Method {\n\t\tt.Errorf(\"Request method = %v, want %v\", r.Method, want)\n\t}\n}"} {"input": "package parser\n\nimport \"bytes\"\n\n\ntype DropBehavior int\n\n\nconst (\n\tDropDefault DropBehavior = iota\n\tDropRestrict\n\tDropCascade\n)\n\nvar dropBehaviorName = [...]string{\n\tDropDefault: \"\",\n\tDropRestrict: \"RESTRICT\",\n\tDropCascade: \"CASCADE\",\n}\n\nfunc (d DropBehavior) String() string {\n\treturn dropBehaviorName[d]\n}\n\n\ntype DropDatabase struct {\n\tName Name\n\tIfExists bool\n}\n\n\nfunc (node *DropDatabase) Format(buf *bytes.Buffer, f FmtFlags) {\n\tbuf.WriteString(\"DROP DATABASE \")\n\tif node.IfExists {\n\t\tbuf.WriteString(\"IF EXISTS \")\n\t}\n\tFormatNode(buf, f, node.Name)\n}\n\n\ntype DropIndex struct {\n\tIndexList TableNameWithIndexList\n\tIfExists bool\n\tDropBehavior DropBehavior\n}\n\n\nfunc (node *DropIndex) Format(buf *bytes.Buffer, f FmtFlags) {\n\tbuf.WriteString(\"DROP INDEX \")\n\tif node.IfExists {\n\t\tbuf.WriteString(\"IF EXISTS \")\n\t}\n\tFormatNode(buf, f, node.IndexList)\n\tif node.DropBehavior != DropDefault {\n\t\tbuf.WriteByte(' ')\n\t\tbuf.WriteString(node.DropBehavior.String())\n\t}\n}\n\n\ntype DropTable struct {\n\tNames QualifiedNames\n\tIfExists bool\n\tDropBehavior DropBehavior\n}\n\n\n\n\nfunc (node *DropTable) Format(buf *bytes.Buffer, f FmtFlags) ", "output": "{\n\tbuf.WriteString(\"DROP TABLE \")\n\tif node.IfExists {\n\t\tbuf.WriteString(\"IF EXISTS \")\n\t}\n\tFormatNode(buf, f, node.Names)\n\tif node.DropBehavior != DropDefault {\n\t\tbuf.WriteByte(' ')\n\t\tbuf.WriteString(node.DropBehavior.String())\n\t}\n}"} {"input": "package util\n\nimport (\n\t\"testing\"\n\n\tkubeadmapi \"k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm\"\n)\n\nfunc TestTokenParseErrors(t *testing.T) {\n\tinvalidTokens := []string{\n\t\t\"1234567890123456789012\",\n\t\t\"12345.1234567890123456\",\n\t\t\".1234567890123456\",\n\t\t\"123456.1234567890.123456\",\n\t}\n\n\tfor _, token := range invalidTokens {\n\t\tif _, _, err := ParseToken(token); err == nil {\n\t\t\tt.Errorf(\"generateTokenIfNeeded did not return an error for this invalid token: [%s]\", token)\n\t\t}\n\t}\n}\n\nfunc TestGenerateToken(t *testing.T) {\n\tvar cfg kubeadmapi.TokenDiscovery\n\n\tGenerateToken(&cfg)\n\tif len(cfg.ID) != 6 {\n\t\tt.Errorf(\"failed GenerateToken first part length:\\n\\texpected: 6\\n\\t actual: %d\", len(cfg.ID))\n\t}\n\tif len(cfg.Secret) != 16 {\n\t\tt.Errorf(\"failed GenerateToken first part length:\\n\\texpected: 16\\n\\t actual: %d\", len(cfg.Secret))\n\t}\n}\n\n\n\nfunc TestRandBytes(t *testing.T) ", "output": "{\n\tvar randTest = []int{\n\t\t0,\n\t\t1,\n\t\t2,\n\t\t3,\n\t\t100,\n\t}\n\n\tfor _, rt := range randTest {\n\t\tactual, err := RandBytes(rt)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"failed RandBytes: %v\", err)\n\t\t}\n\t\tif len(actual) != rt*2 {\n\t\t\tt.Errorf(\"failed RandBytes:\\n\\texpected: %d\\n\\t actual: %d\\n\", rt*2, len(actual))\n\t\t}\n\t}\n}"} {"input": "package logging_test\n\nimport (\n\t\"cloud.google.com/go/logging/apiv2\"\n\t\"golang.org/x/net/context\"\n\tloggingpb \"google.golang.org/genproto/googleapis/logging/v2\"\n)\n\nfunc ExampleNewConfigClient() {\n\tctx := context.Background()\n\tc, err := logging.NewConfigClient(ctx)\n\tif err != nil {\n\t}\n\t_ = c\n}\n\nfunc ExampleConfigClient_ListSinks() {\n\tctx := context.Background()\n\tc, err := logging.NewConfigClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.ListSinksRequest{\n\t}\n\tit := c.ListSinks(ctx, req)\n\tfor {\n\t\tresp, err := it.Next()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\t_ = resp\n\t}\n}\n\nfunc ExampleConfigClient_GetSink() {\n\tctx := context.Background()\n\tc, err := logging.NewConfigClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.GetSinkRequest{\n\t}\n\tresp, err := c.GetSink(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\nfunc ExampleConfigClient_CreateSink() {\n\tctx := context.Background()\n\tc, err := logging.NewConfigClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.CreateSinkRequest{\n\t}\n\tresp, err := c.CreateSink(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\n\n\nfunc ExampleConfigClient_DeleteSink() {\n\tctx := context.Background()\n\tc, err := logging.NewConfigClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.DeleteSinkRequest{\n\t}\n\terr = c.DeleteSink(ctx, req)\n\tif err != nil {\n\t}\n}\n\nfunc ExampleConfigClient_UpdateSink() ", "output": "{\n\tctx := context.Background()\n\tc, err := logging.NewConfigClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &loggingpb.UpdateSinkRequest{\n\t}\n\tresp, err := c.UpdateSink(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}"} {"input": "package pool\n\nimport (\n\n)\n\ntype ObjPool struct {\n\tobj chan interface{}\n\tNew func() interface{}\n}\n\n\n\nfunc (p *ObjPool) Get() interface{} {\n\tselect {\n\tcase o := <-p.obj:\n\t\treturn o\n\tdefault:\n\t\treturn p.New()\n\t}\n}\n\nfunc (p *ObjPool) Put(o interface{}) {\n\tselect {\n\tcase p.obj <- o:\n\tdefault:\n\t}\n}\n\nfunc NewObjPool() *ObjPool ", "output": "{\n\treturn &ObjPool{\n\t\tobj: make(chan interface{}, 200),\n\t}\n}"} {"input": "package l3plugin\n\nimport (\n\t\"go.ligato.io/cn-infra/v2/config\"\n\t\"go.ligato.io/cn-infra/v2/logging\"\n\n\t\"go.ligato.io/vpp-agent/v3/plugins/kvscheduler\"\n\t\"go.ligato.io/vpp-agent/v3/plugins/linux/ifplugin\"\n\t\"go.ligato.io/vpp-agent/v3/plugins/linux/nsplugin\"\n\t\"go.ligato.io/vpp-agent/v3/plugins/netalloc\"\n)\n\n\nvar DefaultPlugin = *NewPlugin()\n\n\n\n\n\ntype Option func(*L3Plugin)\n\n\nfunc UseDeps(f func(*Deps)) Option {\n\treturn func(p *L3Plugin) {\n\t\tf(&p.Deps)\n\t}\n}\n\nfunc NewPlugin(opts ...Option) *L3Plugin ", "output": "{\n\tp := &L3Plugin{}\n\n\tp.PluginName = \"linux-l3plugin\"\n\tp.KVScheduler = &kvscheduler.DefaultPlugin\n\tp.NsPlugin = &nsplugin.DefaultPlugin\n\tp.AddrAlloc = &netalloc.DefaultPlugin\n\tp.IfPlugin = &ifplugin.DefaultPlugin\n\n\tfor _, o := range opts {\n\t\to(p)\n\t}\n\n\tif p.Log == nil {\n\t\tp.Log = logging.ForPlugin(p.String())\n\t}\n\tif p.Cfg == nil {\n\t\tp.Cfg = config.ForPlugin(p.String(),\n\t\t\tconfig.WithCustomizedFlag(config.FlagName(p.String()), \"linux-l3plugin.conf\"),\n\t\t)\n\t}\n\n\treturn p\n}"} {"input": "package common\n\nimport (\n\t\"os/exec\"\n)\n\nconst VMWARE_PLAYER_VERSION = \"6\"\n\n\n\n\ntype Player6Driver struct {\n\tPlayer5Driver\n}\n\nfunc (d *Player6Driver) Clone(dst, src string) error {\n\n\tcmd := exec.Command(d.Player5Driver.VmrunPath,\n\t\t\"-T\", \"ws\",\n\t\t\"clone\", src, dst,\n\t\t\"full\")\n\n\tif _, _, err := runAndLog(cmd); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (d *Player6Driver) Verify() error ", "output": "{\n\tif err := d.Player5Driver.Verify(); err != nil {\n\t\treturn err\n\t}\n\n\treturn playerVerifyVersion(VMWARE_PLAYER_VERSION)\n}"} {"input": "package keymanagement\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ImportKeyVersionRequest struct {\n\n\tKeyId *string `mandatory:\"true\" contributesTo:\"path\" name:\"keyId\"`\n\n\tImportKeyVersionDetails `contributesTo:\"body\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ImportKeyVersionRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ImportKeyVersionRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request ImportKeyVersionRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype ImportKeyVersionResponse struct {\n\n\tRawResponse *http.Response\n\n\tKeyVersion `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response ImportKeyVersionResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ImportKeyVersionResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ImportKeyVersionRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package packets\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\n\ntype UnsubackPacket struct {\n\tFixedHeader\n\tMessageID uint16\n}\n\nfunc (ua *UnsubackPacket) Type() byte {\n\treturn ua.FixedHeader.MessageType\n}\nfunc (ua *UnsubackPacket) String() string {\n\tstr := fmt.Sprintf(\"%s\\n\", ua.FixedHeader)\n\tstr += fmt.Sprintf(\"MessageID: %d\", ua.MessageID)\n\treturn str\n}\n\n\n\n\n\nfunc (ua *UnsubackPacket) Unpack(b io.Reader) error {\n\tua.MessageID = decodeUint16(b)\n\n\treturn nil\n}\n\n\n\nfunc (ua *UnsubackPacket) Details() Details {\n\treturn Details{Qos: 0, MessageID: ua.MessageID}\n}\n\nfunc (ua *UnsubackPacket) Write(w io.Writer) error ", "output": "{\n\tvar err error\n\tua.FixedHeader.RemainingLength = 2\n\tpacket := ua.FixedHeader.pack()\n\tpacket.Write(encodeUint16(ua.MessageID))\n\t_, err = packet.WriteTo(w)\n\n\treturn err\n}"} {"input": "package main\n\nimport (\n\t\"go/ast\"\n)\n\nfunc init() {\n\tregister(fiximportFix)\n}\n\nvar fiximportFix = fix{\n\t\"fiximport\",\n\t\"2013-07-21\", \n\tfiximport,\n\t`\n Fix import statements to match the new canonical import path.\n`,\n}\n\n\n\nfunc fiximport(f *ast.File) bool ", "output": "{\n\tspec := importSpec(f, \"example.com/mypkg\")\n\tif spec == nil {\n\t\treturn false\n\t}\n\tspec.Path.Value = \"\\\"example.com/mypkg2\\\"\"\n\treturn true\n}"} {"input": "package app\n\nimport (\n\t\"net/url\"\n)\n\ntype Service interface {\n\tProxyPath() string\n\tURL() string\n\tBasicAuth() (username, password string, ok bool)\n\tAddSecret(parameters url.Values)\n}\n\ntype basicAuthService struct {\n\tproxyPath, url, clientId, clientSecret string\n}\n\nfunc (s basicAuthService) ProxyPath() string {\n\treturn s.proxyPath\n}\n\nfunc (s basicAuthService) URL() string {\n\treturn s.url\n}\n\nfunc (s basicAuthService) BasicAuth() (string, string, bool) {\n\treturn s.clientId, s.clientSecret, true\n}\n\nfunc (s basicAuthService) AddSecret(parameters url.Values) {\n}\n\ntype addParameterService struct {\n\tproxyPath, url, parameterName, clientSecret string\n}\n\n\n\nfunc (s addParameterService) URL() string {\n\treturn s.url\n}\n\nfunc (s addParameterService) BasicAuth() (string, string, bool) {\n\treturn \"\", \"\", false\n}\n\nfunc (s addParameterService) AddSecret(parameters url.Values) {\n\tparameters.Add(s.parameterName, s.clientSecret)\n}\n\nfunc BasicAuthService(proxyPath, url, clientId, clientSecret string) Service {\n\treturn basicAuthService{proxyPath, url, clientId, clientSecret}\n}\n\nfunc AddParameterService(proxyPath, url, parameterName, clientSecret string) Service {\n\treturn addParameterService{proxyPath, url, parameterName, clientSecret}\n}\n\nfunc (s addParameterService) ProxyPath() string ", "output": "{\n\treturn s.proxyPath\n}"} {"input": "package ansiwriter\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\ntype Modifier func() string\n\nfunc escapeANSI(code int) string {\n\treturn fmt.Sprintf(\"\\033[%dm\", code)\n}\n\nfunc Bold() string { return escapeANSI(1) }\n\nfunc Red() string { return escapeANSI(31) }\nfunc Green() string { return escapeANSI(32) }\nfunc Yellow() string { return escapeANSI(33) }\nfunc Blue() string { return escapeANSI(34) }\nfunc Magenta() string { return escapeANSI(35) }\nfunc Cyan() string { return escapeANSI(36) }\nfunc White() string { return escapeANSI(37) }\n\ntype awr struct {\n\tio.Writer\n\tmodifiers []Modifier\n}\n\n\n\n\nfunc New(w io.Writer, mods ...Modifier) io.Writer {\n\treturn awr{w, mods}\n}\n\nfunc (a awr) Write(b []byte) (n int, err error) {\n\tfor _, mod := range a.modifiers {\n\t\ta.Writer.Write([]byte(mod()))\n\t}\n\tn, err = a.Writer.Write(b)\n\t_, _ = a.Writer.Write([]byte(\"\\033[0m\"))\n\treturn\n}\n\nfunc Black() string ", "output": "{ return escapeANSI(30) }"} {"input": "package challenge15\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n)\n\n\n\nfunc RemoveValidPad(input []byte, blockSize int) ([]byte, error) ", "output": "{\n\tfor i := 1; i <= blockSize; i++ {\n\t\tpad := bytes.Repeat([]byte{byte(i)}, i)\n\t\tif bytes.HasSuffix(input, pad) {\n\t\t\treturn input[:len(input)-i], nil\n\t\t}\n\t}\n\treturn nil, errors.New(\"Invalid pad\")\n}"} {"input": "package flog\n\nimport \"github.com/Sirupsen/logrus\"\n\ntype Parameter interface {\n\tConvert() map[string]interface{}\n}\n\ntype Fields struct {\n\tEvent string\n\tError error\n}\n\nfunc (f Fields) Convert() map[string]interface{} {\n\tfields := map[string]interface{}{}\n\n\tif f.Event != \"\" {\n\t\tfields[\"event\"] = f.Event\n\t}\n\n\tif f.Error != nil {\n\t\tfields[\"error\"] = f.Error\n\t}\n\n\treturn fields\n}\n\ntype Details map[string]interface{}\n\nfunc (d Details) Convert() map[string]interface{} {\n\treturn d\n}\n\ntype DebugFields map[string]interface{}\n\nfunc (d DebugFields) Convert() map[string]interface{} {\n\treturn map[string]interface{}{}\n}\n\nfunc transform(params []Parameter) logrus.Fields {\n\tlogrusFields := logrus.Fields{}\n\n\tfor _, p := range params {\n\t\tfieldMap := p.Convert()\n\n\t\tfor k, v := range fieldMap {\n\t\t\tlogrusFields[k] = v\n\t\t}\n\t}\n\n\treturn logrusFields\n}\n\nfunc Debug(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Debug(msg)\n}\n\n\n\nfunc Warn(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Warning(msg)\n}\n\nfunc Error(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Error(msg)\n}\n\nfunc Fatal(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Fatal(msg)\n}\n\nfunc Panic(msg string, params ...Parameter) {\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Panic(msg)\n}\n\nfunc Info(msg string, params ...Parameter) ", "output": "{\n\tf := transform(params)\n\n\tlogrus.WithFields(f).Info(msg)\n}"} {"input": "package main\n\nimport (\n\t\"code.google.com/p/go.crypto/ssh/terminal\"\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc clearscr() {\n\tfmt.Printf(\"%c[2J%c[0;0H\", 27, 27)\n}\n\ntype uterm struct {\n\ts *terminal.State\n\tt *terminal.Terminal\n}\n\nfunc newTerm() Term {\n\tu := new(uterm)\n\tvar err error\n\tu.s, err = terminal.MakeRaw(0)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tu.t = terminal.NewTerminal(os.Stdin, \"lixian >> \")\n\treturn u\n}\n\nfunc (u *uterm) Restore() {\n\tterminal.Restore(0, u.s)\n}\n\n\n\nfunc (u *uterm) ReadLine() (string, error) ", "output": "{\n\treturn u.t.ReadLine()\n}"} {"input": "package helpers\n\nimport (\n\t\"errors\"\n\t\"os\"\n\n\tconfiguration \"github.com/GolosTools/golos-vote-bot/config\"\n)\n\n\n\nfunc GetConfig() (config configuration.Config, err error) ", "output": "{\n\terr = configuration.LoadConfiguration(\"./config.json\", &config)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\terr = configuration.LoadConfiguration(\"./config.local.json\", &config)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn config, err\n\t}\n\tif config.TelegramToken == \"write-your-telegram-token-here\" {\n\t\treturn config, errors.New(\"токен для телеграма не введён\")\n\t}\n\treturn config, err\n}"} {"input": "package vbox\n\nimport (\n\t\"bufio\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path\"\n)\n\n\nfunc loadIds(root string) ([]string, error) {\n\tdirs, err := ioutil.ReadDir(root)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout := []string{}\n\tfor _, d := range dirs {\n\t\tif !d.IsDir() {\n\t\t\tout = append(out, d.Name())\n\t\t}\n\t}\n\treturn out, nil\n}\n\n\n\n\n\n\n\n\nfunc getParentIds(root, id string) ([]string, error) ", "output": "{\n\tf, err := os.Open(path.Join(root, \"layers\", id))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\tout := []string{}\n\ts := bufio.NewScanner(f)\n\n\tfor s.Scan() {\n\t\tif t := s.Text(); t != \"\" {\n\t\t\tout = append(out, s.Text())\n\t\t}\n\t}\n\treturn out, s.Err()\n}"} {"input": "package filesystem\n\nimport (\n\tkeystore2 \"github.com/cossacklabs/acra/keystore\"\n)\n\nfunc getSymmetricKeyName(id string) string {\n\treturn id + `_sym`\n}\n\nfunc getTokenSymmetricKeyName(id []byte, ownerType keystore2.KeyOwnerType) string {\n\tvar name string\n\tswitch ownerType {\n\tcase keystore2.KeyOwnerTypeClient:\n\t\tname = getClientIDSymmetricKeyName(id)\n\tcase keystore2.KeyOwnerTypeZone:\n\t\tname = getZoneIDSymmetricKeyName(id)\n\tdefault:\n\t\tname = string(id)\n\t}\n\treturn name + \".token\"\n}\n\nfunc getClientIDSymmetricKeyName(id []byte) string {\n\treturn getSymmetricKeyName(GetServerDecryptionKeyFilename(id))\n}\n\n\n\nfunc getZoneIDSymmetricKeyName(id []byte) string ", "output": "{\n\treturn getSymmetricKeyName(GetZoneKeyFilename(id))\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n)\n\n\n\ntype CreateInstanceConsoleConnectionDetails struct {\n\n\tInstanceId *string `mandatory:\"true\" json:\"instanceId\"`\n\n\tPublicKey *string `mandatory:\"true\" json:\"publicKey\"`\n}\n\n\n\nfunc (m CreateInstanceConsoleConnectionDetails) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package api\n\n\ntype UserInfo interface {\n\tGetName() string\n\tGetUID() string\n\tGetScope() string\n\tGetExtra() map[string]string\n}\n\n\n\ntype UserIdentityInfo interface {\n\tGetUserName() string\n\tGetProviderName() string\n\tGetExtra() map[string]string\n}\n\n\ntype UserIdentityMapper interface {\n\tUserFor(identityInfo UserIdentityInfo) (UserInfo, error)\n}\n\ntype Client interface {\n\tGetId() string\n\tGetSecret() string\n\tGetRedirectUri() string\n\tGetUserData() interface{}\n}\n\ntype Grant struct {\n\tClient Client\n\tScope string\n\tExpiration int64\n\tRedirectURI string\n}\n\ntype DefaultUserInfo struct {\n\tName string\n\tUID string\n\tScope string\n\tExtra map[string]string\n}\n\n\n\nfunc (i *DefaultUserInfo) GetUID() string {\n\treturn i.UID\n}\n\nfunc (i *DefaultUserInfo) GetScope() string {\n\treturn i.Scope\n}\n\nfunc (i *DefaultUserInfo) GetExtra() map[string]string {\n\treturn i.Extra\n}\n\ntype DefaultUserIdentityInfo struct {\n\tUserName string\n\tProviderName string\n\tExtra map[string]string\n}\n\n\nfunc NewDefaultUserIdentityInfo(username string) DefaultUserIdentityInfo {\n\treturn DefaultUserIdentityInfo{\n\t\tUserName: username,\n\t\tExtra: make(map[string]string),\n\t}\n}\n\nfunc (i *DefaultUserIdentityInfo) GetUserName() string {\n\treturn i.UserName\n}\n\nfunc (i *DefaultUserIdentityInfo) GetProviderName() string {\n\treturn i.ProviderName\n}\n\nfunc (i *DefaultUserIdentityInfo) GetExtra() map[string]string {\n\treturn i.Extra\n}\n\nfunc (i *DefaultUserInfo) GetName() string ", "output": "{\n\treturn i.Name\n}"} {"input": "package daemon\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\nconst GetMapNameOKCode int = 200\n\n\ntype GetMapNameOK struct {\n\n\tPayload *models.BPFMap `json:\"body,omitempty\"`\n}\n\n\n\n\n\nfunc (o *GetMapNameOK) WithPayload(payload *models.BPFMap) *GetMapNameOK {\n\to.Payload = payload\n\treturn o\n}\n\n\nfunc (o *GetMapNameOK) SetPayload(payload *models.BPFMap) {\n\to.Payload = payload\n}\n\n\nfunc (o *GetMapNameOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n\tif o.Payload != nil {\n\t\tpayload := o.Payload\n\t\tif err := producer.Produce(rw, payload); err != nil {\n\t\t\tpanic(err) \n\t\t}\n\t}\n}\n\n\nconst GetMapNameNotFoundCode int = 404\n\n\ntype GetMapNameNotFound struct {\n}\n\n\nfunc NewGetMapNameNotFound() *GetMapNameNotFound {\n\n\treturn &GetMapNameNotFound{}\n}\n\n\nfunc (o *GetMapNameNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(404)\n}\n\nfunc NewGetMapNameOK() *GetMapNameOK ", "output": "{\n\n\treturn &GetMapNameOK{}\n}"} {"input": "package schedulercache\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/labels\"\n\t\"k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache\"\n)\n\n\ntype FakeCache struct {\n\tAssumeFunc func(*api.Pod)\n}\n\nfunc (f *FakeCache) AssumePod(pod *api.Pod) error {\n\tf.AssumeFunc(pod)\n\treturn nil\n}\n\n\n\nfunc (f *FakeCache) UpdatePod(oldPod, newPod *api.Pod) error { return nil }\n\nfunc (f *FakeCache) RemovePod(pod *api.Pod) error { return nil }\n\nfunc (f *FakeCache) AddNode(node *api.Node) error { return nil }\n\nfunc (f *FakeCache) UpdateNode(oldNode, newNode *api.Node) error { return nil }\n\nfunc (f *FakeCache) RemoveNode(node *api.Node) error { return nil }\n\nfunc (f *FakeCache) UpdateNodeNameToInfoMap(infoMap map[string]*schedulercache.NodeInfo) error {\n\treturn nil\n}\n\nfunc (f *FakeCache) List(s labels.Selector) ([]*api.Pod, error) { return nil, nil }\n\nfunc (f *FakeCache) AddPod(pod *api.Pod) error ", "output": "{ return nil }"} {"input": "package server\n\nimport (\n\t\"fmt\"\n\t\"github.com/kshvakov/jsonrpc2\"\n\t\"reflect\"\n)\n\n\n\ntype server struct {\n\thandlers map[string]handler\n}\n\nfunc (s *server) RegisterFunc(method string, fn interface{}) {\n\n\ts.addHandler(method, reflect.ValueOf(fn))\n}\n\nfunc (s *server) RegisterObject(name string, obj interface{}) {\n\n\tfor i := 0; i < reflect.TypeOf(obj).NumMethod(); i++ {\n\n\t\tmethod := reflect.TypeOf(obj).Method(i)\n\n\t\tif method.PkgPath != \"\" {\n\n\t\t\tcontinue\n\t\t}\n\n\t\ts.addHandler(fmt.Sprintf(\"%s.%s\", name, method.Name), reflect.ValueOf(obj).Method(i))\n\t}\n}\n\nfunc (s *server) addHandler(method string, fn reflect.Value) {\n\n\tif _, found := s.handlers[method]; !found {\n\n\t\tft := fn.Type()\n\n\t\tif ft.Kind() == reflect.Ptr {\n\n\t\t\tft = ft.Elem()\n\t\t}\n\n\t\tif ft.NumIn() != 1 || ft.NumOut() != 2 || !ft.In(0).Implements(reflect.TypeOf((*jsonrpc2.Params)(nil)).Elem()) {\n\n\t\t\treturn\n\t\t}\n\n\t\tif !ft.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) {\n\n\t\t\treturn\n\t\t}\n\n\t\tparams := ft.In(0)\n\n\t\tif params.Kind() == reflect.Ptr {\n\n\t\t\tparams = params.Elem()\n\t\t}\n\n\t\ts.handlers[method] = handler{\n\t\t\tmethod: fn,\n\t\t\tparams: reflect.New(params).Interface().(jsonrpc2.Params),\n\t\t}\n\n\t} else {\n\n\t\tpanic(fmt.Sprintf(\"Method '%s' is exists\", method))\n\t}\n}\n\nfunc New() *server ", "output": "{\n\n\treturn &server{\n\t\thandlers: make(map[string]handler),\n\t}\n}"} {"input": "package file\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\t\"github.com/coredns/coredns/plugin/pkg/rcode\"\n\t\"github.com/coredns/coredns/request\"\n\n\t\"github.com/miekg/dns\"\n)\n\n\n\n\nfunc (z *Zone) isNotify(state request.Request) bool {\n\tif state.Req.Opcode != dns.OpcodeNotify {\n\t\treturn false\n\t}\n\tif len(z.TransferFrom) == 0 {\n\t\treturn false\n\t}\n\tremote := state.IP()\n\tfor _, f := range z.TransferFrom {\n\t\tfrom, _, err := net.SplitHostPort(f)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif from == remote {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (z *Zone) Notify() {\n\tgo notify(z.origin, z.TransferTo)\n}\n\n\n\n\n\n\nfunc notifyAddr(c *dns.Client, m *dns.Msg, s string) error {\n\tvar err error\n\n\tcode := dns.RcodeServerFailure\n\tfor i := 0; i < 3; i++ {\n\t\tret, _, err := c.Exchange(m, s)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tcode = ret.Rcode\n\t\tif code == dns.RcodeSuccess {\n\t\t\treturn nil\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"notify for zone %q was not accepted by %q: %q\", m.Question[0].Name, s, err)\n\t}\n\treturn fmt.Errorf(\"notify for zone %q was not accepted by %q: rcode was %q\", m.Question[0].Name, s, rcode.ToString(code))\n}\n\nfunc notify(zone string, to []string) error ", "output": "{\n\tm := new(dns.Msg)\n\tm.SetNotify(zone)\n\tc := new(dns.Client)\n\n\tfor _, t := range to {\n\t\tif t == \"*\" {\n\t\t\tcontinue\n\t\t}\n\t\tif err := notifyAddr(c, m, t); err != nil {\n\t\t\tlog.Error(err.Error())\n\t\t} else {\n\t\t\tlog.Infof(\"Sent notify for zone %q to %q\", zone, t)\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package utils\n\nimport (\n\t\"bufio\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\n\n\n\nfunc Atoui(s string) uint32 {\n\ti, e := strconv.ParseUint(s, 10, 32)\n\tif e != nil {\n\t\treturn 0\n\t}\n\treturn uint32(i)\n}\n\n\nfunc ReadConfig(path string) map[string]string {\n\n\tconfigMap := make(map[string]string)\n\n\tf, err := os.Open(path)\n\tdefer f.Close()\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tscanner := bufio.NewScanner(f)\n\n\tfor scanner.Scan() {\n\n\t\tline := scanner.Text()\n\n\t\tif !strings.HasPrefix(line, \"//\") {\n\t\t\tfields := strings.SplitN(scanner.Text(), \"=\", 2)\n\n\t\t\tconfigMap[strings.TrimSpace(fields[0])] = strings.TrimSpace(fields[1])\n\t\t}\n\n\t}\n\n\treturn configMap\n}\n\n\nfunc GotError(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc Atoi(s string) int ", "output": "{\n\ti, e := strconv.Atoi(s)\n\tif e != nil {\n\t\treturn 0\n\t}\n\treturn i\n}"} {"input": "package winapi\n\nimport (\n\t\"unsafe\"\n)\n\n\nfunc CreateMDIWindow(lpClassName string, lpWindowName string, dwStyle uintptr, X int32, Y int32, nWidth uintptr, nHeight uintptr, hWndParent uintptr, hInstance uintptr, lParam uintptr) (uintptr, error) {\n\t_lpClassName, err := stringToUintptr(lpClassName)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\t_lpWindowName, err := stringToUintptr(lpWindowName)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tr1, _, err := procCreateMDIWindow.Call(_lpClassName, _lpWindowName, dwStyle, int32ToUintptr(X), int32ToUintptr(Y), nWidth, nHeight, hWndParent, hInstance, lParam)\n\treturn r1, err\n}\n\n\nfunc DefFrameProc(hWnd uintptr, hWndMDIClient uintptr, uMsg uintptr, wParam uintptr, lParam uintptr) (uintptr, error) {\n\tr1, _, err := procDefFrameProc.Call(hWnd, hWndMDIClient, uMsg, wParam, lParam)\n\treturn r1, err\n}\n\n\nfunc DefMDIChildProc(hWnd uintptr, uMsg uintptr, wParam uintptr, lParam uintptr) (uintptr, error) {\n\tr1, _, err := procDefMDIChildProc.Call(hWnd, uMsg, wParam, lParam)\n\treturn r1, err\n}\n\n\n\n\nfunc TranslateMDISysAccel(hWndClient uintptr, lpMsg *MSG) (uintptr, error) ", "output": "{\n\tr1, _, err := procTranslateMDISysAccel.Call(hWndClient, uintptr(unsafe.Pointer(lpMsg)))\n\treturn r1, err\n}"} {"input": "package header\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\n\t\"github.com/google/martian\"\n\t\"github.com/google/martian/parse\"\n)\n\nfunc init() {\n\tparse.Register(\"header.Modifier\", modifierFromJSON)\n}\n\ntype modifier struct {\n\tname, value string\n}\n\ntype modifierJSON struct {\n\tName string `json:\"name\"`\n\tValue string `json:\"value\"`\n\tScope []parse.ModifierType `json:\"scope\"`\n}\n\n\nfunc (m *modifier) ModifyRequest(req *http.Request) error {\n\tif m.name == \"Host\" {\n\t\treq.Host = m.value\n\t} else {\n\t\treq.Header.Set(m.name, m.value)\n\t}\n\n\treturn nil\n}\n\n\n\n\n\n\n\nfunc NewModifier(name, value string) martian.RequestResponseModifier {\n\treturn &modifier{\n\t\tname: http.CanonicalHeaderKey(name),\n\t\tvalue: value,\n\t}\n}\n\n\n\n\n\n\n\n\n\n\nfunc modifierFromJSON(b []byte) (*parse.Result, error) {\n\tmsg := &modifierJSON{}\n\tif err := json.Unmarshal(b, msg); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmodifier := NewModifier(msg.Name, msg.Value)\n\n\treturn parse.NewResult(modifier, msg.Scope)\n}\n\nfunc (m *modifier) ModifyResponse(res *http.Response) error ", "output": "{\n\tres.Header.Set(m.name, m.value)\n\n\treturn nil\n}"} {"input": "package pydio\n\nimport (\n\t\"bytes\"\n\t\"encoding/xml\"\n\t\"fmt\"\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\nvar (\n\tfakeXML []byte\n\tfakeXML2 []byte\n)\n\nfunc init() {\n\tsecret = \"TestingSecret\"\n\n\tfakeXML = []byte(`\n\t\n\t\n\t\t\n\t\t\t\n\t\t\t\n\t\t\t\t\n\t\t\t\n\t\t\n\t\n\t`)\n}\n\ntype Query struct {\n\tUser User `xml:\"user\"`\n}\n\n\n\nfunc TestUser(t *testing.T) ", "output": "{\n\tConvey(\"Unmarshaling user\", t, func() {\n\t\tvar q Query\n\n\t\terr := xml.Unmarshal(fakeXML, &q)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"error: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\tSo(q.User, ShouldResemble, *fakeUser)\n\t\tSo(q.User.Repos[0].IsReadable(), ShouldEqual, true)\n\t})\n\n\tConvey(\"Unmarshaling user 2\", t, func() {\n\t\tvar q Query\n\n\t\tdec := xml.NewDecoder(bytes.NewReader(fakeXML))\n\t\tdec.Strict = false\n\n\t\terr := dec.Decode(&q)\n\t\tSo(err, ShouldBeNil)\n\n\t\tSo(q.User, ShouldResemble, *fakeUser)\n\t})\n}"} {"input": "package apiv1\n\nimport (\n\t\"encoding/json\"\n)\n\ntype DiskHint struct {\n\tval interface{}\n}\n\nvar _ json.Unmarshaler = &DiskHint{}\nvar _ json.Marshaler = DiskHint{}\n\n\n\nfunc NewDiskHintFromMap(val map[string]interface{}) DiskHint {\n\treturn DiskHint{val}\n}\n\nfunc (i *DiskHint) UnmarshalJSON(data []byte) error {\n\tvar val interface{}\n\n\terr := json.Unmarshal(data, &val)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*i = DiskHint{val}\n\n\treturn nil\n}\n\nfunc (i DiskHint) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(i.val)\n}\n\nfunc NewDiskHintFromString(val string) DiskHint ", "output": "{\n\treturn DiskHint{val}\n}"} {"input": "package gwf\n\nimport (\n\t\"net/http\"\n\t\"strings\"\n)\n\n\ntype Context struct {\n\tw http.ResponseWriter\n\tr *http.Request\n\n\tpath []string\n}\n\ntype Module interface {\n\tAction(*Context)\n}\n\ntype Dispatcher struct {\n\tmodules map[string]Module\n}\n\nfunc (c *Context) Request() *http.Request {\n\treturn c.r\n}\n\nfunc (c *Context) Writer() http.ResponseWriter {\n\treturn c.w\n}\n\nfunc (c *Context) Init(w http.ResponseWriter, r *http.Request) {\n\tc.w, c.r = w, r\n\n\tpath := strings.Split(r.URL.Path, \"/\")\n\tc.path = path[1:]\n}\n\nfunc (c *Context) Path(index int) (string, bool) {\n\tif index < 0 || index >= len(c.path) {\n\t\treturn \"\", false\n\t} else {\n\t\treturn c.path[index], true\n\t}\n}\n\n\n\n\nfunc (d *Dispatcher) AddModule(name string, m Module) {\n\tif nil == d.modules {\n\t\td.modules = make(map[string]Module)\n\t}\n\td.modules[name] = m\n}\n\nfunc (d *Dispatcher) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\n\tvar c Context\n\tc.Init(w, r)\n\n\tif name, ok := c.Path(0); ok {\n\t\tif module, ok := d.modules[name]; ok && module != nil {\n\t\t\t(module).Action(&c)\n\t\t\treturn\n\t\t}\n\t}\n\tw.WriteHeader(http.StatusNotFound)\n}\n\nfunc (c *Context) Depth() int ", "output": "{\n\treturn len(c.path)\n}"} {"input": "package backoff\n\nimport (\n\t\"math\"\n\t\"time\"\n\n\t\"github.com/quan-xie/tuba/util/xtime\"\n)\n\n\ntype Backoff interface {\n\tNext(retry int) time.Duration\n}\n\ntype constantBackoff struct {\n\tbackoffInterval xtime.Duration\n}\n\n\nfunc NewConstantBackoff(backoffInterval xtime.Duration) Backoff {\n\treturn &constantBackoff{backoffInterval: backoffInterval}\n}\n\n\nfunc (cb *constantBackoff) Next(retry int) time.Duration {\n\tif retry <= 0 {\n\t\treturn 0 * time.Millisecond\n\t}\n\n\treturn time.Duration(cb.backoffInterval) * 1 << uint(retry)\n}\n\ntype exponentialBackoff struct {\n\texponentFactor float64\n\tinitialTimeout float64\n\tmaxTimeout float64\n}\n\n\n\n\n\nfunc (eb *exponentialBackoff) Next(retry int) time.Duration {\n\tif retry <= 0 {\n\t\treturn 0 * time.Millisecond\n\t}\n\n\treturn time.Duration(math.Min(eb.initialTimeout+math.Pow(eb.exponentFactor, float64(retry)), eb.maxTimeout)) * time.Millisecond\n}\n\nfunc NewExponentialBackoff(initialTimeout, maxTimeout time.Duration, exponentFactor float64) Backoff ", "output": "{\n\treturn &exponentialBackoff{\n\t\texponentFactor: exponentFactor,\n\t\tinitialTimeout: float64(initialTimeout / time.Millisecond),\n\t\tmaxTimeout: float64(maxTimeout / time.Millisecond),\n\t}\n}"} {"input": "package tests\n\nimport (\n\t\"database/sql\"\n\t_ \"github.com/lib/pq\"\n\t\"log\"\n\t\"strings\"\n)\n\nfunc Connect() (*sql.DB, error) {\n\tvar conn *sql.DB\n\tlog.SetFlags(log.Ltime | log.Lmicroseconds)\n\n\tvar err error\n\tvar hostportarr = strings.Split(HostPort, \":\")\n\tvar dbHost = hostportarr[0]\n\tvar dbPort = hostportarr[1]\n\n\tlog.Println(\"connecting to host:\" + dbHost + \" port:\" + dbPort + \" user:\" + userid + \" password:\" + password + \" database:\" + database)\n\tconn, err = GetDBConnection(dbHost, userid, dbPort, database, password)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn conn, err\n}\n\n\n\nfunc GetDBConnection(dbHost string, userid string, dbPort string, database string, password string) (*sql.DB, error) ", "output": "{\n\n\tvar dbConn *sql.DB\n\tvar err error\n\n\tif password == \"\" {\n\t\tdbConn, err = sql.Open(\"postgres\", \"sslmode=disable user=\"+userid+\" host=\"+dbHost+\" port=\"+dbPort+\" dbname=\"+database)\n\t} else {\n\t\tdbConn, err = sql.Open(\"postgres\", \"sslmode=disable user=\"+userid+\" host=\"+dbHost+\" port=\"+dbPort+\" dbname=\"+database+\" password=\"+password)\n\t}\n\tif err != nil {\n\t\tlog.Println(\"error in getting connection :\" + err.Error())\n\t}\n\treturn dbConn, err\n}"} {"input": "package daemon\n\nimport (\n\t\"github.com/docker/docker/container\"\n\t\"github.com/docker/docker/pkg/archive\"\n\t\"github.com/docker/docker/pkg/idtools\"\n)\n\n\n\nfunc (daemon *Daemon) tarCopyOptions(container *container.Container, noOverwriteDirNonDir bool) (*archive.TarOptions, error) ", "output": "{\n\tif container.Config.User == \"\" {\n\t\treturn daemon.defaultTarCopyOptions(noOverwriteDirNonDir), nil\n\t}\n\n\tuser, err := idtools.LookupUser(container.Config.User)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &archive.TarOptions{\n\t\tNoOverwriteDirNonDir: noOverwriteDirNonDir,\n\t\tChownOpts: &idtools.IDPair{UID: user.Uid, GID: user.Gid},\n\t}, nil\n}"} {"input": "package tree\n\nimport (\n\t\"container/list\"\n\t\"testing\"\n)\n\n\n\nfunc TestFindInTree(t *testing.T) ", "output": "{\n\tl := list.New()\n\tl.PushBack(\"github.com/Masterminds/glide\")\n\tl.PushBack(\"github.com/Masterminds/vcs\")\n\tl.PushBack(\"github.com/Masterminds/semver\")\n\n\tf := findInList(\"foo\", l)\n\tif f != false {\n\t\tt.Error(\"findInList found true instead of false\")\n\t}\n\n\tf = findInList(\"github.com/Masterminds/vcs\", l)\n\tif f != true {\n\t\tt.Error(\"findInList found false instead of true\")\n\t}\n}"} {"input": "package signature\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha256\"\n\t\"log\"\n\n\t\"github.com/cloudfoundry/dropsonde/metrics\"\n)\n\nconst SIGNATURE_LENGTH = 32\n\n\n\ntype Verifier struct {\n\tsharedSecret string\n}\n\n\n\nfunc NewVerifier(sharedSecret string) *Verifier {\n\treturn &Verifier{\n\t\tsharedSecret: sharedSecret,\n\t}\n}\n\n\n\n\n\n\n\n\nfunc (v *Verifier) Run(inputChan <-chan []byte, outputChan chan<- []byte) {\n\tfor signedMessage := range inputChan {\n\t\tif len(signedMessage) < SIGNATURE_LENGTH {\n\t\t\tlog.Print(\"signatureVerifier: missing signature\")\n\t\t\tcontinue\n\t\t}\n\n\t\tsignature, message := signedMessage[:SIGNATURE_LENGTH], signedMessage[SIGNATURE_LENGTH:]\n\t\tif v.verifyMessage(message, signature) {\n\t\t\toutputChan <- message\n\t\t\tmetrics.BatchIncrementCounter(\"signatureVerifier.validSignatures\")\n\t\t} else {\n\t\t\tlog.Print(\"signatureVerifier: invalid signature\")\n\t\t}\n\t}\n}\n\nfunc (v *Verifier) verifyMessage(message, signature []byte) bool {\n\texpectedMAC := generateSignature(message, []byte(v.sharedSecret))\n\treturn hmac.Equal(signature, expectedMAC)\n}\n\n\n\nfunc SignMessage(message, secret []byte) []byte {\n\tsignature := generateSignature(message, secret)\n\treturn append(signature, message...)\n}\n\n\n\nfunc generateSignature(message, secret []byte) []byte ", "output": "{\n\tmac := hmac.New(sha256.New, secret)\n\tmac.Write(message)\n\treturn mac.Sum(nil)\n}"} {"input": "package main\n\nimport . \"g2d\"\n\nvar screen = Point{480, 360}\nvar size = Point{20, 20}\n\ntype Ball struct {\n x, y int\n dx, dy int\n}\n\nfunc NewBall(pos Point) *Ball {\n return &Ball{pos.X, pos.Y, 5, 5}\n}\n\nfunc (b *Ball) Move() {\n if !(0 <= b.x+b.dx && b.x+b.dx <= screen.X-size.X) {\n b.dx = -b.dx\n }\n if !(0 <= b.y+b.dy && b.y+b.dy <= screen.Y-size.Y) {\n b.dy = -b.dy\n }\n b.x += b.dx\n b.y += b.dy\n}\n\n\n\n\nvar b1 = NewBall(Point{40, 80})\nvar b2 = NewBall(Point{80, 40})\n\nfunc mainConsole() {\n for i := 0; i < 25; i++ {\n Println(\"Ball 1 @\", b1.Position())\n Println(\"Ball 2 @\", b2.Position())\n b1.Move()\n b2.Move()\n }\n}\n\nfunc tick() {\n ClearCanvas() \n b1.Move()\n b2.Move()\n DrawImage(\"ball.png\", b1.Position()) \n DrawImage(\"ball.png\", b2.Position()) \n}\n\nfunc main() {\n \n InitCanvas(screen)\n MainLoop(tick)\n}\n\nfunc (b *Ball) Position() Point ", "output": "{\n return Point{b.x, b.y}\n}"} {"input": "package wml_test\n\nimport (\n\t\"encoding/xml\"\n\t\"testing\"\n\n\t\"baliance.com/gooxml/schema/soo/wml\"\n)\n\n\n\nfunc TestCT_DocPartTypesMarshalUnmarshal(t *testing.T) {\n\tv := wml.NewCT_DocPartTypes()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := wml.NewCT_DocPartTypes()\n\txml.Unmarshal(buf, v2)\n}\n\nfunc TestCT_DocPartTypesConstructor(t *testing.T) ", "output": "{\n\tv := wml.NewCT_DocPartTypes()\n\tif v == nil {\n\t\tt.Errorf(\"wml.NewCT_DocPartTypes must return a non-nil value\")\n\t}\n\tif err := v.Validate(); err != nil {\n\t\tt.Errorf(\"newly constructed wml.CT_DocPartTypes should validate: %s\", err)\n\t}\n}"} {"input": "package aianomalydetection\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype DataSourceDetailsInflux struct {\n\tVersionSpecificDetails InfluxDetails `mandatory:\"true\" json:\"versionSpecificDetails\"`\n\n\tUserName *string `mandatory:\"true\" json:\"userName\"`\n\n\tPasswordSecretId *string `mandatory:\"true\" json:\"passwordSecretId\"`\n\n\tMeasurementName *string `mandatory:\"true\" json:\"measurementName\"`\n\n\tUrl *string `mandatory:\"true\" json:\"url\"`\n}\n\nfunc (m DataSourceDetailsInflux) String() string {\n\treturn common.PointerString(m)\n}\n\n\n\n\n\nfunc (m *DataSourceDetailsInflux) UnmarshalJSON(data []byte) (e error) {\n\tmodel := struct {\n\t\tVersionSpecificDetails influxdetails `json:\"versionSpecificDetails\"`\n\t\tUserName *string `json:\"userName\"`\n\t\tPasswordSecretId *string `json:\"passwordSecretId\"`\n\t\tMeasurementName *string `json:\"measurementName\"`\n\t\tUrl *string `json:\"url\"`\n\t}{}\n\n\te = json.Unmarshal(data, &model)\n\tif e != nil {\n\t\treturn\n\t}\n\tvar nn interface{}\n\tnn, e = model.VersionSpecificDetails.UnmarshalPolymorphicJSON(model.VersionSpecificDetails.JsonData)\n\tif e != nil {\n\t\treturn\n\t}\n\tif nn != nil {\n\t\tm.VersionSpecificDetails = nn.(InfluxDetails)\n\t} else {\n\t\tm.VersionSpecificDetails = nil\n\t}\n\n\tm.UserName = model.UserName\n\n\tm.PasswordSecretId = model.PasswordSecretId\n\n\tm.MeasurementName = model.MeasurementName\n\n\tm.Url = model.Url\n\n\treturn\n}\n\nfunc (m DataSourceDetailsInflux) MarshalJSON() (buff []byte, e error) ", "output": "{\n\ttype MarshalTypeDataSourceDetailsInflux DataSourceDetailsInflux\n\ts := struct {\n\t\tDiscriminatorParam string `json:\"dataSourceType\"`\n\t\tMarshalTypeDataSourceDetailsInflux\n\t}{\n\t\t\"INFLUX\",\n\t\t(MarshalTypeDataSourceDetailsInflux)(m),\n\t}\n\n\treturn json.Marshal(&s)\n}"} {"input": "package messenger\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/scionproto/scion/go/lib/common\"\n\t\"github.com/scionproto/scion/go/lib/ctrl\"\n\t\"github.com/scionproto/scion/go/lib/infra/disp\"\n\t\"github.com/scionproto/scion/go/lib/log\"\n\t\"github.com/scionproto/scion/go/proto\"\n)\n\nvar _ disp.MessageAdapter = (*Adapter)(nil)\n\n\ntype Adapter struct{}\n\n\nvar DefaultAdapter = &Adapter{}\n\n\n\nfunc (a *Adapter) RawToMsg(b common.RawBytes) (proto.Cerealizable, error) {\n\treturn ctrl.NewSignedPldFromRaw(b)\n}\n\nfunc (a *Adapter) MsgKey(msg proto.Cerealizable) string {\n\tsignedCtrlPld, ok := msg.(*ctrl.SignedPld)\n\tif !ok {\n\t\tlog.Warn(\"Unable to type assert disp.Message to ctrl.SignedPld\", \"msg\", msg,\n\t\t\t\"type\", common.TypeOf(msg))\n\t\treturn \"\"\n\t}\n\n\tctrlPld, err := signedCtrlPld.Pld()\n\tif err != nil {\n\t\tlog.Warn(\"Unable to extract CtrlPld from SignedCtrlPld\", \"err\", err)\n\t\treturn \"\"\n\t}\n\treturn strconv.FormatUint(ctrlPld.ReqId, 10)\n}\n\nfunc (a *Adapter) MsgToRaw(msg proto.Cerealizable) (common.RawBytes, error) ", "output": "{\n\tpld, ok := msg.(*ctrl.SignedPld)\n\tif !ok {\n\t\treturn nil, common.NewBasicError(\n\t\t\t\"Unable to type assert proto.Cerealizable to ctrl.SignedPld\",\n\t\t\tnil, \"msg\", msg, \"type\", common.TypeOf(msg))\n\t}\n\treturn pld.PackPld()\n}"} {"input": "package file\n\nimport (\n\t\"io\"\n\t\"os\"\n)\n\n\n\n\nfunc CreateAndWrite(name string, r io.Reader) error ", "output": "{\n\tfd, err := os.Create(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fd.Close()\n\tif _, err := io.Copy(fd, r); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package graph\n\nimport \"fmt\"\n\ntype Graph struct {\n\tconnections []*Graph\n\tValue interface{}\n}\n\n\n\nfunc (g *Graph) Connect(h *Graph) {\n\tg.connections = append(g.connections, h)\n\th.connections = append(h.connections, g)\n}\n\nfunc (g *Graph) String() string {\n\treturn fmt.Sprintf(\"%v\", g.Value)\n}\n\nfunc New() *Graph ", "output": "{\n\treturn new(Graph)\n}"} {"input": "package proxy\n\nimport (\n\t\"store\"\n\t\"utils\"\n)\n\nconst (\n\tEFFICIENT_POOL_KEY = \"EfficientPoolKey\"\n)\n\nvar (\n\tefficientPool = InitEfficientPool()\n)\n\ntype EfficientPool struct {\n\tBasePool\n\tStorage store.SetStringStorer\n}\n\nfunc InitEfficientPool() *EfficientPool {\n\treturn &EfficientPool{BasePool: *InitBasePool(), Storage: store.RedisSet{}}\n}\n\nfunc (pool *EfficientPool) Add(proxy string) {\n\tpool.Storage.Add(EFFICIENT_POOL_KEY, proxy)\n}\n\n\n\nfunc Rand() (ok bool, proxy string) {\n\treturn efficientPool.Storage.Rand(EFFICIENT_POOL_KEY)\n}\n\nfunc Feedback(proxy string, ok bool, time int) {\n\tstablePool.Add(proxy, utils.EscapeToTime(ok, time))\n\n\tif !ok {\n\t\tefficientPool.Remove(proxy)\n\t}\n}\n\nfunc (pool *EfficientPool) Remove(proxy string) ", "output": "{\n\tpool.Storage.Remove(EFFICIENT_POOL_KEY, proxy)\n}"} {"input": "package sardata\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"io\"\n\t\"math\"\n\n\t\"github.com/luci/luci-go/common/errors\"\n\t\"github.com/luci/luci-go/common/iotools\"\n)\n\n\ntype BlockHeader struct {\n\tLength uint64\n\n\tCompression CompressionScheme\n}\n\nfunc (b BlockHeader) Write(w io.Writer) error {\n\tbuf := make([]byte, binary.MaxVarintLen64+1)\n\tbuf = buf[:binary.PutUvarint(buf, b.Length)]\n\tbuf = append(buf, byte(b.Compression))\n\t_, err := w.Write(buf)\n\treturn err\n}\n\nfunc (b *BlockHeader) Read(r io.Reader) (err error) {\n\tbr := byteReader{Reader: r}\n\n\tif b.Length, err = binary.ReadUvarint(br); err != nil {\n\t\treturn\n\t}\n\tc, err := br.ReadByte()\n\tif err != nil {\n\t\treturn\n\t}\n\tb.Compression = CompressionScheme(c)\n\treturn b.Compression.Valid()\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc BlockReader(r io.Reader) (io.ReadCloser, error) {\n\th := BlockHeader{}\n\tif err := h.Read(r); err != nil {\n\t\treturn nil, err\n\t}\n\tif h.Length > math.MaxInt64 {\n\t\treturn nil, errors.New(\"block length exceeds int64\")\n\t}\n\treturn h.Compression.Reader(io.LimitReader(r, int64(h.Length)))\n}\n\nfunc BlockWriter(w io.Writer, scheme CompressionScheme, level int) (io.WriteCloser, error) ", "output": "{\n\tbuf := bytes.Buffer{}\n\tcompressWriter, err := scheme.Writer(&buf, level)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcountWriter := &iotools.CountingWriter{Writer: compressWriter}\n\n\treturn writeCloseHook{\n\t\tcountWriter,\n\t\tfunc() error {\n\t\t\tif err := compressWriter.Close(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\th := BlockHeader{uint64(buf.Len()), scheme}\n\t\t\tif err := h.Write(w); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t_, err := w.Write(buf.Bytes())\n\t\t\treturn err\n\t\t},\n\t}, nil\n}"} {"input": "package commands\n\nimport (\n\t\"fmt\"\n\t\"github.com/kr/beanstalk\"\n\t\"github.com/spf13/cobra\"\n\t\"log\"\n)\n\nvar tubePeekDelayedCommand = &cobra.Command{\n\tUse: \"peek_delayed [tube_name]\",\n\tShort: \"Retrieve the first available job in the delayed queue\",\n\tLong: `This jobs train was running late.`,\n}\n\n\n\nfunc tube_peek_delayed(cmd *cobra.Command, args []string) {\n\tclient := connect()\n\tdefer client.Close()\n\n\tclient.Tube = beanstalk.Tube{client, tube_name}\n\n\tid, body, err := client.Tube.PeekBuried()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(\"Delayed: [%d] : %s\\n\", id, body)\n}\n\nfunc init() ", "output": "{\n\ttubePeekDelayedCommand.Run = tube_peek_delayed\n}"} {"input": "package ltree\n\n\n\n\n\nfunc isSymmetric(root *TreeNode) bool {\n\tif root == nil {\n\t\treturn true\n\t}\n\treturn isMirror(root.Left, root.Right)\n}\n\nfunc isMirror(left, right *TreeNode) bool ", "output": "{\n\treturn (left == nil && right == nil) ||\n\t\t(left != nil && right != nil &&\n\t\t\tleft.Val == right.Val &&\n\t\t\tisMirror(left.Left, right.Right) &&\n\t\t\tisMirror(right.Left, left.Right))\n}"} {"input": "package errorreporting \n\nimport (\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc/metadata\"\n)\n\n\n\n\nfunc DefaultAuthScopes() []string {\n\treturn []string{\n\t\t\"https:www.googleapis.com/auth/cloud-platform\",\n\t}\n}\n\nfunc insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context ", "output": "{\n\tout, _ := metadata.FromOutgoingContext(ctx)\n\tout = out.Copy()\n\tfor _, md := range mds {\n\t\tfor k, v := range md {\n\t\t\tout[k] = append(out[k], v...)\n\t\t}\n\t}\n\treturn metadata.NewOutgoingContext(ctx, out)\n}"} {"input": "package togglr\n\nimport (\n\t\"testing\"\n)\n\n\n\ntype FeaturesJSON struct {\n\tFeatureJson Feature\n\tFeatureJsonFalse Feature\n\tFeatureWithTag Feature `json:\"fwt\"`\n}\n\nfunc TestInitWithJson(t *testing.T) ", "output": "{\n\tInit(\"data/feature.json\")\n\n\tm := FeaturesJSON{}\n\tRead(&m)\n\n\tif !m.FeatureJson.IsEnabled() {\n\t\tt.Fatal(\"FeatureJson was not set\")\n\t}\n\n\tif !m.FeatureWithTag.IsEnabled() {\n\t\tt.Fatal(\"FeatureWithTag was not set\")\n\t}\n\n\tif m.FeatureJsonFalse.IsEnabled() {\n\t\tt.Fatal(\"FeatureJsonFalse was not set correctly\")\n\t}\n}"} {"input": "package com\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\nfunc TestIsFile(t *testing.T) {\n\tif !IsFile(\"file.go\") {\n\t\tt.Errorf(\"IsExist:\\n Expect => %v\\n Got => %v\\n\", true, false)\n\t}\n\n\tif IsFile(\"testdata\") {\n\t\tt.Errorf(\"IsExist:\\n Expect => %v\\n Got => %v\\n\", false, true)\n\t}\n\n\tif IsFile(\"files.go\") {\n\t\tt.Errorf(\"IsExist:\\n Expect => %v\\n Got => %v\\n\", false, true)\n\t}\n}\n\n\n\n\nfunc BenchmarkIsFile(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tIsFile(\"file.go\")\n\t}\n}\n\nfunc BenchmarkIsExist(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tIsExist(\"file.go\")\n\t}\n}\n\nfunc TestIsExist(t *testing.T) ", "output": "{\n\tConvey(\"Check if file or directory exists\", t, func() {\n\t\tConvey(\"Pass a file name that exists\", func() {\n\t\t\tSo(IsExist(\"file.go\"), ShouldEqual, true)\n\t\t})\n\t\tConvey(\"Pass a directory name that exists\", func() {\n\t\t\tSo(IsExist(\"testdata\"), ShouldEqual, true)\n\t\t})\n\t\tConvey(\"Pass a directory name that does not exist\", func() {\n\t\t\tSo(IsExist(\".hg\"), ShouldEqual, false)\n\t\t})\n\t})\n}"} {"input": "package tokens\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"path\"\n\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/client\"\n\t\"github.com/golang/glog\"\n\t\"github.com/spf13/cobra\"\n\n\t\"github.com/openshift/origin/pkg/auth/server/tokenrequest\"\n\tosclientcmd \"github.com/openshift/origin/pkg/cmd/util/clientcmd\"\n)\n\nconst (\n\tTokenRecommendedCommandName = \"tokens\"\n\tTOKEN_FILE_PARAM = \"token-file\"\n)\n\nfunc NewCmdTokens(name, fullName string, f *osclientcmd.Factory, out io.Writer) *cobra.Command {\n\tcmds := &cobra.Command{\n\t\tUse: name,\n\t\tShort: \"Manage authentication tokens\",\n\t\tLong: `Manage authentication tokens`,\n\t\tRun: func(c *cobra.Command, args []string) {\n\t\t\tc.SetOutput(os.Stdout)\n\t\t\tc.Help()\n\t\t},\n\t}\n\n\tcmds.AddCommand(NewCmdValidateToken(f))\n\tcmds.AddCommand(NewCmdRequestToken(f))\n\n\treturn cmds\n}\n\nfunc getFlagString(cmd *cobra.Command, flag string) string {\n\tf := cmd.Flags().Lookup(flag)\n\tif f == nil {\n\t\tglog.Fatalf(\"Flag accessed but not defined for command %s: %s\", cmd.Name(), flag)\n\t}\n\treturn f.Value.String()\n}\n\n\n\nfunc getRequestTokenURL(clientCfg *client.Config) string ", "output": "{\n\treturn clientCfg.Host + path.Join(\"/oauth\", tokenrequest.RequestTokenEndpoint)\n}"} {"input": "package gotick\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\n\ntype Project struct {\n\tID uint `json:\"id\"`\n\tName string `json:\"name\"`\n\tBudget float32 `json:\"budget\"`\n\tDateClosed string `json:\"date_closed\"`\n\tNotifications bool `json:\"notifications\"`\n\tBillable bool `json:\"billable\"`\n\tRecurring bool `json:\"recurring\"`\n\tClientID uint `json:\"client_id\"`\n\tOwnerID uint `json:\"owner_id\"`\n\tURL string `json:\"url\"`\n\tCreatedAt string `json:\"created_at\"`\n\tUpdatedAt string `json:\"updated_at\"`\n}\n\n\n\ntype Projects []Project\n\n\n\nfunc GetOpenProjectsOnPage(tickData JSONGetter, page int) (Projects, error) {\n\tvar projects Projects\n\turl := fmt.Sprintf(\"/projects.json?page=%d\", page)\n\tdata, err := tickData.GetJSON(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif bytes.Equal(data, []byte(\"[]\")) {\n\t\treturn nil, nil\n\t}\n\terr = json.Unmarshal(data, &projects)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn projects, nil\n}\n\nfunc GetProject(tickData JSONGetter, projectID int) (Project, error) {\n\tvar project Project\n\turl := fmt.Sprintf(\"/projects/%d.json\", projectID)\n\tdata, err := tickData.GetJSON(url)\n\tif err != nil {\n\t\treturn Project{}, err\n\t}\n\tif bytes.Equal(data, []byte(\"[]\")) {\n\t\treturn Project{}, nil\n\t}\n\terr = json.Unmarshal(data, &project)\n\tif err != nil {\n\t\treturn Project{}, err\n\t}\n\treturn project, nil\n}\n\nfunc GetOpenProjects(tickData JSONGetter) (Projects, error) ", "output": "{\n\tvar allProjects Projects\n\tfoundLastPage := false\n\tcurrentPage := 1\n\tfor !foundLastPage {\n\t\tprojects, err := GetOpenProjectsOnPage(tickData, currentPage)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif projects == Projects(nil) {\n\t\t\tfoundLastPage = true\n\t\t} else {\n\t\t\tallProjects = append(allProjects, projects...)\n\t\t\tcurrentPage++\n\t\t}\n\t}\n\treturn allProjects, nil\n}"} {"input": "package fs\n\nimport (\n\t\"github.com/opencontainers/runc/libcontainer/cgroups\"\n\t\"github.com/opencontainers/runc/libcontainer/cgroups/fscommon\"\n\t\"github.com/opencontainers/runc/libcontainer/configs\"\n)\n\ntype NetPrioGroup struct {\n}\n\nfunc (s *NetPrioGroup) Name() string {\n\treturn \"net_prio\"\n}\n\nfunc (s *NetPrioGroup) Apply(path string, d *cgroupData) error {\n\treturn join(path, d.pid)\n}\n\nfunc (s *NetPrioGroup) Set(path string, r *configs.Resources) error {\n\tfor _, prioMap := range r.NetPrioIfpriomap {\n\t\tif err := fscommon.WriteFile(path, \"net_prio.ifpriomap\", prioMap.CgroupString()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (s *NetPrioGroup) GetStats(path string, stats *cgroups.Stats) error ", "output": "{\n\treturn nil\n}"} {"input": "package rtda\n\nimport (\n\t\"github.com/zxh0/jvm.go/rtda/heap\"\n)\n\ntype FrameCache struct {\n\tthread *Thread\n\tcachedFrames []*Frame\n\tframeCount uint\n\tmaxFrame uint\n}\n\n\n\nfunc (cache *FrameCache) borrowFrame(method *heap.Method) *Frame {\n\tif cache.frameCount > 0 {\n\t\tfor i, frame := range cache.cachedFrames {\n\t\t\tif frame != nil &&\n\t\t\t\tframe.maxLocals >= method.MaxLocals &&\n\t\t\t\tframe.maxStack >= method.MaxStack {\n\n\t\t\t\tcache.frameCount--\n\t\t\t\tcache.cachedFrames[i] = nil\n\t\t\t\tframe.reset(method)\n\t\t\t\treturn frame\n\t\t\t}\n\t\t}\n\t}\n\treturn newFrame(cache.thread, method)\n}\n\nfunc (cache *FrameCache) returnFrame(frame *Frame) {\n\tif cache.frameCount < cache.maxFrame {\n\t\tfor i, cachedFrame := range cache.cachedFrames {\n\t\t\tif cachedFrame == nil {\n\t\t\t\tcache.cachedFrames[i] = frame\n\t\t\t\tcache.frameCount++\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor _, cachedFrame := range cache.cachedFrames {\n\t\t\tif frame.maxLocals > cachedFrame.maxLocals {\n\t\t\t\tcachedFrame.maxLocals = frame.maxLocals\n\t\t\t\tcachedFrame.LocalVars = frame.LocalVars\n\t\t\t\tframe.maxLocals = 0\n\t\t\t}\n\t\t\tif frame.maxStack > cachedFrame.maxStack {\n\t\t\t\tcachedFrame.maxStack = frame.maxStack\n\t\t\t\tcachedFrame.OperandStack = frame.OperandStack\n\t\t\t\tframe.maxStack = 0\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc newFrameCache(thread *Thread, maxFrame uint) *FrameCache ", "output": "{\n\treturn &FrameCache{\n\t\tthread: thread,\n\t\tmaxFrame: maxFrame,\n\t\tcachedFrames: make([]*Frame, maxFrame),\n\t}\n}"} {"input": "package serial\n\nimport (\n\t\"flag\"\n\n\t\"github.com/vmware/govmomi/govc/cli\"\n\t\"github.com/vmware/govmomi/govc/flags\"\n\t\"golang.org/x/net/context\"\n)\n\ntype connect struct {\n\t*flags.VirtualMachineFlag\n\n\tdevice string\n\tclient bool\n}\n\nfunc init() {\n\tcli.Register(\"device.serial.connect\", &connect{})\n}\n\n\n\nfunc (cmd *connect) Process() error { return nil }\n\nfunc (cmd *connect) Run(f *flag.FlagSet) error {\n\tvm, err := cmd.VirtualMachine()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif vm == nil {\n\t\treturn flag.ErrHelp\n\t}\n\n\tdevices, err := vm.Device(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td, err := devices.FindSerialPort(cmd.device)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn vm.EditDevice(context.TODO(), devices.ConnectSerialPort(d, f.Arg(0), cmd.client))\n}\n\nfunc (cmd *connect) Register(f *flag.FlagSet) ", "output": "{\n\tf.StringVar(&cmd.device, \"device\", \"\", \"serial port device name\")\n\tf.BoolVar(&cmd.client, \"client\", false, \"Use client direction\")\n}"} {"input": "package metrics\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\n\ntype GaugeMetric struct {\n\tvalue float64\n\tmutex sync.RWMutex\n}\n\nfunc (metric *GaugeMetric) Humanize() string {\n\tformatString := \"[GaugeMetric; value=%f]\"\n\n\tmetric.mutex.RLock()\n\tdefer metric.mutex.RUnlock()\n\n\treturn fmt.Sprintf(formatString, metric.value)\n}\n\nfunc (metric *GaugeMetric) Set(value float64) float64 {\n\tmetric.mutex.Lock()\n\tdefer metric.mutex.Unlock()\n\n\tmetric.value = value\n\n\treturn metric.value\n}\n\nfunc (metric *GaugeMetric) IncrementBy(value float64) float64 {\n\tmetric.mutex.Lock()\n\tdefer metric.mutex.Unlock()\n\n\tmetric.value += value\n\n\treturn metric.value\n}\n\n\n\nfunc (metric *GaugeMetric) DecrementBy(value float64) float64 {\n\tmetric.mutex.Lock()\n\tdefer metric.mutex.Unlock()\n\n\tmetric.value -= value\n\n\treturn metric.value\n}\n\nfunc (metric *GaugeMetric) Decrement() float64 {\n\treturn metric.DecrementBy(1)\n}\n\nfunc (metric *GaugeMetric) Get() float64 {\n\tmetric.mutex.RLock()\n\tdefer metric.mutex.RUnlock()\n\n\treturn metric.value\n}\n\nfunc (metric *GaugeMetric) Marshallable() map[string]interface{} {\n\tmetric.mutex.RLock()\n\tdefer metric.mutex.RUnlock()\n\n\tv := make(map[string]interface{}, 2)\n\n\tv[valueKey] = metric.value\n\tv[typeKey] = gaugeTypeValue\n\n\treturn v\n}\n\nfunc (metric *GaugeMetric) Increment() float64 ", "output": "{\n\treturn metric.IncrementBy(1)\n}"} {"input": "package mediaupload\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n\n\t\"github.com/rafael84/go-spa/backend/cfg\"\n\t\"github.com/rafael84/go-spa/backend/random\"\n\t\"github.com/rafael84/go-spa/backend/storage/location\"\n\t\"github.com/rafael84/go-spa/backend/storage/mediatype\"\n)\n\n\n\nfunc MoveFile(location *location.Model, mediatype *mediatype.Model, srcPath string) (string, error) ", "output": "{\n\n\tdir := fmt.Sprintf(\"%s/%s/%s\", cfg.Media.Root, location.StaticPath, mediatype.Name)\n\terr := os.MkdirAll(dir, 0755)\n\tif err != nil {\n\t\tlog.Errorf(\"Unable to create directory: %s\", err)\n\t\treturn \"\", errors.New(\"Could not process uploaded file\")\n\t}\n\n\tfilename, err := random.New(16)\n\tif err != nil {\n\t\tlog.Errorf(\"Unable to generate filename: %s\", err)\n\t\treturn \"\", errors.New(\"Could not process uploaded file\")\n\t}\n\tdstPath := fmt.Sprintf(\"%s/%s\", dir, filename)\n\n\terr = os.Rename(srcPath, dstPath)\n\tif err != nil {\n\t\tlog.Errorf(\"Could not move file %s\", err)\n\t\treturn \"\", errors.New(\"Could not process uploaded file\")\n\t}\n\n\treturn dstPath, nil\n}"} {"input": "package ray\n\nimport (\n\t\"github.com/v2ray/v2ray-core/common/alloc\"\n)\n\nconst (\n\tbufferSize = 16\n)\n\n\n\n\ntype directRay struct {\n\tInput chan *alloc.Buffer\n\tOutput chan *alloc.Buffer\n}\n\nfunc (this *directRay) OutboundInput() <-chan *alloc.Buffer {\n\treturn this.Input\n}\n\nfunc (this *directRay) OutboundOutput() chan<- *alloc.Buffer {\n\treturn this.Output\n}\n\nfunc (this *directRay) InboundInput() chan<- *alloc.Buffer {\n\treturn this.Input\n}\n\nfunc (this *directRay) InboundOutput() <-chan *alloc.Buffer {\n\treturn this.Output\n}\n\nfunc NewRay() Ray ", "output": "{\n\treturn &directRay{\n\t\tInput: make(chan *alloc.Buffer, bufferSize),\n\t\tOutput: make(chan *alloc.Buffer, bufferSize),\n\t}\n}"} {"input": "package image\n\nimport (\n\t\"github.com/containers/image/types\"\n)\n\n\n\n\ntype imageCloser struct {\n\ttypes.Image\n\tsrc types.ImageSource\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc FromSource(ctx *types.SystemContext, src types.ImageSource) (types.ImageCloser, error) {\n\timg, err := FromUnparsedImage(ctx, UnparsedInstance(src, nil))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &imageCloser{\n\t\tImage: img,\n\t\tsrc: src,\n\t}, nil\n}\n\nfunc (ic *imageCloser) Close() error {\n\treturn ic.src.Close()\n}\n\n\n\n\n\n\ntype sourcedImage struct {\n\t*UnparsedImage\n\tmanifestBlob []byte\n\tmanifestMIMEType string\n\tgenericManifest\n}\n\n\n\n\n\n\nfunc FromUnparsedImage(ctx *types.SystemContext, unparsed *UnparsedImage) (types.Image, error) {\n\n\tmanifestBlob, manifestMIMEType, err := unparsed.Manifest()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparsedManifest, err := manifestInstanceFromBlob(ctx, unparsed.src, manifestBlob, manifestMIMEType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &sourcedImage{\n\t\tUnparsedImage: unparsed,\n\t\tmanifestBlob: manifestBlob,\n\t\tmanifestMIMEType: manifestMIMEType,\n\t\tgenericManifest: parsedManifest,\n\t}, nil\n}\n\n\nfunc (i *sourcedImage) Size() (int64, error) {\n\treturn -1, nil\n}\n\n\nfunc (i *sourcedImage) Manifest() ([]byte, string, error) {\n\treturn i.manifestBlob, i.manifestMIMEType, nil\n}\n\nfunc (i *sourcedImage) Inspect() (*types.ImageInspectInfo, error) {\n\treturn inspectManifest(i.genericManifest)\n}\n\n\n\nfunc (i *sourcedImage) LayerInfosForCopy() []types.BlobInfo ", "output": "{\n\treturn i.UnparsedImage.LayerInfosForCopy()\n}"} {"input": "package modules\n\nimport (\n\t\"io\"\n\n\t\"github.com/kylelemons/go-gypsy/yaml\"\n)\n\ntype Node interface{}\ntype Scalar string\ntype Map map[string]Node\ntype List []Node\n\nfunc YamlNodeToNode(node yaml.Node) Node {\n\tscalar, ok := node.(yaml.Scalar)\n\tif ok {\n\t\treturn Scalar(scalar.String())\n\t}\n\tlist, ok := node.(yaml.List)\n\tif ok {\n\t\tresult := make(List, list.Len())\n\t\tfor i, n := range list {\n\t\t\tresult[i] = YamlNodeToNode(n)\n\t\t}\n\t\treturn result\n\t}\n\tmp, ok := node.(yaml.Map)\n\tif ok {\n\t\tresult := make(Map)\n\t\tfor k, v := range mp {\n\t\t\tresult[k] = YamlNodeToNode(v)\n\t\t}\n\t\treturn result\n\t}\n\treturn nil\n}\n\nfunc Parse(r io.Reader) (Node, error) {\n\tn, err := yaml.Parse(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn YamlNodeToNode(n), err\n}\n\nfunc Child(root Node, spec string) (Node, error) {\n\treturn nil, nil\n}\n\nfunc (s Scalar) String() string {\n\treturn string(s)\n}\n\nfunc (s Scalar) GetBool() bool {\n\tif s == \"true\" || s == \"yes\" || s == \"1\" {\n\t\treturn true\n\t} else if s == \"false\" || s == \"no\" || s == \"0\" {\n\t\treturn false\n\t}\n\tpanic(\"Invalid bool value:\" + s.String())\n}\n\n\n\nfunc (m Map) Key(key string) Node {\n\treturn m[key]\n}\n\nfunc (l List) Item(idx int) Node {\n\treturn l[idx]\n}\n\nfunc (l List) Len() int {\n\treturn len(l)\n}\n\nfunc (m Map) Keys() []string ", "output": "{\n\tkeys := make([]string, 0, len(m))\n\tfor key := range m {\n\t\tkeys = append(keys, key)\n\t}\n\treturn keys\n}"} {"input": "package classfile\n\nimport (\n\t\"github.com/zxh0/jvm.go/jvmgo/util/bigendian\"\n)\n\ntype ClassReader struct {\n\tdata []byte\n}\n\nfunc newClassReader(data []byte) *ClassReader {\n\treturn &ClassReader{data}\n}\n\nfunc (self *ClassReader) readUint8() uint8 {\n\tval := self.data[0]\n\tself.data = self.data[1:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint16() uint16 {\n\tval := bigendian.Uint16(self.data)\n\tself.data = self.data[2:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint32() uint32 {\n\tval := bigendian.Int32(self.data)\n\tself.data = self.data[4:]\n\treturn uint32(val)\n}\nfunc (self *ClassReader) readInt32() int32 {\n\tval := bigendian.Int32(self.data)\n\tself.data = self.data[4:]\n\treturn val\n}\n\nfunc (self *ClassReader) readInt64() int64 {\n\tval := bigendian.Int64(self.data)\n\tself.data = self.data[8:]\n\treturn val\n}\n\nfunc (self *ClassReader) readFloat32() float32 {\n\tval := bigendian.Float32(self.data)\n\tself.data = self.data[4:]\n\treturn val\n}\n\nfunc (self *ClassReader) readFloat64() float64 {\n\tval := bigendian.Float64(self.data)\n\tself.data = self.data[8:]\n\treturn val\n}\n\nfunc (self *ClassReader) readBytes(length uint32) []byte {\n\tbytes := self.data[:length]\n\tself.data = self.data[length:]\n\treturn bytes\n}\n\n\n\n\nfunc (self *ClassReader) readString() string ", "output": "{\n\tlength := uint32(self.readUint16())\n\tbytes := self.readBytes(length)\n\treturn string(bytes)\n}"} {"input": "package license\n\nimport (\n\t\"context\"\n\n\t\"github.com/sacloud/libsacloud/v2/sacloud\"\n)\n\n\n\nfunc (s *Service) CreateWithContext(ctx context.Context, req *CreateRequest) (*sacloud.License, error) {\n\tif err := req.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tparams, err := req.ToRequestParameter()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := sacloud.NewLicenseOp(s.caller)\n\treturn client.Create(ctx, params)\n}\n\nfunc (s *Service) Create(req *CreateRequest) (*sacloud.License, error) ", "output": "{\n\treturn s.CreateWithContext(context.Background(), req)\n}"} {"input": "package chart\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n)\n\ntype CT_Thickness struct {\n\tValAttr ST_Thickness\n}\n\n\n\nfunc (m *CT_Thickness) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tstart.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: \"val\"},\n\t\tValue: fmt.Sprintf(\"%v\", m.ValAttr)})\n\te.EncodeToken(start)\n\te.EncodeToken(xml.EndElement{Name: start.Name})\n\treturn nil\n}\n\nfunc (m *CT_Thickness) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tfor _, attr := range start.Attr {\n\t\tif attr.Name.Local == \"val\" {\n\t\t\tparsed, err := ParseUnionST_Thickness(attr.Value)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tm.ValAttr = parsed\n\t\t}\n\t}\n\tfor {\n\t\ttok, err := d.Token()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"parsing CT_Thickness: %s\", err)\n\t\t}\n\t\tif el, ok := tok.(xml.EndElement); ok && el.Name == start.Name {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (m *CT_Thickness) Validate() error {\n\treturn m.ValidateWithPath(\"CT_Thickness\")\n}\n\n\nfunc (m *CT_Thickness) ValidateWithPath(path string) error {\n\tif err := m.ValAttr.ValidateWithPath(path + \"/ValAttr\"); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc NewCT_Thickness() *CT_Thickness ", "output": "{\n\tret := &CT_Thickness{}\n\treturn ret\n}"} {"input": "package postgresql\n\nimport (\n\t\"sql\"\n)\n\ntype Connection struct {\n\thandle *pqConnection;\n}\n\nfunc (self *Connection) Query(sql string, params ...interface{}) (sql.ResultSet, sql.Error) {\n\tstmt, err := self.Prepare(sql)\n\tif err != nil {\n\t\treturn nil, err\t\n\t}\n\n\treturn stmt.Query(params...)\n}\n\n\n\nfunc (self *Connection) Prepare(query string) (sql.Statement, sql.Error) {\n\n\tstmt := new(Statement)\n\treturn stmt, nil\n}\n\nfunc (self *Connection) Close() sql.Error {\n\tself.handle.pqClose()\n\treturn nil\n}\n\nfunc (self *Connection) Execute(sql string, params ...interface{}) sql.Error ", "output": "{\n\tstmt, err := self.Prepare(sql)\n\tif err != nil {\n\t\treturn err\t\n\t}\n\n\tdefer stmt.Close()\n\treturn stmt.Execute(params...)\n}"} {"input": "package appfiles\n\nimport (\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com/cloudfoundry/cli/glob\"\n)\n\n\n\ntype CfIgnore interface {\n\tFileShouldBeIgnored(path string) bool\n}\n\nfunc NewCfIgnore(text string) CfIgnore {\n\tpatterns := []ignorePattern{}\n\tlines := strings.Split(text, \"\\n\")\n\tlines = append(defaultIgnoreLines, lines...)\n\n\tfor _, line := range lines {\n\t\tline = strings.TrimSpace(line)\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tignore := true\n\t\tif strings.HasPrefix(line, \"!\") {\n\t\t\tline = line[1:]\n\t\t\tignore = false\n\t\t}\n\n\t\tfor _, p := range globsForPattern(path.Clean(line)) {\n\t\t\tpatterns = append(patterns, ignorePattern{ignore, p})\n\t\t}\n\t}\n\n\treturn cfIgnore(patterns)\n}\n\nfunc (ignore cfIgnore) FileShouldBeIgnored(path string) bool {\n\tresult := false\n\n\tfor _, pattern := range ignore {\n\t\tif strings.HasPrefix(pattern.glob.String(), \"/\") && !strings.HasPrefix(path, \"/\") {\n\t\t\tpath = \"/\" + path\n\t\t}\n\n\t\tif pattern.glob.Match(path) {\n\t\t\tresult = pattern.exclude\n\t\t}\n\t}\n\n\treturn result\n}\n\n\n\ntype ignorePattern struct {\n\texclude bool\n\tglob glob.Glob\n}\n\ntype cfIgnore []ignorePattern\n\nvar defaultIgnoreLines = []string{\n\t\".cfignore\",\n\t\"/manifest.yml\",\n\t\".gitignore\",\n\t\".git\",\n\t\".hg\",\n\t\".svn\",\n\t\"_darcs\",\n\t\".DS_Store\",\n}\n\nfunc globsForPattern(pattern string) (globs []glob.Glob) ", "output": "{\n\tglobs = append(globs, glob.MustCompileGlob(pattern))\n\tglobs = append(globs, glob.MustCompileGlob(path.Join(pattern, \"*\")))\n\tglobs = append(globs, glob.MustCompileGlob(path.Join(pattern, \"**\", \"*\")))\n\n\tif !strings.HasPrefix(pattern, \"/\") {\n\t\tglobs = append(globs, glob.MustCompileGlob(path.Join(\"**\", pattern)))\n\t\tglobs = append(globs, glob.MustCompileGlob(path.Join(\"**\", pattern, \"*\")))\n\t\tglobs = append(globs, glob.MustCompileGlob(path.Join(\"**\", pattern, \"**\", \"*\")))\n\t}\n\n\treturn\n}"} {"input": "package cmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/viper\"\n\t\"github.com/willf/bloom\"\n)\n\nvar checkCmd = &cobra.Command{\n\tUse: \"check\",\n\tShort: \"Check domain presence in the bloom filter\",\n}\n\nfunc init() {\n\tinitCommonFlags(checkCmd)\n\n\tcheckCmd.RunE = check\n}\n\n\n\nfunc check(cmd *cobra.Command, args []string) error ", "output": "{\n\tif err := InitializeConfig(checkCmd); err != nil {\n\t\treturn err\n\t}\n\n\tbf := bloom.New(1000000, 5)\n\n\tfileName := viper.GetString(\"DatabasePath\")\n\tif _, err := os.Stat(fileName); err == nil {\n\t\tbff, err2 := os.Open(fileName)\n\t\tif err2 != nil {\n\t\t\tpanic(err2)\n\t\t}\n\t\tdefer bff.Close()\n\n\t\tif _, err3 := bf.ReadFrom(bff); err != nil {\n\t\t\tpanic(err3)\n\t\t}\n\t} else {\n\t\tfmt.Println(\"You must build a filter first, use 'build' command.\")\n\t\treturn err\n\t}\n\n\tif len(args) > 0 {\n\t\tfor _, domain := range args {\n\t\t\tfmt.Printf(\"%s,%v\\n\", domain, bf.TestString(domain))\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSEMRCluster_HadoopJarStepConfig struct {\n\n\tArgs []string `json:\"Args,omitempty\"`\n\n\tJar string `json:\"Jar,omitempty\"`\n\n\tMainClass string `json:\"MainClass,omitempty\"`\n\n\tStepProperties []AWSEMRCluster_KeyValue `json:\"StepProperties,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\n\n\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) AWSCloudFormationType() string ", "output": "{\n\treturn \"AWS::EMR::Cluster.HadoopJarStepConfig\"\n}"} {"input": "package mdt\n\nimport \"bytes\"\n\ntype rows []row\n\n\n\nfunc (r rows) lengthAt(index int) int {\n\tvar max int\n\tfor _, row := range r {\n\t\tif n := row.lengthAt(index); n > max {\n\t\t\tmax = n\n\t\t}\n\t}\n\tif max < 3 {\n\t\tmax = 3\n\t}\n\treturn max\n}\n\nfunc (r rows) toMarkdown() string {\n\tcolNum := r.colNum()\n\tlens := []int{}\n\tfor i := 0; i < colNum; i++ {\n\t\tlens = append(lens, r.lengthAt(i))\n\t}\n\n\tvar buf bytes.Buffer\n\tfor _, row := range r {\n\t\tbuf.WriteString(row.toMarkdown(colNum, lens) + \"\\n\")\n\t}\n\treturn buf.String()\n}\n\nfunc (r rows) colNum() int ", "output": "{\n\tvar max int\n\tfor _, row := range r {\n\t\tif n := row.colNum(); n > max {\n\t\t\tmax = n\n\t\t}\n\t}\n\treturn max\n}"} {"input": "package elastic\n\nimport (\n\t\"encoding/json\"\n\t\"testing\"\n)\n\nfunc TestRangeQuery(t *testing.T) {\n\tq := NewRangeQuery(\"postDate\").From(\"2010-03-01\").To(\"2010-04-01\").Boost(3)\n\tq = q.QueryName(\"my_query\")\n\tsrc, err := q.Source()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdata, err := json.Marshal(src)\n\tif err != nil {\n\t\tt.Fatalf(\"marshaling to JSON failed: %v\", err)\n\t}\n\tgot := string(data)\n\texpected := `{\"range\":{\"_name\":\"my_query\",\"postDate\":{\"boost\":3,\"from\":\"2010-03-01\",\"include_lower\":true,\"include_upper\":true,\"to\":\"2010-04-01\"}}}`\n\tif got != expected {\n\t\tt.Errorf(\"expected\\n%s\\n,got:\\n%s\", expected, got)\n\t}\n}\n\n\n\nfunc TestRangeQueryWithFormat(t *testing.T) {\n\tq := NewRangeQuery(\"born\").\n\t\tGte(\"2012/01/01\").\n\t\tLte(\"now\").\n\t\tFormat(\"yyyy/MM/dd\")\n\tsrc, err := q.Source()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdata, err := json.Marshal(src)\n\tif err != nil {\n\t\tt.Fatalf(\"marshaling to JSON failed: %v\", err)\n\t}\n\tgot := string(data)\n\texpected := `{\"range\":{\"born\":{\"format\":\"yyyy/MM/dd\",\"from\":\"2012/01/01\",\"include_lower\":true,\"include_upper\":true,\"to\":\"now\"}}}`\n\tif got != expected {\n\t\tt.Errorf(\"expected\\n%s\\n,got:\\n%s\", expected, got)\n\t}\n}\n\nfunc TestRangeQueryWithTimeZone(t *testing.T) ", "output": "{\n\tq := NewRangeQuery(\"born\").\n\t\tGte(\"2012-01-01\").\n\t\tLte(\"now\").\n\t\tTimeZone(\"+1:00\")\n\tsrc, err := q.Source()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdata, err := json.Marshal(src)\n\tif err != nil {\n\t\tt.Fatalf(\"marshaling to JSON failed: %v\", err)\n\t}\n\tgot := string(data)\n\texpected := `{\"range\":{\"born\":{\"from\":\"2012-01-01\",\"include_lower\":true,\"include_upper\":true,\"time_zone\":\"+1:00\",\"to\":\"now\"}}}`\n\tif got != expected {\n\t\tt.Errorf(\"expected\\n%s\\n,got:\\n%s\", expected, got)\n\t}\n}"} {"input": "package common\n\nimport (\n\t\"strconv\"\n\t\"time\"\n)\n\ntype ConversionResult struct {\n\tDateAsString string\n\tDateAsInt int\n\tDate time.Time\n}\n\nfunc ConvertIntToDisplay(dateAsInt int) string {\n\tdayAsString := strconv.Itoa(dateAsInt)\n\n\treturn dayAsString\n}\n\nfunc ConvertStringToDates(dateAsString string) (ConversionResult, error) {\n\tresult := ConversionResult{}\n\tresult.DateAsString = dateAsString\n\n\tdateAsInt, err := strconv.Atoi(dateAsString)\n\tif err != nil {\n\t\treturn result, nil\n\t}\n\tresult.DateAsInt = dateAsInt\n\n\tdate, err := time.Parse(\"20060102\", dateAsString)\n\tif err != nil {\n\t\treturn result, nil\n\t}\n\tresult.Date = date\n\n\treturn result, nil\n}\n\nfunc (d *ConversionResult) Tomorrow() (ConversionResult, error) {\n\treturn ConvertStringToDates(d.Date.AddDate(0, 0, 1).Format(\"20060102\"))\n}\n\n\n\nfunc (d *ConversionResult) Yesterday() (ConversionResult, error) ", "output": "{\n\treturn ConvertStringToDates(d.Date.AddDate(0, 0, -1).Format(\"20060102\"))\n}"} {"input": "package hll\n\nimport \"testing\"\n\nfunc TestOnesTo(t *testing.T) {\n\ttestCases := []struct {\n\t\tstartPos, endPos uint\n\t\texpectResult uint64\n\t}{\n\t\t{0, 0, 1},\n\t\t{63, 63, 1 << 63},\n\t\t{2, 4, 4 + 8 + 16},\n\t\t{56, 63, 0xFF00000000000000},\n\t}\n\n\tfor i, testCase := range testCases {\n\t\tactualResult := onesFromTo(testCase.startPos, testCase.endPos)\n\t\tif testCase.expectResult != actualResult {\n\t\t\tt.Errorf(\"Case %d actual result was %v\", i, actualResult)\n\t\t}\n\t}\n}\n\nfunc TestExtractShift(t *testing.T) {\n\ttestCases := []struct {\n\t\tinput uint64\n\t\tstartPos, endPos uint\n\t\texpectResult uint64\n\t}{\n\t\t{0, 0, 63, 0},\n\t\t{0xAABBCCDD00, 8, 47, 0xAABBCCDD},\n\t\t{0xFF00000000000000, 56, 63, 0xFF},\n\t\t{0xFF, 0, 7, 0xFF},\n\t}\n\n\tfor i, testCase := range testCases {\n\t\tactualResult := extractShift(testCase.input, testCase.startPos, testCase.endPos)\n\t\tif testCase.expectResult != actualResult {\n\t\t\tt.Errorf(\"Case %d actual result was %v\", i, actualResult)\n\t\t}\n\t}\n}\n\n\n\nfunc TestConcat(t *testing.T) ", "output": "{\n\ttestCases := []struct {\n\t\tinputs []concatInput\n\t\texpectResult uint64\n\t}{\n\t\t{[]concatInput{{0xABCD, 0, 15}, {0x1234, 0, 15}}, 0xABCD1234},\n\t\t{[]concatInput{{0x0000ABCD0000, 16, 31}, {0x1234000000000000, 48, 63}}, 0xABCD1234},\n\t\t{[]concatInput{{0x1234, 0, 15}, {0x12, 0, 7}}, 0x123412},\n\t}\n\n\tfor i, testCase := range testCases {\n\t\tactualResult := concat(testCase.inputs)\n\t\tif testCase.expectResult != actualResult {\n\t\t\tt.Errorf(\"Case %d actual result was %x\", i, actualResult)\n\t\t}\n\t}\n}"} {"input": "package geo\n\n\n\ntype Polygon [][]Point\n\n\nfunc NewPolygon(points ...Point) Polygon {\n\tp1, p2 := points[0], points[len(points)-1]\n\tif p1.Longitude() != p2.Longitude() || p1.Latitude() != p2.Latitude() {\n\t\tpoints = append(points, p1)\n\t}\n\treturn Polygon{points}\n}\n\n\n\n\n\n\n\nfunc (p Polygon) Geo() *GeoJSON {\n\tif len(p) == 0 {\n\t\treturn nil\n\t}\n\treturn &GeoJSON{\n\t\tType: \"Polygon\",\n\t\tCoordinates: p,\n\t}\n}\n\nfunc (p *Polygon) Exclude(points ...Point) ", "output": "{\n\tif p == nil {\n\t\treturn\n\t}\n\tp1, p2 := points[0], points[len(points)-1]\n\tif p1.Longitude() != p2.Longitude() || p1.Latitude() != p2.Latitude() {\n\t\tpoints = append(points, p1)\n\t}\n\t*p = append(*p, points)\n}"} {"input": "package queue\n\n\n\n\ntype LazyQueue struct {\n\tqChan chan interface{}\n\tDequeueMethod DequeueMethod\n}\n\n\n\n\ntype DequeueMethod func(interface{})\n\n\n\n\n\n\n\n\nfunc (lq *LazyQueue) Enqueue(qinfo interface{}) {\n\tlq.qChan <- qinfo\n}\n\nfunc (lq *LazyQueue) startDequeue() {\n\tfor {\n\t\tselect {\n\t\tcase bm := <-lq.qChan:\n\t\t\tlq.DequeueMethod(bm)\n\t\t}\n\t}\n}\n\nfunc NewLazyQueue(qsize int, dequeueMethod DequeueMethod, grcount int) *LazyQueue ", "output": "{\n\tqInstance := &LazyQueue{}\n\tqInstance.qChan = make(chan interface{}, qsize)\n\tqInstance.DequeueMethod = dequeueMethod\n\tif grcount <= 0 {\n\t\tgrcount = 1\n\t}\n\tfor i := 0; i < grcount; i++ {\n\t\tgo qInstance.startDequeue()\n\t}\n\n\treturn qInstance\n}"} {"input": "package html\n\nimport (\n\t\"golang.org/x/net/html/atom\"\n)\n\n\n\n\n\nfunc (node *Node) NextByAtom(atom atom.Atom) *Node {\n\tfor node = node.NextElement(); node != nil; node = node.NextElement() {\n\t\tif node.DataAtom == atom {\n\t\t\treturn node\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (node *Node) PrevByAtom(atom atom.Atom) *Node {\n\tfor node = node.PrevElement(); node != nil; node = node.PrevElement() {\n\t\tif node.DataAtom == atom {\n\t\t\treturn node\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (node *Node) FindByAtom(atoms ...atom.Atom) (nodes []*Node) ", "output": "{\n\tnodes = make([]*Node, 1)\n\tnodes[0] = node\n\tfor _, a := range atoms {\n\t\tchildren := make([]*Node, 0)\n\t\tfor _, n := range nodes {\n\t\t\tfor _, c := range n.ElementChildren() {\n\t\t\t\tif c.DataAtom == a {\n\t\t\t\t\tchildren = append(children, c)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tnodes = children\n\t}\n\treturn\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"time\"\n \"sync\"\n)\n\n\nfunc workerNoRetrieve(ch chan int) {\n go func(ch chan int) {\n ch <- 23\n }(ch)\n\n \n}\n\n\nfunc workerAct(ch chan int, x int, y int) int {\n go func(c chan int) {\n sum := x+y\n ch <- sum\n }(ch)\n\n value := <-ch\n return value\n}\n\n\nfunc main() {\n channel := make(chan int)\n fmt.Println(\"Captured val is: \",workerAct(channel, 10, 10))\n workerNoRetrieve(channel)\n fmt.Println(worker2(channel, 23, 43))\n\n time.Sleep(2000) \n}\n\n\n\n\nfunc worker2(ch chan int, x int, y int) int ", "output": "{\n go func(c chan int) {\n sum := x+y\n ch <- sum\n }(ch)\n\n value := <-ch\n return value\n}"} {"input": "package bits\n\n\n\n\nfunc TrailingZeros64(x uint64) int\n\n\n\nfunc MostSignificantOne64(x uint64) int\n\n\n\n\n\nfunc ForEachSetBit64(x uint64, f func(i int)) ", "output": "{\n\tfor x != 0 {\n\t\ti := TrailingZeros64(x)\n\t\tf(i)\n\t\tx &^= MaskOf64(i)\n\t}\n}"} {"input": "package retrieval\n\nimport (\n\t\"time\"\n\n\t\"github.com/prometheus/common/model\"\n\n\t\"github.com/prometheus/prometheus/config\"\n)\n\ntype nopAppender struct{}\n\nfunc (a nopAppender) Append(*model.Sample) {\n}\n\ntype slowAppender struct{}\n\n\n\ntype collectResultAppender struct {\n\tresult model.Samples\n}\n\nfunc (a *collectResultAppender) Append(s *model.Sample) {\n\tfor ln, lv := range s.Metric {\n\t\tif len(lv) == 0 {\n\t\t\tdelete(s.Metric, ln)\n\t\t}\n\t}\n\ta.result = append(a.result, s)\n}\n\n\n\ntype fakeTargetProvider struct {\n\tsources []string\n\tupdate chan *config.TargetGroup\n}\n\nfunc (tp *fakeTargetProvider) Run(ch chan<- *config.TargetGroup, done <-chan struct{}) {\n\tdefer close(ch)\n\tfor {\n\t\tselect {\n\t\tcase tg := <-tp.update:\n\t\t\tch <- tg\n\t\tcase <-done:\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (tp *fakeTargetProvider) Sources() []string {\n\treturn tp.sources\n}\n\nfunc (a slowAppender) Append(*model.Sample) ", "output": "{\n\ttime.Sleep(time.Millisecond)\n\treturn\n}"} {"input": "package config\n\nimport (\n\t\"koding/klientctl/commands/cli\"\n\n\t\"github.com/spf13/cobra\"\n)\n\n\n\n\nfunc NewCommand(c *cli.CLI) *cobra.Command ", "output": "{\n\tcmd := &cobra.Command{\n\t\tUse: \"config\",\n\t\tShort: \"Manage remote machine configuration\",\n\t\tRunE: cli.PrintHelp(c.Err()),\n\t}\n\n\tcmd.AddCommand(\n\t\tNewSetCommand(c),\n\t\tNewShowCommand(c),\n\t)\n\n\tcli.MultiCobraCmdMiddleware(\n\t\tcli.NoArgs, \n\t)(c, cmd)\n\n\treturn cmd\n}"} {"input": "package rest\n\nimport (\n\t\"testing\"\n)\n\nfunc TestReverseRouteResolution(t *testing.T) {\n\n\tnoParam := &Route{\"GET\", \"/\", nil}\n\tgot := noParam.MakePath(nil)\n\texpected := \"/\"\n\tif got != expected {\n\t\tt.Errorf(\"expected %s, got %s\", expected, got)\n\t}\n\n\ttwoParams := &Route{\"GET\", \"/:id.:format\", nil}\n\tgot = twoParams.MakePath(\n\t\tmap[string]string{\n\t\t\t\"id\": \"123\",\n\t\t\t\"format\": \"json\",\n\t\t},\n\t)\n\texpected = \"/123.json\"\n\tif got != expected {\n\t\tt.Errorf(\"expected %s, got %s\", expected, got)\n\t}\n\n\tsplatParam := &Route{\"GET\", \"/:id.*format\", nil}\n\tgot = splatParam.MakePath(\n\t\tmap[string]string{\n\t\t\t\"id\": \"123\",\n\t\t\t\"format\": \"tar.gz\",\n\t\t},\n\t)\n\texpected = \"/123.tar.gz\"\n\tif got != expected {\n\t\tt.Errorf(\"expected %s, got %s\", expected, got)\n\t}\n\n\trelaxedParam := &Route{\"GET\", \"/#file\", nil}\n\tgot = relaxedParam.MakePath(\n\t\tmap[string]string{\n\t\t\t\"file\": \"a.txt\",\n\t\t},\n\t)\n\texpected = \"/a.txt\"\n\tif got != expected {\n\t\tt.Errorf(\"expected %s, got %s\", expected, got)\n\t}\n}\n\n\n\nfunc TestShortcutMethods(t *testing.T) ", "output": "{\n\n\tr := Get(\"/\", nil)\n\tif r.HttpMethod != \"GET\" {\n\t\tt.Errorf(\"expected GET, got %s\", r.HttpMethod)\n\t}\n\n\tr = Post(\"/\", nil)\n\tif r.HttpMethod != \"POST\" {\n\t\tt.Errorf(\"expected POST, got %s\", r.HttpMethod)\n\t}\n\n\tr = Put(\"/\", nil)\n\tif r.HttpMethod != \"PUT\" {\n\t\tt.Errorf(\"expected PUT, got %s\", r.HttpMethod)\n\t}\n\n\tr = Delete(\"/\", nil)\n\tif r.HttpMethod != \"DELETE\" {\n\t\tt.Errorf(\"expected DELETE, got %s\", r.HttpMethod)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"github.com/endophage/gotuf\"\n\t\"github.com/endophage/gotuf/data\"\n\t\"github.com/flynn/go-docopt\"\n)\n\n\n\nfunc cmdMeta(args *docopt.Args, repo *tuf.Repo) error {\n\tpaths := args.All[\"\"].([]string)\n\tfor _, file := range paths {\n\t\treader, _ := os.Open(file)\n\t\tmeta, _ := data.NewFileMeta(reader, \"sha256\")\n\t\tjsonBytes, err := json.Marshal(meta)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfilename := fmt.Sprintf(\"%s.meta.json\", file)\n\t\terr = ioutil.WriteFile(filename, jsonBytes, 0644)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc init() ", "output": "{\n\tregister(\"meta\", cmdMeta, `\nusage: tuftools meta [...]\n\nGenerate sample metadata for file(s) given by path.\n\n`)\n}"} {"input": "package translatableerror\n\n\ntype FlagNoLongerSupportedError struct {\n\tFlag string\n}\n\nfunc (e FlagNoLongerSupportedError) Error() string {\n\treturn \"Flag '{{.Flag}}' is no longer supported.\"\n}\n\n\n\nfunc (e FlagNoLongerSupportedError) Translate(translate func(string, ...interface{}) string) string ", "output": "{\n\treturn translate(e.Error(), map[string]interface{}{\n\t\t\"Flag\": e.Flag,\n\t})\n}"} {"input": "package events\n\n\ntype Broker struct {\n\tevents chan Event \n\tsubs map[chan Event]string \n\tsub chan sub \n\tunsub chan sub \n}\n\n\ntype Event struct {\n\tName string \n\tData interface{} \n}\n\ntype sub struct {\n\tname string \n\tevents chan Event \n}\n\n\n\nfunc New() *Broker {\n\tb := &Broker{\n\t\tevents: make(chan Event, 8),\n\t\tsubs: make(map[chan Event]string),\n\t\tsub: make(chan sub),\n\t\tunsub: make(chan sub),\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase c := <-b.sub: \n\t\t\t\tb.subs[c.events] = c.name\n\t\t\tcase c := <-b.unsub: \n\t\t\t\tdelete(b.subs, c.events)\n\t\t\tcase e := <-b.events: \n\t\t\t\tfor c := range b.subs {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase c <- e:\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn b\n}\n\n\n\n\n\nfunc (b Broker) Unsubscribe(c chan Event) {\n\tb.unsub <- sub{events: c}\n}\n\n\nfunc (b Broker) Publish(e Event) {\n\tb.events <- e\n}\n\nfunc (b Broker) Subscribe(name string) chan Event ", "output": "{\n\tc := make(chan Event)\n\tb.sub <- sub{name: name, events: c}\n\treturn c\n}"} {"input": "package discovery\n\nimport (\n\t\"fmt\"\n\t\"github.com/spencergibb/go-nuvem/util\"\n\t\"github.com/spf13/viper\"\n\t\"net\"\n\t\"strconv\"\n)\n\ntype StaticDiscovery struct {\n\tNamespace string\n\tInstances []string\n}\n\nfunc (s *StaticDiscovery) Configure(namespace string) {\n\tif s.Namespace != \"\" {\n\t\tfmt.Errorf(\"%s already inited: %s\", StaticFactoryKey, s.Namespace)\n\t\treturn\n\t}\n\ts.Namespace = namespace\n\tinstances := viper.GetStringSlice(util.GetStaticRegistryKey(s))\n\tfmt.Printf(\"instances %+v\\n\", instances)\n\ts.Instances = instances\n}\n\nfunc (s *StaticDiscovery) GetIntances() []util.Instance {\n\tinstances := make([]util.Instance, len(s.Instances))\n\n\tfor i, config := range s.Instances {\n\t\thost, portStr, err := net.SplitHostPort(config)\n\n\t\tport, err := strconv.Atoi(portStr)\n\n\t\tprint(err) \n\n\t\tinstances[i] = util.Instance{Host: host, Port: port}\n\t}\n\n\treturn instances\n}\n\nfunc (s *StaticDiscovery) GetNamespace() string {\n\treturn s.Namespace\n}\n\nfunc NewStaticDiscovery() Discovery {\n\treturn &StaticDiscovery{}\n}\n\nvar StaticFactoryKey = \"StaticDiscovery\"\n\n\n\nfunc init() ", "output": "{\n\tprintln(\"registering static discovery\")\n\tRegister(StaticFactoryKey, NewStaticDiscovery)\n}"} {"input": "package alert\n\nimport (\n\t. \"aliyun-openapi-go-sdk/core\"\n)\n\ntype GetContactGroupRequest struct {\n\tRoaRequest\n\tProjectName string\n\tGroupName string\n}\n\n\nfunc (r *GetContactGroupRequest) GetProjectName() string {\n\treturn r.ProjectName\n}\nfunc (r *GetContactGroupRequest) SetGroupName(value string) {\n\tr.GroupName = value\n\tr.PathParams.Set(\"GroupName\", value)\n}\nfunc (r *GetContactGroupRequest) GetGroupName() string {\n\treturn r.GroupName\n}\n\nfunc (r *GetContactGroupRequest) Init() {\n\tr.RoaRequest.Init()\n\tr.PathPattern = \"/projects/ProjectName/groups/GroupName\"\n\tr.SetMethod(\"GET\")\n\tr.SetProtocol(\"HTTP\")\n\tr.SetProduct(Product)\n}\n\ntype GetContactGroupResponse struct {\n\tcode string `xml:\"code\" json:\"code\"`\n\tmessage string `xml:\"message\" json:\"message\"`\n\tsuccess string `xml:\"success\" json:\"success\"`\n\ttraceId string `xml:\"traceId\" json:\"traceId\"`\n\tresult string `xml:\"result\" json:\"result\"`\n}\n\nfunc GetContactGroup(req *GetContactGroupRequest, accessId, accessSecret string) (*GetContactGroupResponse, error) {\n\tvar pResponse GetContactGroupResponse\n\tbody, err := ApiHttpRequest(accessId, accessSecret, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tApiUnmarshalResponse(req.GetFormat(), body, &pResponse)\n\treturn &pResponse, err\n}\n\nfunc (r *GetContactGroupRequest) SetProjectName(value string) ", "output": "{\n\tr.ProjectName = value\n\tr.PathParams.Set(\"ProjectName\", value)\n}"} {"input": "package common\n\nimport (\n\t\"log\"\n\t\"time\"\n\n\t\"gopkg.in/mgo.v2\"\n)\n\nvar session *mgo.Session\n\nfunc GetSession() *mgo.Session {\n\tif session == nil {\n\t\tvar err error\n\t\tsession, err = mgo.DialWithInfo(&mgo.DialInfo{\n\t\t\tAddrs: []string{AppConfig.MongoDBHost},\n\t\t\tUsername: AppConfig.DBUser,\n\t\t\tPassword: AppConfig.DBPwd,\n\t\t\tTimeout: 60 * time.Second,\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"[GetSession]: %s\\n\", err)\n\t\t}\n\t}\n\treturn session\n}\nfunc createDbSession() {\n\tvar err error\n\tsession, err = mgo.DialWithInfo(&mgo.DialInfo{\n\t\tAddrs: []string{AppConfig.MongoDBHost},\n\t\tUsername: AppConfig.DBUser,\n\t\tPassword: AppConfig.DBPwd,\n\t\tTimeout: 60 * time.Second,\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"[createDbSession]: %s\\n\", err)\n\t}\n}\n\n\n\n\nfunc addIndexes() ", "output": "{\n\tvar err error\n\tuserIndex := mgo.Index{\n\t\tKey: []string{\"email\"},\n\t\tUnique: true,\n\t\tBackground: true,\n\t\tSparse: true,\n\t}\n\tsession := GetSession().Copy()\n\tdefer session.Close()\n\tuserCol := session.DB(AppConfig.Database).C(\"users\")\n\n\terr = userCol.EnsureIndex(userIndex)\n\tif err != nil {\n\t\tlog.Fatalf(\"[addIndexes]: %s\\n\", err)\n\t}\n}"} {"input": "package soundcloud\n\nimport (\n\t\"net/url\"\n)\n\ntype PlaylistApi struct {\n\tplaylistEndpoint\n}\n\nfunc (api *Api) Playlists(params url.Values) ([]*Playlist, error) {\n\tret := make([]*Playlist, 0)\n\terr := api.get(\"/playlists\", params, &ret)\n\treturn ret, err\n}\n\n\n\nfunc (api *Api) Playlist(id uint64) *PlaylistApi ", "output": "{\n\treturn &PlaylistApi{*api.newPlaylistEndpoint(\"playlists\", id)}\n}"} {"input": "package genny\n\nimport (\n\t\"github.com/markbates/safe\"\n\t\"github.com/pkg/errors\"\n)\n\ntype TransformerFn func(File) (File, error)\n\ntype Transformer struct {\n\tExt string\n\tStripExt bool\n\tfn TransformerFn\n}\n\nfunc (t Transformer) Transform(f File) (File, error) {\n\tif !HasExt(f, t.Ext) {\n\t\treturn f, nil\n\t}\n\tif t.fn == nil {\n\t\treturn f, nil\n\t}\n\terr := safe.RunE(func() error {\n\t\tvar e error\n\t\tf, e = t.fn(f)\n\t\tif e != nil {\n\t\t\treturn errors.WithStack(e)\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn f, errors.WithStack(err)\n\t}\n\tif t.StripExt {\n\t\treturn StripExt(f, t.Ext), nil\n\t}\n\treturn f, nil\n}\n\n\n\nfunc NewTransformer(ext string, fn TransformerFn) Transformer ", "output": "{\n\treturn Transformer{\n\t\tExt: ext,\n\t\tfn: fn,\n\t}\n}"} {"input": "package loadbalancer\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n)\n\n\n\n\n\ntype WorkRequest struct {\n\tErrorDetails []WorkRequestError `mandatory:\"true\" json:\"errorDetails\"`\n\n\tId *string `mandatory:\"true\" json:\"id\"`\n\n\tLifecycleState WorkRequestLifecycleStateEnum `mandatory:\"true\" json:\"lifecycleState\"`\n\n\tLoadBalancerId *string `mandatory:\"true\" json:\"loadBalancerId\"`\n\n\tMessage *string `mandatory:\"true\" json:\"message\"`\n\n\tTimeAccepted *common.SDKTime `mandatory:\"true\" json:\"timeAccepted\"`\n\n\tType *string `mandatory:\"true\" json:\"type\"`\n\n\tTimeFinished *common.SDKTime `mandatory:\"false\" json:\"timeFinished\"`\n}\n\nfunc (m WorkRequest) String() string {\n\treturn common.PointerString(m)\n}\n\n\ntype WorkRequestLifecycleStateEnum string\n\n\nconst (\n\tWorkRequestLifecycleStateAccepted WorkRequestLifecycleStateEnum = \"ACCEPTED\"\n\tWorkRequestLifecycleStateInProgress WorkRequestLifecycleStateEnum = \"IN_PROGRESS\"\n\tWorkRequestLifecycleStateFailed WorkRequestLifecycleStateEnum = \"FAILED\"\n\tWorkRequestLifecycleStateSucceeded WorkRequestLifecycleStateEnum = \"SUCCEEDED\"\n)\n\nvar mappingWorkRequestLifecycleState = map[string]WorkRequestLifecycleStateEnum{\n\t\"ACCEPTED\": WorkRequestLifecycleStateAccepted,\n\t\"IN_PROGRESS\": WorkRequestLifecycleStateInProgress,\n\t\"FAILED\": WorkRequestLifecycleStateFailed,\n\t\"SUCCEEDED\": WorkRequestLifecycleStateSucceeded,\n}\n\n\n\n\nfunc GetWorkRequestLifecycleStateEnumValues() []WorkRequestLifecycleStateEnum ", "output": "{\n\tvalues := make([]WorkRequestLifecycleStateEnum, 0)\n\tfor _, v := range mappingWorkRequestLifecycleState {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}"} {"input": "package systemd\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/google/cadvisor/container\"\n\t\"github.com/google/cadvisor/fs\"\n\tinfo \"github.com/google/cadvisor/info/v1\"\n\t\"github.com/google/cadvisor/watcher\"\n\n\t\"k8s.io/klog/v2\"\n)\n\ntype systemdFactory struct{}\n\nfunc (f *systemdFactory) String() string {\n\treturn \"systemd\"\n}\n\nfunc (f *systemdFactory) NewContainerHandler(name string, inHostNamespace bool) (container.ContainerHandler, error) {\n\treturn nil, fmt.Errorf(\"Not yet supported\")\n}\n\nfunc (f *systemdFactory) CanHandleAndAccept(name string) (bool, bool, error) {\n\tif strings.HasSuffix(name, \".mount\") {\n\t\treturn true, false, nil\n\t}\n\tklog.V(5).Infof(\"%s not handled by systemd handler\", name)\n\treturn false, false, nil\n}\n\n\n\n\nfunc Register(machineInfoFactory info.MachineInfoFactory, fsInfo fs.FsInfo, includedMetrics container.MetricSet) error {\n\tklog.V(1).Infof(\"Registering systemd factory\")\n\tfactory := &systemdFactory{}\n\tcontainer.RegisterContainerHandlerFactory(factory, []watcher.ContainerWatchSource{watcher.Raw})\n\treturn nil\n}\n\nfunc (f *systemdFactory) DebugInfo() map[string][]string ", "output": "{\n\treturn map[string][]string{}\n}"} {"input": "package messenger\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/scionproto/scion/go/lib/common\"\n\t\"github.com/scionproto/scion/go/lib/ctrl\"\n\t\"github.com/scionproto/scion/go/lib/infra/disp\"\n\t\"github.com/scionproto/scion/go/lib/log\"\n\t\"github.com/scionproto/scion/go/proto\"\n)\n\nvar _ disp.MessageAdapter = (*Adapter)(nil)\n\n\ntype Adapter struct{}\n\n\nvar DefaultAdapter = &Adapter{}\n\nfunc (a *Adapter) MsgToRaw(msg proto.Cerealizable) (common.RawBytes, error) {\n\tpld, ok := msg.(*ctrl.SignedPld)\n\tif !ok {\n\t\treturn nil, common.NewBasicError(\n\t\t\t\"Unable to type assert proto.Cerealizable to ctrl.SignedPld\",\n\t\t\tnil, \"msg\", msg, \"type\", common.TypeOf(msg))\n\t}\n\treturn pld.PackPld()\n}\n\nfunc (a *Adapter) RawToMsg(b common.RawBytes) (proto.Cerealizable, error) {\n\treturn ctrl.NewSignedPldFromRaw(b)\n}\n\n\n\nfunc (a *Adapter) MsgKey(msg proto.Cerealizable) string ", "output": "{\n\tsignedCtrlPld, ok := msg.(*ctrl.SignedPld)\n\tif !ok {\n\t\tlog.Warn(\"Unable to type assert disp.Message to ctrl.SignedPld\", \"msg\", msg,\n\t\t\t\"type\", common.TypeOf(msg))\n\t\treturn \"\"\n\t}\n\n\tctrlPld, err := signedCtrlPld.Pld()\n\tif err != nil {\n\t\tlog.Warn(\"Unable to extract CtrlPld from SignedCtrlPld\", \"err\", err)\n\t\treturn \"\"\n\t}\n\treturn strconv.FormatUint(ctrlPld.ReqId, 10)\n}"} {"input": "package master\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\n\tauth \"github.com/abbot/go-http-auth\"\n\t\"github.com/h2oai/steam/master/az\"\n)\n\ntype DefaultAz struct {\n\tdirectory az.Directory\n}\n\nfunc NewDefaultAz(directory az.Directory) *DefaultAz {\n\treturn &DefaultAz{directory}\n}\n\n\n\nfunc (a *DefaultAz) Identify(r *http.Request) (az.Principal, error) {\n\tusername := r.Header.Get(auth.AuthUsernameHeader)\n\tpz, err := a.directory.Lookup(username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif pz == nil {\n\t\treturn nil, fmt.Errorf(\"User %s does not exist\\n\", username)\n\t}\n\n\treturn pz, nil\n}\n\nfunc serveNoop(w http.ResponseWriter, r *http.Request) {}\nfunc authNoop(user, realm string) string { return \"\" }\n\nfunc (a *DefaultAz) Authenticate(username string) string ", "output": "{\n\tpz, err := a.directory.Lookup(username)\n\tif err != nil {\n\t\tlog.Printf(\"User %s read failed: %s\\n\", username, err)\n\t\treturn \"\"\n\t}\n\n\tif pz == nil {\n\t\tlog.Printf(\"User %s does not exist\\n\", username)\n\t\treturn \"\"\n\t}\n\treturn pz.Password()\n}"} {"input": "package csvutil\n\nimport (\n\t\"reflect\"\n\t\"strings\"\n)\n\ntype tag struct {\n\tname string\n\tempty bool\n\tomitEmpty bool\n\tignore bool\n}\n\n\n\nfunc parseTag(tagname string, field reflect.StructField) (t tag) ", "output": "{\n\ttags := strings.Split(field.Tag.Get(tagname), \",\")\n\tif len(tags) == 1 && tags[0] == \"\" {\n\t\tt.name = field.Name\n\t\tt.empty = true\n\t\treturn\n\t}\n\tswitch tags[0] {\n\tcase \"-\":\n\t\tt.ignore = true\n\t\treturn\n\tcase \"\":\n\t\tt.name = field.Name\n\tdefault:\n\t\tt.name = tags[0]\n\t}\n\tfor _, tagOpt := range tags[1:] {\n\t\tswitch tagOpt {\n\t\tcase \"omitempty\":\n\t\t\tt.omitEmpty = true\n\t\t}\n\t}\n\treturn\n}"} {"input": "package encode\n\nimport \"testing\"\n\nfunc TestRunLengthEncode(t *testing.T) {\n\tfor _, test := range encodeTests {\n\t\tif actual := RunLengthEncode(test.input); actual != test.expected {\n\t\t\tt.Errorf(\"FAIL %s - RunLengthEncode(%s) = %q, expected %q.\",\n\t\t\t\ttest.description, test.input, actual, test.expected)\n\t\t}\n\t\tt.Logf(\"PASS RunLengthEncode - %s\", test.description)\n\t}\n}\nfunc TestRunLengthDecode(t *testing.T) {\n\tfor _, test := range decodeTests {\n\t\tif actual := RunLengthDecode(test.input); actual != test.expected {\n\t\t\tt.Errorf(\"FAIL %s - RunLengthDecode(%s) = %q, expected %q.\",\n\t\t\t\ttest.description, test.input, actual, test.expected)\n\t\t}\n\t\tt.Logf(\"PASS RunLengthDecode - %s\", test.description)\n\t}\n}\n\n\nfunc TestRunLengthEncodeDecode(t *testing.T) ", "output": "{\n\tfor _, test := range encodeDecodeTests {\n\t\tif actual := RunLengthDecode(RunLengthEncode(test.input)); actual != test.expected {\n\t\t\tt.Errorf(\"FAIL %s - RunLengthDecode(RunLengthEncode(%s)) = %q, expected %q.\",\n\t\t\t\ttest.description, test.input, actual, test.expected)\n\t\t}\n\t\tt.Logf(\"PASS %s\", test.description)\n\t}\n}"} {"input": "package iso20022\n\n\ntype GrossDividendRateFormat21Choice struct {\n\n\tAmount *ActiveCurrencyAnd13DecimalAmount `xml:\"Amt\"`\n\n\tAmountAndRateStatus *AmountAndRateStatus1 `xml:\"AmtAndRateSts\"`\n\n\tRateTypeAndAmountAndRateStatus *RateTypeAndAmountAndStatus22 `xml:\"RateTpAndAmtAndRateSts\"`\n}\n\nfunc (g *GrossDividendRateFormat21Choice) SetAmount(value, currency string) {\n\tg.Amount = NewActiveCurrencyAnd13DecimalAmount(value, currency)\n}\n\n\n\nfunc (g *GrossDividendRateFormat21Choice) AddRateTypeAndAmountAndRateStatus() *RateTypeAndAmountAndStatus22 {\n\tg.RateTypeAndAmountAndRateStatus = new(RateTypeAndAmountAndStatus22)\n\treturn g.RateTypeAndAmountAndRateStatus\n}\n\nfunc (g *GrossDividendRateFormat21Choice) AddAmountAndRateStatus() *AmountAndRateStatus1 ", "output": "{\n\tg.AmountAndRateStatus = new(AmountAndRateStatus1)\n\treturn g.AmountAndRateStatus\n}"} {"input": "package x11\n\nimport (\n\t\"C\"\n\t\"unsafe\"\n\n\t\"github.com/richardwilkes/toolbox/xmath/geom\"\n\t\"github.com/richardwilkes/ui/keys\"\n)\n\ntype CrossingEvent C.XCrossingEvent\n\nfunc (evt *CrossingEvent) Window() Window {\n\treturn Window(evt.window)\n}\n\n\n\nfunc (evt *CrossingEvent) Modifiers() keys.Modifiers {\n\treturn Modifiers(evt.state)\n}\n\nfunc (evt *CrossingEvent) ToEvent() *Event {\n\treturn (*Event)(unsafe.Pointer(evt))\n}\n\nfunc (evt *CrossingEvent) Where() geom.Point ", "output": "{\n\treturn geom.Point{X: float64(evt.x), Y: float64(evt.y)}\n}"} {"input": "package iso20022\n\n\ntype TaxReportHeader1 struct {\n\n\tMessageIdentification *MessageIdentification1 `xml:\"MsgId\"`\n\n\tNumberOfTaxReports *Number `xml:\"NbOfTaxRpts,omitempty\"`\n\n\tTaxAuthority []*TaxOrganisationIdentification1 `xml:\"TaxAuthrty,omitempty\"`\n}\n\nfunc (t *TaxReportHeader1) AddMessageIdentification() *MessageIdentification1 {\n\tt.MessageIdentification = new(MessageIdentification1)\n\treturn t.MessageIdentification\n}\n\n\n\nfunc (t *TaxReportHeader1) AddTaxAuthority() *TaxOrganisationIdentification1 {\n\tnewValue := new(TaxOrganisationIdentification1)\n\tt.TaxAuthority = append(t.TaxAuthority, newValue)\n\treturn newValue\n}\n\nfunc (t *TaxReportHeader1) SetNumberOfTaxReports(value string) ", "output": "{\n\tt.NumberOfTaxReports = (*Number)(&value)\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n)\n\ntype HelloHandler struct {\n\tSaying string\n\tcounter int\n}\n\n\n\nfunc (h *HelloHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) ", "output": "{\n\tsaying := Saying{\n\t\tId: h.counter,\n\t\tSaying: h.Saying,\n\t}\n\n\tb, _ := json.Marshal(&saying)\n\th.counter++\n\tw.Write(b)\n}"} {"input": "package event\n\nimport (\n\t\"fmt\"\n\t\"sync/atomic\"\n\t\"time\"\n)\n\n\ntype Increment struct {\n\tName string\n\tValue int64\n}\n\nfunc (e *Increment) StatClass() string {\n\treturn \"counter\"\n}\n\n\nfunc (e *Increment) Update(e2 Event) error {\n\tif e.Type() != e2.Type() {\n\t\treturn fmt.Errorf(\"statsd event type conflict: %s vs %s \", e.String(), e2.String())\n\t}\n\tatomic.AddInt64(&e.Value, e2.Payload().(int64))\n\treturn nil\n}\n\n\nfunc (e *Increment) Reset() {\n\te.Value = 0\n}\n\n\nfunc (e Increment) Payload() interface{} {\n\treturn e.Value\n}\n\n\nfunc (e Increment) Stats(tick time.Duration) []string {\n\treturn []string{fmt.Sprintf(\"%s:%d|c\", e.Name, e.Value)}\n}\n\n\nfunc (e Increment) Key() string {\n\treturn e.Name\n}\n\n\n\n\n\nfunc (e Increment) Type() int {\n\treturn EventIncr\n}\n\n\nfunc (e Increment) TypeString() string {\n\treturn \"Increment\"\n}\n\n\nfunc (e Increment) String() string {\n\treturn fmt.Sprintf(\"{Type: %s, Key: %s, Value: %d}\", e.TypeString(), e.Name, e.Value)\n}\n\nfunc (e *Increment) SetKey(key string) ", "output": "{\n\te.Name = key\n}"} {"input": "package goutils\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"strings\"\n)\n\nvar letters = []rune(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\")\n\nfunc RandNString(n int) string {\n\tb := make([]rune, n)\n\tfor i := range b {\n\t\tb[i] = letters[rand.Intn(len(letters))]\n\t}\n\treturn string(b)\n}\n\n\n\nfunc StrFormat(format string, kv map[string]interface{}) string ", "output": "{\n\tfor key, val := range kv {\n\t\tkey = \"{\" + key + \"}\"\n\t\tformat = strings.Replace(format, key, fmt.Sprintf(\"%v\", val), -1)\n\t}\n\treturn format\n}"} {"input": "package fake_command_runner_matchers\n\nimport (\n\t\"fmt\"\n\t\"os/exec\"\n\n\t\"github.com/cloudfoundry/gunk/command_runner/fake_command_runner\"\n)\n\n\n\ntype HaveKilledMatcher struct {\n\tSpec fake_command_runner.CommandSpec\n\tkilled []*exec.Cmd\n}\n\nfunc (m *HaveKilledMatcher) Match(actual interface{}) (bool, error) {\n\trunner, ok := actual.(*fake_command_runner.FakeCommandRunner)\n\tif !ok {\n\t\treturn false, fmt.Errorf(\"Not a fake command runner: %#v.\", actual)\n\t}\n\n\tm.killed = runner.KilledCommands()\n\n\tmatched := false\n\tfor _, cmd := range m.killed {\n\t\tif m.Spec.Matches(cmd) {\n\t\t\tmatched = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif matched {\n\t\treturn true, nil\n\t} else {\n\t\treturn false, nil\n\t}\n}\n\nfunc (m *HaveKilledMatcher) FailureMessage(actual interface{}) (message string) {\n\treturn fmt.Sprintf(\"Expected to kill:%s\\n\\nActually killed:%s\", prettySpec(m.Spec), prettyCommands(m.killed))\n}\n\nfunc (m *HaveKilledMatcher) NegatedFailureMessage(actual interface{}) (message string) {\n\treturn fmt.Sprintf(\"Expected to not kill the following commands:%s\", prettySpec(m.Spec))\n}\n\nfunc HaveKilled(spec fake_command_runner.CommandSpec) *HaveKilledMatcher ", "output": "{\n\treturn &HaveKilledMatcher{Spec: spec}\n}"} {"input": "package readers\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n)\n\n\n\nfunc NewIOStat() IReader {\n\tios := &IOStat{}\n\tios.Data = make(map[string]interface{})\n\treturn ios\n}\n\ntype IOStat struct {\n\tData map[string]interface{}\n}\n\n\nfunc (ios *IOStat) Run() error {\n\treturn errors.New(\"iostat -x is only available on Linux.\")\n}\n\n\nfunc (ios *IOStat) ToJson() ([]byte, error) {\n\treturn json.Marshal(ios.Data)\n}\n\nfunc init() ", "output": "{\n\tRegister(\"IOStat\", NewIOStat)\n}"} {"input": "package local\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/apache/beam/sdks/go/pkg/beam/io/textio\"\n)\n\nfunc init() {\n\ttextio.RegisterFileSystem(\"default\", New)\n}\n\ntype fs struct{}\n\n\nfunc New(ctx context.Context) textio.FileSystem {\n\treturn &fs{}\n}\n\n\n\nfunc (f *fs) List(ctx context.Context, glob string) ([]string, error) {\n\treturn filepath.Glob(glob)\n}\n\nfunc (f *fs) OpenRead(ctx context.Context, filename string) (io.ReadCloser, error) {\n\treturn os.Open(filename)\n}\n\nfunc (f *fs) OpenWrite(ctx context.Context, filename string) (io.WriteCloser, error) {\n\tif err := os.MkdirAll(filepath.Dir(filename), 0755); err != nil {\n\t\treturn nil, err\n\t}\n\treturn os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)\n}\n\nfunc (f *fs) Close() error ", "output": "{\n\treturn nil\n}"} {"input": "package leetcode\n\n\n\n\nfunc myPow(x float64, n int) float64 {\n\tif n == 0 {\n\t\treturn 1\n\t}\n\tflag := false\n\tif n > 0 {\n\t\tflag = true\n\t} else {\n\t\tn = -n\n\t}\n\tres := pow(x, n)\n\tif !flag {\n\t\tres = 1 / res\n\t}\n\treturn res\n}\n\n\n\nfunc pow(x float64, n int) float64 ", "output": "{\n\tif n == 1 {\n\t\treturn x\n\t}\n\tres := pow(x*x, n/2)\n\tif n%2 == 1 {\n\t\tres *= x\n\t}\n\treturn res\n}"} {"input": "package compute_test\n\nimport (\n\t\"context\"\n\n\tcompute \"cloud.google.com/go/compute/apiv1\"\n\t\"google.golang.org/api/iterator\"\n\tcomputepb \"google.golang.org/genproto/googleapis/cloud/compute/v1\"\n)\n\nfunc ExampleNewAcceleratorTypesRESTClient() {\n\tctx := context.Background()\n\tc, err := compute.NewAcceleratorTypesRESTClient(ctx)\n\tif err != nil {\n\t}\n\tdefer c.Close()\n\n\t_ = c\n}\n\n\n\nfunc ExampleAcceleratorTypesClient_Get() {\n\tctx := context.Background()\n\tc, err := compute.NewAcceleratorTypesRESTClient(ctx)\n\tif err != nil {\n\t}\n\tdefer c.Close()\n\n\treq := &computepb.GetAcceleratorTypeRequest{\n\t}\n\tresp, err := c.Get(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\nfunc ExampleAcceleratorTypesClient_List() {\n\tctx := context.Background()\n\tc, err := compute.NewAcceleratorTypesRESTClient(ctx)\n\tif err != nil {\n\t}\n\tdefer c.Close()\n\n\treq := &computepb.ListAcceleratorTypesRequest{\n\t}\n\tit := c.List(ctx, req)\n\tfor {\n\t\tresp, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t}\n\t\t_ = resp\n\t}\n}\n\nfunc ExampleAcceleratorTypesClient_AggregatedList() ", "output": "{\n\tctx := context.Background()\n\tc, err := compute.NewAcceleratorTypesRESTClient(ctx)\n\tif err != nil {\n\t}\n\tdefer c.Close()\n\n\treq := &computepb.AggregatedListAcceleratorTypesRequest{\n\t}\n\tit := c.AggregatedList(ctx, req)\n\tfor {\n\t\tresp, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t}\n\t\t_ = resp\n\t}\n}"} {"input": "package filtered\n\nimport (\n\tcontext \"context\"\n\n\tv1 \"github.com/google/knative-gcp/pkg/client/informers/externalversions/events/v1\"\n\tfiltered \"github.com/google/knative-gcp/pkg/client/injection/informers/factory/filtered\"\n\tcontroller \"knative.dev/pkg/controller\"\n\tinjection \"knative.dev/pkg/injection\"\n\tlogging \"knative.dev/pkg/logging\"\n)\n\nfunc init() {\n\tinjection.Default.RegisterFilteredInformers(withInformer)\n}\n\n\ntype Key struct {\n\tSelector string\n}\n\n\n\n\nfunc Get(ctx context.Context, selector string) v1.CloudStorageSourceInformer {\n\tuntyped := ctx.Value(Key{Selector: selector})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panicf(\n\t\t\t\"Unable to fetch github.com/google/knative-gcp/pkg/client/informers/externalversions/events/v1.CloudStorageSourceInformer with selector %s from context.\", selector)\n\t}\n\treturn untyped.(v1.CloudStorageSourceInformer)\n}\n\nfunc withInformer(ctx context.Context) (context.Context, []controller.Informer) ", "output": "{\n\tuntyped := ctx.Value(filtered.LabelKey{})\n\tif untyped == nil {\n\t\tlogging.FromContext(ctx).Panic(\n\t\t\t\"Unable to fetch labelkey from context.\")\n\t}\n\tlabelSelectors := untyped.([]string)\n\tinfs := []controller.Informer{}\n\tfor _, selector := range labelSelectors {\n\t\tf := filtered.Get(ctx, selector)\n\t\tinf := f.Events().V1().CloudStorageSources()\n\t\tctx = context.WithValue(ctx, Key{Selector: selector}, inf)\n\t\tinfs = append(infs, inf.Informer())\n\t}\n\treturn ctx, infs\n}"} {"input": "package server\n\nimport (\n\t\"sync\"\n)\n\ntype ID uint32\n\ntype IDGenerator struct {\n\tlastID ID\n\tids []ID\n\tlocker *sync.Mutex\n\tthreadSafe bool\n}\n\nfunc NewIDGenerator(buffer int, threadSafe bool) *IDGenerator {\n\tgen := &IDGenerator{0, make([]ID, 0, buffer), &sync.Mutex{}, threadSafe}\n\tif threadSafe {\n\t\tgen.locker.Lock()\n\t\tdefer gen.locker.Unlock()\n\t}\n\n\tgen.genIDs()\n\treturn gen\n}\n\n\n\nfunc (gen *IDGenerator) NextID() ID {\n\tid := ID(0)\n\n\tif gen.threadSafe {\n\t\tgen.locker.Lock()\n\t\tdefer gen.locker.Unlock()\n\t}\n\tid, gen.ids = gen.ids[len(gen.ids)-1], gen.ids[:len(gen.ids)-1]\n\tif len(gen.ids) == 0 {\n\t\tgen.genIDs()\n\t}\n\n\treturn id\n}\n\nfunc (gen *IDGenerator) PutID(id ID) {\n\tif gen.threadSafe {\n\t\tgen.locker.Lock()\n\t\tdefer gen.locker.Unlock()\n\t}\n\tgen.ids = append(gen.ids, id)\n}\n\nfunc (gen *IDGenerator) genIDs() ", "output": "{\n\tgen.lastID += ID(cap(gen.ids) / 2)\n\tid := gen.lastID - 1\n\tfor i := 0; i < cap(gen.ids)/2; i++ {\n\t\tgen.ids = append(gen.ids, id)\n\t\tid--\n\t}\n}"} {"input": "package release_v1_5\n\nimport (\n\t\"github.com/golang/glog\"\n\tv1core \"github.com/openshift/origin/pkg/build/client/clientset_generated/release_v1_5/typed/core/v1\"\n\trestclient \"k8s.io/kubernetes/pkg/client/restclient\"\n\tdiscovery \"k8s.io/kubernetes/pkg/client/typed/discovery\"\n\t\"k8s.io/kubernetes/pkg/util/flowcontrol\"\n)\n\ntype Interface interface {\n\tDiscovery() discovery.DiscoveryInterface\n\tCore() v1core.CoreInterface\n}\n\n\n\ntype Clientset struct {\n\t*discovery.DiscoveryClient\n\t*v1core.CoreClient\n}\n\n\nfunc (c *Clientset) Core() v1core.CoreInterface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.CoreClient\n}\n\n\nfunc (c *Clientset) Discovery() discovery.DiscoveryInterface {\n\treturn c.DiscoveryClient\n}\n\n\n\n\n\n\nfunc NewForConfigOrDie(c *restclient.Config) *Clientset {\n\tvar clientset Clientset\n\tclientset.CoreClient = v1core.NewForConfigOrDie(c)\n\n\tclientset.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c)\n\treturn &clientset\n}\n\n\nfunc New(c *restclient.RESTClient) *Clientset {\n\tvar clientset Clientset\n\tclientset.CoreClient = v1core.New(c)\n\n\tclientset.DiscoveryClient = discovery.NewDiscoveryClient(c)\n\treturn &clientset\n}\n\nfunc NewForConfig(c *restclient.Config) (*Clientset, error) ", "output": "{\n\tconfigShallowCopy := *c\n\tif configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 {\n\t\tconfigShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst)\n\t}\n\tvar clientset Clientset\n\tvar err error\n\tclientset.CoreClient, err = v1core.NewForConfig(&configShallowCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclientset.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy)\n\tif err != nil {\n\t\tglog.Errorf(\"failed to create the DiscoveryClient: %v\", err)\n\t\treturn nil, err\n\t}\n\treturn &clientset, nil\n}"} {"input": "package healthcheck\n\nimport (\n\t\"k8s.io/kubernetes/pkg/apis/extensions\"\n\n\t\"k8s.io/ingress/core/pkg/ingress/annotations/parser\"\n\t\"k8s.io/ingress/core/pkg/ingress/resolver\"\n)\n\nconst (\n\tupsMaxFails = \"ingress.kubernetes.io/upstream-max-fails\"\n\tupsFailTimeout = \"ingress.kubernetes.io/upstream-fail-timeout\"\n)\n\n\n\ntype Upstream struct {\n\tMaxFails int `json:\"maxFails\"`\n\tFailTimeout int `json:\"failTimeout\"`\n}\n\ntype healthCheck struct {\n\tbackendResolver resolver.DefaultBackend\n}\n\n\n\n\n\n\nfunc (a healthCheck) Parse(ing *extensions.Ingress) (interface{}, error) {\n\tdefBackend := a.backendResolver.GetDefaultBackend()\n\tif ing.GetAnnotations() == nil {\n\t\treturn &Upstream{defBackend.UpstreamMaxFails, defBackend.UpstreamFailTimeout}, nil\n\t}\n\n\tmf, err := parser.GetIntAnnotation(upsMaxFails, ing)\n\tif err != nil {\n\t\tmf = defBackend.UpstreamMaxFails\n\t}\n\n\tft, err := parser.GetIntAnnotation(upsFailTimeout, ing)\n\tif err != nil {\n\t\tft = defBackend.UpstreamFailTimeout\n\t}\n\n\treturn &Upstream{mf, ft}, nil\n}\n\nfunc NewParser(br resolver.DefaultBackend) parser.IngressAnnotation ", "output": "{\n\treturn healthCheck{br}\n}"} {"input": "package lib\n\nimport (\n\t\"log\"\n\t\"strings\"\n)\n\ntype (\n\tQuestion struct {\n\t\tRelatesTo struct {\n\t\t\tAnswers []string `json:\"answers\"`\n\t\t\tSave bool `json:\"save\"`\n\t\t\tSaveTag string `json:\"saveTag\"`\n\t\t} `json:\"relatesTo\"`\n\t\tContext []string `json:\"context\"`\n\t\tQuestionText string `json:\"question\"`\n\t\tPossibleAnswers []string `json:\"answers\"`\n\t}\n\n\tQuestions []*Question\n)\n\nfunc (this Questions) First() *Question {\n\tif len(this) > 0 {\n\t\treturn this[0]\n\t}\n\treturn nil\n}\n\nfunc (this Questions) next(prevAnswer string) (*Question, bool) {\n\tfor i := range this {\n\t\tfor a := range this[i].RelatesTo.Answers {\n\t\t\tif strings.EqualFold(this[i].RelatesTo.Answers[a], prevAnswer) {\n\t\t\t\treturn this[i], this[i].RelatesTo.Save\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, false\n}\n\n\n\nfunc (this *Question) makeKeyboard() Keyboard {\n\tkeyboard := Keyboard{}\n\tfor i := range this.PossibleAnswers {\n\t\tkeyboard = append(keyboard, []string{this.PossibleAnswers[i]})\n\t}\n\treturn keyboard\n}\n\nfunc (this Questions) nextFrom(prevAnswers ...string) (*Question, bool) ", "output": "{\n\tfor i := range prevAnswers {\n\t\tif nxt, sv := this.next(prevAnswers[i]); nxt != nil {\n\t\t\tlog.Println(\"got it from sticker ...\")\n\t\t\treturn nxt, sv\n\t\t}\n\t}\n\treturn nil, false\n}"} {"input": "package model\n\ntype Interface interface {\n\tVisitString(name string, resume func())\n\tVisitInt(name string, resume func())\n\tVisitFloat(name string, resume func())\n\tVisitBool(name string, resume func())\n\tVisitPtr(name string, resume func())\n\tVisitBytes(name string, resume func())\n\tVisitSlice(name string, resume func())\n\tVisitStruct(name string, fields []Field, resume func())\n\tVisitStructField(field Field, resume func())\n\tVisitMap(name string, resume func())\n\tVisitCustom(name string, resume func())\n\tVisitReference(name string, resume func())\n}\n\ntype Visitor struct{}\n\nfunc (self *Visitor) VisitString(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitInt(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitFloat(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitBool(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitPtr(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitBytes(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitSlice(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitStruct(name string, fields []Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitStructField(field Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitMap(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitCustom(name string, resume func()) {\n\tresume()\n}\n\n\n\ntype EmbeddedStructVisitor struct {\n\tInterface\n}\n\nfunc (self *EmbeddedStructVisitor) VisitStruct(name string, fields []Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitReference(name string, resume func()) ", "output": "{\n\tresume()\n}"} {"input": "package main\n\nimport \"sync\"\nimport \"time\"\nimport \"fmt\"\n\ntype SyncMap struct {\n lock *sync.RWMutex\n hm map[int]string\n}\n\nfunc NewSyncMap() *SyncMap {\n return &SyncMap{lock: new(sync.RWMutex), hm: make(map[int]string)}\n}\n\n\n\nfunc main() {\n sm := NewSyncMap()\n for j:=0;j<5;j++ {\n sm.Put(j, \"no\")\n }\n time.Sleep(time.Second)\n sm2 := NewSyncMap()\n for i:=0;i<10;i++{\n go sm2.Put(i, \"go\")\n }\n time.Sleep(time.Second)\n fmt.Println(sm)\n fmt.Println(sm2)\n}\n\nfunc (m *SyncMap) Put (k int, v string) ", "output": "{\n m.lock.Lock()\n defer m.lock.Unlock()\n m.hm[k] = v\n}"} {"input": "package windows\n\nimport (\n\t\"github.com/docker/libnetwork/driverapi\"\n\t\"github.com/docker/libnetwork/types\"\n)\n\nconst networkType = \"windows\"\n\n\n\ntype driver struct{}\n\n\nfunc Init(dc driverapi.DriverCallback) error {\n\tc := driverapi.Capability{\n\t\tScope: driverapi.LocalScope,\n\t}\n\treturn dc.RegisterDriver(networkType, &driver{}, c)\n}\n\nfunc (d *driver) Config(option map[string]interface{}) error {\n\treturn nil\n}\n\nfunc (d *driver) CreateNetwork(id types.UUID, option map[string]interface{}) error {\n\treturn nil\n}\n\nfunc (d *driver) DeleteNetwork(nid types.UUID) error {\n\treturn nil\n}\n\n\n\nfunc (d *driver) DeleteEndpoint(nid, eid types.UUID) error {\n\treturn nil\n}\n\nfunc (d *driver) EndpointOperInfo(nid, eid types.UUID) (map[string]interface{}, error) {\n\treturn make(map[string]interface{}, 0), nil\n}\n\n\nfunc (d *driver) Join(nid, eid types.UUID, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {\n\treturn nil\n}\n\n\nfunc (d *driver) Leave(nid, eid types.UUID) error {\n\treturn nil\n}\n\nfunc (d *driver) Type() string {\n\treturn networkType\n}\n\nfunc (d *driver) CreateEndpoint(nid, eid types.UUID, epInfo driverapi.EndpointInfo, epOptions map[string]interface{}) error ", "output": "{\n\treturn nil\n}"} {"input": "package movavg_test\n\nimport (\n\t\"fmt\"\n\n\t. \"github.com/mxmCherry/movavg\"\n)\n\n\n\nfunc ExampleMulti() ", "output": "{\n\n\tmultiMA := MultiThreadSafe(\n\t\tMulti{\n\t\t\tNewSMA(2),\n\t\t\tNewSMA(3),\n\t\t\tNewSMA(4),\n\t\t},\n\t)\n\n\tfmt.Println(multiMA.Avg()) \n\n\tfmt.Println(multiMA.Add(2)) \n\tfmt.Println(multiMA.Avg()) \n\n\tfmt.Println(multiMA.Add(4)) \n\tfmt.Println(multiMA.Avg()) \n\n\tfmt.Println(multiMA.Add(6)) \n\tfmt.Println(multiMA.Avg()) \n\n\tfmt.Println(multiMA.Add(8)) \n\tfmt.Println(multiMA.Avg()) \n\n\tfmt.Println(multiMA.Add(10)) \n\tfmt.Println(multiMA.Avg()) \n\n}"} {"input": "package libvirtxml\n\ntype StorageVolumeTargetFormat struct {\n\tnode *Node\n}\n\nfunc newStorageVolumeTargetFormat(node *Node) StorageVolumeTargetFormat {\n\treturn StorageVolumeTargetFormat{\n\t\tnode: node,\n\t}\n}\n\n\n\nfunc (s StorageVolumeTargetFormat) SetType(value string) {\n\ts.node.setAttribute(nameForLocal(\"type\"), value)\n}\n\nfunc (s StorageVolumeTargetFormat) Type() string ", "output": "{\n\treturn s.node.getAttribute(nameForLocal(\"type\"))\n}"} {"input": "package arg2\n\nimport (\n\t\"encoding/binary\"\n\t\"io\"\n\n\t\"github.com/uber/tchannel-go/typed\"\n)\n\n\n\n\n\ntype KeyValIterator struct {\n\tremaining []byte\n\tleftPairCount int\n\tkey []byte\n\tval []byte\n}\n\n\n\n\nfunc NewKeyValIterator(arg2Payload []byte) (KeyValIterator, error) {\n\tif len(arg2Payload) < 2 {\n\t\treturn KeyValIterator{}, io.EOF\n\t}\n\n\tleftPairCount := binary.BigEndian.Uint16(arg2Payload[0:2])\n\treturn KeyValIterator{\n\t\tleftPairCount: int(leftPairCount),\n\t\tremaining: arg2Payload[2:],\n\t}.Next()\n}\n\n\n\n\n\nfunc (i KeyValIterator) Value() []byte {\n\treturn i.val\n}\n\n\nfunc (i KeyValIterator) Remaining() bool {\n\treturn i.leftPairCount > 0\n}\n\n\n\n\n\n\nfunc (i KeyValIterator) Next() (kv KeyValIterator, _ error) {\n\tif i.leftPairCount <= 0 {\n\t\treturn KeyValIterator{}, io.EOF\n\t}\n\n\trbuf := typed.NewReadBuffer(i.remaining)\n\tkeyLen := int(rbuf.ReadUint16())\n\tkey := rbuf.ReadBytes(keyLen)\n\tvalLen := int(rbuf.ReadUint16())\n\tval := rbuf.ReadBytes(valLen)\n\tif rbuf.Err() != nil {\n\t\treturn KeyValIterator{}, rbuf.Err()\n\t}\n\n\tleftPairCount := i.leftPairCount - 1\n\n\tkv = KeyValIterator{\n\t\tremaining: rbuf.Remaining(),\n\t\tleftPairCount: leftPairCount,\n\t\tkey: key,\n\t\tval: val,\n\t}\n\treturn kv, nil\n}\n\nfunc (i KeyValIterator) Key() []byte ", "output": "{\n\treturn i.key\n}"} {"input": "package closer\n\nimport (\n\t\"sync\"\n)\n\ntype Closer struct {\n\tIsClosedChan chan struct{}\n\n\tf func()\n\tmutex sync.Mutex\n}\n\n\n\nfunc New(f func()) *Closer {\n\treturn &Closer{\n\t\tIsClosedChan: make(chan struct{}),\n\t\tf: f,\n\t}\n}\n\n\nfunc (c *Closer) Close() {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\n\tif c.IsClosed() {\n\t\treturn\n\t}\n\n\tclose(c.IsClosedChan)\n\n\tc.f()\n}\n\n\n\n\nfunc (c *Closer) IsClosed() bool ", "output": "{\n\tselect {\n\tcase <-c.IsClosedChan:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/matcornic/subify/common/config\"\n\tlogger \"github.com/spf13/jwalterweatherman\"\n)\n\n\n\n\n\nfunc Exit(format string, args ...interface{}) {\n\tExitVerbose(\"\", format, args...)\n}\n\n\n\nfunc ExitPrintError(err error, format string, args ...interface{}) {\n\tExitVerbose(fmt.Sprint(err), format, args...)\n}\n\n\n\nfunc ExitVerbose(verboseLog string, format string, args ...interface{}) {\n\tlogger.ERROR.Println(verboseLog)\n\tif !config.Verbose {\n\t\tlogger.ERROR.Println(\"Run subify with --verbose option to get more information about the error\")\n\t}\n\tlogger.FATAL.Printf(format)\n\tos.Exit(-1)\n}\n\nfunc VerbosePrintln(logger *log.Logger, log string) ", "output": "{\n\tif config.Verbose && log != \"\" {\n\t\tlogger.Println(log)\n\t}\n}"} {"input": "package machinelearning\n\nimport (\n\t\"net/url\"\n\n\t\"github.com/gunosy/aws-sdk-go/aws\"\n)\n\nfunc init() {\n\tinitRequest = func(r *aws.Request) {\n\t\tswitch r.Operation.Name {\n\t\tcase opPredict:\n\t\t\tr.Handlers.Build.PushBack(updatePredictEndpoint)\n\t\t}\n\t}\n}\n\n\n\n\n\nfunc updatePredictEndpoint(r *aws.Request) ", "output": "{\n\tif !r.ParamsFilled() {\n\t\treturn\n\t}\n\n\tr.Endpoint = *r.Params.(*PredictInput).PredictEndpoint\n\n\turi, err := url.Parse(r.Endpoint)\n\tif err != nil {\n\t\tr.Error = err\n\t\treturn\n\t}\n\tr.HTTPRequest.URL = uri\n}"} {"input": "package gogs\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\n\n\nfunc (c *Client) AdminCreateTeam(user string, opt CreateTeamOption) (*Team, error) {\n\tbody, err := json.Marshal(&opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tteam := new(Team)\n\treturn team, c.getParsedResponse(\"POST\", fmt.Sprintf(\"/admin/orgs/%s/teams\", user),\n\t\tjsonHeader, bytes.NewReader(body), team)\n}\n\nfunc (c *Client) AdminAddTeamMembership(teamID int64, user string) error {\n\t_, err := c.getResponse(\"PUT\", fmt.Sprintf(\"/admin/teams/%d/members/%s\", teamID, user),\n\t\tjsonHeader, nil)\n\treturn err\n}\n\nfunc (c *Client) AdminAddTeamRepository(teamID int64, repo string) error {\n\t_, err := c.getResponse(\"PUT\", fmt.Sprintf(\"/admin/teams/%d/repos/%s\", teamID, repo),\n\t\tjsonHeader, nil)\n\treturn err\n}\n\nfunc (c *Client) AdminCreateOrg(user string, opt CreateOrgOption) (*Organization, error) ", "output": "{\n\tbody, err := json.Marshal(&opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\torg := new(Organization)\n\treturn org, c.getParsedResponse(\"POST\", fmt.Sprintf(\"/admin/users/%s/orgs\", user),\n\t\tjsonHeader, bytes.NewReader(body), org)\n}"} {"input": "package utils\n\nimport (\n\t\"sync\"\n)\n\ntype BeeMap struct {\n\tlock *sync.RWMutex\n\tbm map[interface{}]interface{}\n}\n\n\nfunc NewBeeMap() *BeeMap {\n\treturn &BeeMap{\n\t\tlock: new(sync.RWMutex),\n\t\tbm: make(map[interface{}]interface{}),\n\t}\n}\n\n\nfunc (m *BeeMap) Get(k interface{}) interface{} {\n\tm.lock.RLock()\n\tdefer m.lock.RUnlock()\n\tif val, ok := m.bm[k]; ok {\n\t\treturn val\n\t}\n\treturn nil\n}\n\n\n\nfunc (m *BeeMap) Set(k interface{}, v interface{}) bool {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\tif val, ok := m.bm[k]; !ok {\n\t\tm.bm[k] = v\n\t} else if val != v {\n\t\tm.bm[k] = v\n\t} else {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\nfunc (m *BeeMap) Check(k interface{}) bool {\n\tm.lock.RLock()\n\tdefer m.lock.RUnlock()\n\tif _, ok := m.bm[k]; !ok {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\nfunc (m *BeeMap) Delete(k interface{}) {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\tdelete(m.bm, k)\n}\n\n\n\n\nfunc (m *BeeMap) Items() map[interface{}]interface{} ", "output": "{\n\tm.lock.RLock()\n\tdefer m.lock.RUnlock()\n\treturn m.bm\n}"} {"input": "package db\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/golang/glog\"\n\t\"github.com/hobeone/tv2go/naming\"\n)\n\n\ntype NameException struct {\n\tID int64\n\tSource string\n\tIndexer string\n\tIndexerID int64\n\tName string\n\tSeason int64\n\tCreatedAt time.Time\n\tUpdatedAt time.Time\n}\n\n\nfunc (e *NameException) BeforeSave() error {\n\tif e.Indexer == \"\" {\n\t\treturn fmt.Errorf(\"NameException Indexer can't be blank\")\n\t}\n\tif e.Source == \"\" {\n\t\treturn fmt.Errorf(\"NameException Source can't be blank\")\n\t}\n\tif e.IndexerID == 0 {\n\t\treturn fmt.Errorf(\"NameException IndexerID can't be blank\")\n\t}\n\tif e.Name == \"\" {\n\t\treturn fmt.Errorf(\"NameException Name can't be blank\")\n\t}\n\treturn nil\n}\n\n\n\n\n\n\n\n\nfunc (h *Handle) SaveNameExceptions(source string, excepts []*NameException) error {\n\tif h.writeUpdates {\n\t\ttx := h.db.Begin()\n\t\terr := tx.Where(\"source = ?\", source).Delete(NameException{}).Error\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Couldn't delete old name exceptions for %s: %s\", source, err)\n\t\t\ttx.Rollback()\n\t\t\treturn err\n\t\t}\n\t\tfor _, e := range excepts {\n\t\t\terr := tx.Save(e).Error\n\t\t\tif err != nil {\n\t\t\t\tglog.Errorf(\"Error saving exceptions to the database: %s\", err.Error())\n\t\t\t\ttx.Rollback()\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\ttx.Commit()\n\t}\n\treturn nil\n}\n\nfunc (h *Handle) GetShowFromNameException(name string) (*Show, int64, error) ", "output": "{\n\tne := &[]NameException{}\n\terr := h.db.Where(\"name = ? COLLATE NOCASE\", name).Find(ne).Error\n\tif err != nil {\n\t\tne = &[]NameException{}\n\t\tsceneName := naming.FullSanitizeSceneName(name)\n\t\tglog.Infof(\"searching for name '%s' with scene name '%s'\", name, sceneName)\n\n\t\terr = h.db.Where(\"name = ? COLLATE NOCASE\", name).Find(ne).Error\n\t\tif err != nil {\n\t\t\treturn nil, -1, err\n\t\t}\n\t}\n\tfor _, exp := range *ne {\n\t\tshow, err := h.GetShowByIndexerAndID(exp.Indexer, exp.IndexerID)\n\t\tif err == nil {\n\t\t\treturn show, exp.Season, nil\n\t\t}\n\t}\n\treturn nil, -1, fmt.Errorf(\"Couldn't find matching show for %s\", name)\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/bitly/go-nsq\"\n)\n\n\n\ntype BackendQueue interface {\n\tPut([]byte) error\n\tReadChan() chan []byte \n\tClose() error\n\tDelete() error\n\tDepth() int64\n\tEmpty() error\n}\n\ntype DummyBackendQueue struct {\n\treadChan chan []byte\n}\n\nfunc NewDummyBackendQueue() BackendQueue {\n\treturn &DummyBackendQueue{readChan: make(chan []byte)}\n}\n\nfunc (d *DummyBackendQueue) Put([]byte) error {\n\treturn nil\n}\n\nfunc (d *DummyBackendQueue) ReadChan() chan []byte {\n\treturn d.readChan\n}\n\nfunc (d *DummyBackendQueue) Close() error {\n\treturn nil\n}\n\n\n\nfunc (d *DummyBackendQueue) Depth() int64 {\n\treturn int64(0)\n}\n\nfunc (d *DummyBackendQueue) Empty() error {\n\treturn nil\n}\n\nfunc WriteMessageToBackend(buf *bytes.Buffer, msg *nsq.Message, bq BackendQueue) error {\n\tbuf.Reset()\n\terr := msg.Write(buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = bq.Put(buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (d *DummyBackendQueue) Delete() error ", "output": "{\n\treturn nil\n}"} {"input": "package sweet\n\nimport (\n\t\"fmt\"\n\t\"github.com/mgutz/ansi\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\n\nfunc (Opts *SweetOptions) LogFatal(message string) {\n\tif Opts.UseSyslog {\n\t\tOpts.Syslog.Emerg(message)\n\t} else {\n\t\tlog.Println(ansi.Color(message, \"red+b:white\"))\n\t}\n\tos.Exit(1)\n}\nfunc (Opts *SweetOptions) LogErr(message string) {\n\tif Opts.UseSyslog {\n\t\tOpts.Syslog.Err(message)\n\t} else {\n\t\tlog.Println(ansi.Color(message, \"red+b\"))\n\t}\n}\nfunc (Opts *SweetOptions) LogInfo(message string) {\n\tif Opts.UseSyslog {\n\t\tOpts.Syslog.Info(message)\n\t} else {\n\t\tlog.Println(ansi.Color(message, \"green+b\"))\n\t}\n}\nfunc (Opts *SweetOptions) LogChanges(message string) {\n\tif Opts.UseSyslog {\n\t\tOpts.Syslog.Info(message)\n\t} else {\n\t\tlog.Println(ansi.Color(message, \"blue+b\"))\n\t}\n}\n\n\n\n\nfunc cleanName(n string) string {\n\tc := strings.ToLower(n)\n\tif len(c) > 255 {\n\t\tc = c[:255]\n\t}\n\tc = strings.ToLower(c)\n\tc = strings.Replace(c, \"/\", \"-\", -1)\n\tc = strings.Replace(c, \" \", \"-\", -1)\n\tc = strings.Replace(c, \":\", \"-\", -1)\n\treturn c\n}\n\nfunc timeAgo(oldTime time.Time) string ", "output": "{\n\tvar str string\n\tduration := time.Since(oldTime)\n\tseconds := int64(duration.Seconds())\n\tif seconds <= 0 {\n\t\tstr = \"Now\"\n\t} else if seconds < 60 {\n\t\tstr = fmt.Sprintf(\"%d seconds\", seconds)\n\t} else if seconds < 120 {\n\t\tstr = \"1 minute\"\n\t} else if seconds < 3600 {\n\t\tstr = fmt.Sprintf(\"%d minutes\", seconds/60)\n\t} else if seconds < 7200 {\n\t\tstr = \"1 hour\"\n\t} else if seconds < 86400 {\n\t\tstr = fmt.Sprintf(\"%d hours\", seconds/(60*60))\n\t} else if seconds < 86400*2 {\n\t\tstr = \"1 day\"\n\t} else {\n\t\tstr = fmt.Sprintf(\"%d days\", seconds/(60*60*24))\n\t}\n\treturn str\n}"} {"input": "package receiver\n\nimport (\n\t\"os\"\n\t\"io\"\n)\n\ntype Stream struct {\n\tstream io.WriteCloser\n}\n\n\n\nfunc (this *Stream) Write(data []byte, n *int) (err error) {\n\t*n, err = this.stream.Write(data)\n\treturn err\n}\n\nfunc (this *Stream) Close(dummy int, nothing *int) error {\n\terr := this.stream.Close()\n\treturn err\n}\n\nfunc NewStream(filePath string) (*Stream, error) ", "output": "{\n\tvar err error\n\tvar stream Stream\n\tstream.stream, err = os.Create(filePath)\n\treturn &stream, err\n}"} {"input": "package v20170701\n\nimport (\n\t\"encoding/json\"\n\t\"testing\"\n)\n\nfunc TestMasterProfile(t *testing.T) {\n\tMasterProfileText := \"{\\\"count\\\" : 0}\"\n\tmp := &MasterProfile{}\n\tif e := json.Unmarshal([]byte(MasterProfileText), mp); e != nil {\n\t\tt.Fatalf(\"unexpectedly detected unmarshal failure for MasterProfile, %+v\", e)\n\t}\n\n\tif mp.Count != 1 {\n\t\tt.Fatalf(\"unexpectedly detected MasterProfile.Count != 1 after unmarshal\")\n\t}\n\n\tif mp.FirstConsecutiveStaticIP != \"10.240.255.5\" {\n\t\tt.Fatalf(\"unexpectedly detected MasterProfile.FirstConsecutiveStaticIP != 10.240.255.5 after unmarshal\")\n\t}\n}\n\n\n\nfunc TestAgentPoolProfile(t *testing.T) ", "output": "{\n\tAgentPoolProfileText := \"{\\\"count\\\" : 0}\"\n\tap := &AgentPoolProfile{}\n\tif e := json.Unmarshal([]byte(AgentPoolProfileText), ap); e != nil {\n\t\tt.Fatalf(\"unexpectedly detected unmarshal failure for AgentPoolProfile, %+v\", e)\n\t}\n\n\tif ap.Count != 1 {\n\t\tt.Fatalf(\"unexpectedly detected AgentPoolProfile.Count != 1 after unmarshal\")\n\t}\n\n\tif ap.OSType != Linux {\n\t\tt.Fatalf(\"unexpectedly detected AgentPoolProfile.OSType != Linux after unmarshal\")\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/adampresley/golang-webapp-starter-kit/services/listener\"\n\t\"github.com/adampresley/golang-webapp-starter-kit/services/middleware\"\n)\n\n\n\nfunc setupMiddleware(httpListener *listener.HTTPListenerService, appContext *middleware.AppContext) ", "output": "{\n\thttpListener.\n\t\tAddMiddleware(appContext.Logger).\n\t\tAddMiddleware(appContext.StartAppContext).\n\t\tAddMiddleware(appContext.AccessControl).\n\t\tAddMiddleware(appContext.OptionsHandler)\n}"} {"input": "package permissions\n\nimport (\n\t\"path/filepath\"\n\t\"util\"\n)\n\n\nvar globalPermissions *PermissionsLoader\n\n\nfunc Get() *Permissions {\n\tif globalPermissions == nil {\n\t\treturn &Default\n\t}\n\treturn globalPermissions.Get()\n}\n\n\nfunc SetPath(permissions string) error {\n\tif permissions != \"default\" {\n\t\tpl, err := NewPermissionsLoader(permissions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif globalPermissions != nil {\n\t\t\tglobalPermissions.Close()\n\t\t}\n\t\tglobalPermissions = pl\n\t\tif !pl.Get().Watch {\n\t\t\tglobalPermissions.Close() \n\t\t}\n\n\t} else {\n\t\tif globalPermissions != nil {\n\t\t\tglobalPermissions.Close()\n\t\t}\n\t\tglobalPermissions = nil\n\t}\n\treturn nil\n}\n\n\ntype PermissionsLoader struct {\n\tPermissions *Permissions \n\tWatcher *util.FileWatcher \n}\n\n\n\n\n\n\nfunc NewPermissionsLoader(filename string) (*PermissionsLoader, error) {\n\tfilename, err := filepath.Abs(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp, err := Load(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpl := &PermissionsLoader{\n\t\tPermissions: p,\n\t}\n\tpl.Watcher, err = util.NewFileWatcher(filename, pl)\n\treturn pl, err\n}\n\n\nfunc (pl *PermissionsLoader) Reload() error {\n\tp, err := Load(pl.Watcher.FileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpl.Watcher.Lock()\n\tpl.Permissions = p\n\tpl.Watcher.Unlock()\n\n\tif !p.Watch {\n\t\tpl.Close() \n\t}\n\n\treturn nil\n}\n\n\nfunc (pl *PermissionsLoader) Close() {\n\tpl.Watcher.Close()\n}\n\nfunc (pl *PermissionsLoader) Get() *Permissions ", "output": "{\n\tif pl == nil {\n\t\treturn &Default\n\t}\n\n\tpl.Watcher.RLock()\n\tdefer pl.Watcher.RUnlock()\n\treturn pl.Permissions\n}"} {"input": "package transform\n\nimport (\n\t\"bytes\"\n\t\"regexp\"\n\t\"strings\"\n)\n\ntype CSSTransform struct {\n\turl_exp *regexp.Regexp\n\timp_exp *regexp.Regexp\n\n\tlink_trans *Transform\n}\n\nfunc (t *CSSTransform) Init(trans *Transform) error {\n\tvar err error\n\tt.url_exp, err = regexp.Compile(\"url\\\\(([\\\"][^\\\"]*[\\\"]|['][^']*[']|[^)]*)\\\\)\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.imp_exp, err = regexp.Compile(\"@import \\\"(.*?)\\\"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tt.link_trans = trans\n\treturn nil\n}\n\n\n\nfunc (t *CSSTransform) Process(base_url string, text []byte) ([]byte, error) ", "output": "{\n\tres := t.url_exp.ReplaceAllFunc(text, func(link []byte) []byte {\n\t\tlength := len(link)\n\t\tif length == 0 {\n\t\t\treturn []byte(\"\")\n\t\t}\n\n\t\tvar ll string\n\t\tif bytes.HasPrefix(link, []byte(\"url(\")) && link[length-1] == ')' {\n\t\t\tll = t.link_trans.ProcessLink(base_url, string(link[len(\"url(\"):length-1]))\n\t\t\treturn []byte(strings.Join([]string{\"url(\", ll, \")\"}, \"\"))\n\t\t}\n\n\t\tll = t.link_trans.ProcessLink(base_url, string(link))\n\t\treturn []byte(ll)\n\t})\n\treturn res, nil\n}"} {"input": "package internal\n\nimport (\n\t. \"github.com/signal18/replication-manager/goofys/api/common\"\n\t. \"gopkg.in/check.v1\"\n\n\t\"github.com/jacobsa/fuse\"\n)\n\ntype AwsTest struct {\n\ts3 *S3Backend\n}\n\nvar _ = Suite(&AwsTest{})\n\n\n\nfunc (s *AwsTest) TestRegionDetection(t *C) {\n\ts.s3.bucket = \"goofys-eu-west-1.signal18/replication-manager.xyz\"\n\n\terr, isAws := s.s3.detectBucketLocationByHEAD()\n\tt.Assert(err, IsNil)\n\tt.Assert(*s.s3.awsConfig.Region, Equals, \"eu-west-1\")\n\tt.Assert(isAws, Equals, true)\n}\n\nfunc (s *AwsTest) TestBucket404(t *C) {\n\ts.s3.bucket = RandStringBytesMaskImprSrc(64)\n\n\terr, isAws := s.s3.detectBucketLocationByHEAD()\n\tt.Assert(err, Equals, fuse.ENOENT)\n\tt.Assert(isAws, Equals, true)\n}\n\nfunc (s *AwsTest) SetUpSuite(t *C) ", "output": "{\n\tvar err error\n\ts.s3, err = NewS3(\"\", &FlagStorage{}, &S3Config{\n\t\tRegion: \"us-east-1\",\n\t})\n\tt.Assert(err, IsNil)\n}"} {"input": "package mastodon\n\nimport (\n\t\"context\"\n\t\"net/http\"\n)\n\n\ntype Instance struct {\n\tURI string `json:\"uri\"`\n\tTitle string `json:\"title\"`\n\tDescription string `json:\"description\"`\n\tEMail string `json:\"email\"`\n\tVersion string `json:\"version,omitempty\"`\n\tURLs map[string]string `json:\"urls,omitempty\"`\n\tStats *InstanceStats `json:\"stats,omitempty\"`\n\tThumbnail string `json:\"thumbnail,omitempty\"`\n}\n\n\ntype InstanceStats struct {\n\tUserCount int64 `json:\"user_count\"`\n\tStatusCount int64 `json:\"status_count\"`\n\tDomainCount int64 `json:\"domain_count\"`\n}\n\n\n\n\n\ntype WeeklyActivity struct {\n\tWeek Unixtime `json:\"week\"`\n\tStatuses int64 `json:\"statuses,string\"`\n\tLogins int64 `json:\"logins,string\"`\n\tRegistrations int64 `json:\"registrations,string\"`\n}\n\n\nfunc (c *Client) GetInstanceActivity(ctx context.Context) ([]*WeeklyActivity, error) {\n\tvar activity []*WeeklyActivity\n\terr := c.doAPI(ctx, http.MethodGet, \"/api/v1/instance/activity\", nil, &activity, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn activity, nil\n}\n\n\nfunc (c *Client) GetInstancePeers(ctx context.Context) ([]string, error) {\n\tvar peers []string\n\terr := c.doAPI(ctx, http.MethodGet, \"/api/v1/instance/peers\", nil, &peers, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn peers, nil\n}\n\nfunc (c *Client) GetInstance(ctx context.Context) (*Instance, error) ", "output": "{\n\tvar instance Instance\n\terr := c.doAPI(ctx, http.MethodGet, \"/api/v1/instance\", nil, &instance, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &instance, nil\n}"} {"input": "package kegg\n\nimport (\n\t\"fmt\"\n)\n\nfunc ExampleConvert() {\n\tdrugID, err := New().Convert(\"pubchem\", \"drug\", \"313046637\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Println(drugID)\n}\n\nfunc ExampleGet() {\n\tinfo, err := New().Get(\"drug\", \"D00341\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Println(info != \"\")\n}\n\nfunc ExampleFind() {\n\tmatch, err := New().Find(\"drug\", \"D00341\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Println(match != \"\")\n}\n\n\n\nfunc ExampleLink() ", "output": "{\n\tcompoundID, err := New().Link(\"drug\", \"compound\", \"D00341\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Println(compoundID)\n}"} {"input": "package models\n\nimport (\n\t\"time\"\n\n\t\"github.com/toolkits/logger\"\n\n\t\"github.com/coraldane/ops-meta/db\"\n)\n\ntype RelAgentGroup struct {\n\tId int64\n\tGmtCreate time.Time `orm:\"auto_now_add;type(datetime)\"`\n\tGmtModified time.Time `orm:\"auto_now_add;type(datetime)\"`\n\tAgentId int64 `form:\"agentId\"`\n\tHostGroupId int64 `form:\"hostGroupId\"`\n}\n\nfunc (this *RelAgentGroup) TableUnique() [][]string {\n\treturn [][]string{\n\t\t[]string{\"AgentId\", \"HostGroupId\"},\n\t}\n}\n\nfunc (this *RelAgentGroup) Insert() (int64, error) {\n\tthis.GmtModified = time.Now()\n\n\tif 0 < this.Id {\n\t\treturn db.NewOrm().Update(this)\n\t} else {\n\t\tthis.GmtCreate = time.Now()\n\t\treturn db.NewOrm().Insert(this)\n\t}\n}\n\nfunc (this *RelAgentGroup) DeleteByPK() (int64, error) {\n\tresult, err := this.DeleteByCond()\n\treturn result, err\n}\n\nfunc (this *RelAgentGroup) DeleteByCond() (int64, error) {\n\tquery := db.NewOrm().QueryTable(RelAgentGroup{})\n\tif 0 < this.Id {\n\t\tquery = query.Filter(\"Id\", this.Id)\n\t}\n\tif 0 < this.HostGroupId {\n\t\tquery = query.Filter(\"HostGroupId\", this.HostGroupId)\n\t}\n\tif 0 < this.AgentId {\n\t\tquery = query.Filter(\"AgentId\", this.AgentId)\n\t}\n\treturn query.Delete()\n}\n\n\n\nfunc QueryRelAgentGroupList(agentId int64) ([]RelAgentGroupDto, error) ", "output": "{\n\tvar rows []RelAgentGroupDto\n\t_, err := db.NewOrm().Raw(\"select t.id, t.gmt_create,t.gmt_modified, t.host_group_id, a.group_name from t_rel_agent_group t, t_host_group a where t.agent_id=? and t.host_group_id=a.id\", agentId).QueryRows(&rows)\n\tif nil != err {\n\t\tlogger.Errorln(\"QueryRelAgentGroupList error\", err)\n\t}\n\treturn rows, err\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/crackcell/asciitype/engine\"\n\t\"os\"\n\t\"strings\"\n)\n\n\n\nfunc readStdin() {\n\treader := bufio.NewReader(os.Stdin)\n\tfor {\n\t\tline, err := reader.ReadString('\\n')\n\t\tline = strings.Trim(line, \"\\n\")\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc convert(raw string, fb *engine.Framebuffer, st *engine.SymbolTable) {\n\tfb.Clear()\n\traw = strings.ToUpper(raw)\n\tfor _, r := range raw {\n\t\tfb.Append(st.GetSymbol(r))\n\t}\n\n\tfb.Flush(os.Stdout)\n}\n\nfunc main() {\n\th := flag.Bool(\"h\", false, \"show help messages\")\n\tf := flag.String(\"f\", \"./fonts/tukasans.afont\", \"specify font file\")\n\tflag.Parse()\n\tif *h {\n\t\tshowHelp()\n\t\treturn\n\t}\n\n\tst := new(engine.SymbolTable)\n\tst.Load(*f)\n\n\tfb := engine.NewFramebuffer()\n\n\treader := bufio.NewReader(os.Stdin)\n\n\tfor {\n\t\tline, err := reader.ReadString('\\n')\n\t\tline = strings.Trim(line, \"\\n\")\n\t\tif len(line) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tconvert(line, fb, st)\n\t}\n\n}\n\nfunc showHelp() ", "output": "{\n\tfmt.Println(\"usage: asciifont -f [font file]\")\n}"} {"input": "package apis\n\nimport (\n\t\"bytes\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/Sirupsen/logrus\"\n\t\"github.com/go-ozzo/ozzo-routing\"\n\t\"github.com/go-ozzo/ozzo-routing/content\"\n\t\"github.com/Zhanat87/go/app\"\n\t\"github.com/Zhanat87/go/testdata\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype apiTestCase struct {\n\ttag string\n\tmethod string\n\turl string\n\tbody string\n\tstatus int\n\tresponse string\n}\n\nvar router *routing.Router\n\nfunc init() {\n\tlogger := logrus.New()\n\tlogger.Level = logrus.PanicLevel\n\n\trouter = routing.New()\n\n\trouter.Use(\n\t\tapp.Init(logger),\n\t\tcontent.TypeNegotiator(content.JSON),\n\t\tapp.Transactional(testdata.DB),\n\t)\n}\n\n\n\nfunc runAPITests(t *testing.T, tests []apiTestCase) {\n\tfor _, test := range tests {\n\t\tres := testAPI(test.method, test.url, test.body)\n\t\tassert.Equal(t, test.status, res.Code, test.tag + \", \" + res.Body.String())\n\t\tif test.response != \"\" {\n\t\t\tassert.JSONEq(t, test.response, res.Body.String(), test.tag)\n\t\t}\n\t}\n}\n\nfunc testAPI(method, URL, body string) *httptest.ResponseRecorder ", "output": "{\n\treq, _ := http.NewRequest(method, URL, bytes.NewBufferString(body))\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tres := httptest.NewRecorder()\n\trouter.ServeHTTP(res, req)\n\treturn res\n}"} {"input": "package log\n\n\ntype Key string\n\n\n\n\nvar (\n\tErr = Key(\"err\")\n\tMsg = Key(\"msg\")\n)\n\nfunc (k Key) String() string ", "output": "{\n\treturn string(k)\n}"} {"input": "package main \n \nimport( \n \"fmt\"\n \"strings\"\n) \n \n\n \n \nfunc main() { \n \n \n fmt.Println(joinstr()) \n \n \n fmt.Println(joinstr(\"GEEK\", \"GFG\")) \n fmt.Println(joinstr(\"Geeks\", \"for\", \"Geeks\")) \n fmt.Println(joinstr(\"G\", \"E\", \"E\", \"k\", \"S\")) \n \n}\n\nfunc joinstr(element...string)string", "output": "{ \n return strings.Join(element, \"-\") \n}"} {"input": "package ca_test\n\nimport (\n\t\"crypto/tls\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com/neptulon/ca\"\n)\n\n\n\n\nfunc Example() ", "output": "{\n\tcertChain, certErr := ca.GenCertChain(\"FooBar\", \"127.0.0.1\", \"127.0.0.1\", time.Hour, 512)\n\tif certErr != nil {\n\t\tlog.Fatal(certErr)\n\t}\n\n\t _, tlsErr := tls.Listen(\"tcp\", \"127.0.0.1:4444\", certChain.ServerTLSConf)\n\tif tlsErr != nil {\n\t\tlog.Fatal(tlsErr)\n\t}\n\n}"} {"input": "package user\n\nfunc New(id int, username, password, firstname, lastname, role string) User {\n\treturn User{id, username, password, firstname, lastname, role}\n}\n\n\ntype User struct {\n\tid int\n\tusername string\n\tpassword string\n\tfirstname string\n\tlastname string\n\trole string\n}\n\nfunc (u User) Id() int {\n\treturn u.id\n}\n\n\n\nfunc (u User) Password() string {\n\treturn u.password\n}\n\nfunc (u User) Firstname() string {\n\treturn u.firstname\n}\n\nfunc (u User) Lastname() string {\n\treturn u.lastname\n}\n\nfunc (u User) Role() string {\n\treturn u.role\n}\n\nfunc (u User) Username() string ", "output": "{\n\treturn u.username\n}"} {"input": "package cmd\n\nimport (\n\t\"errors\"\n\t\"os\"\n\n\t\"github.com/codegangsta/cli\"\n\n\t\"github.com/DevMine/srctool/config\"\n\t\"github.com/DevMine/srctool/log\"\n)\n\n\nfunc Delete(c *cli.Context) {\n\tif !c.Args().Present() {\n\t\tdeleteAll(c.Bool(\"dry\"))\n\t} else {\n\t\tif err := deleteParser(genParserName(c.Args().First()), c.Bool(\"dry\"), true); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n}\n\nfunc deleteAll(dryMode bool) {\n\tparsers := getInstalledParsers()\n\tfor _, parser := range parsers {\n\t\tif err := deleteParser(genParserName(parser), dryMode, true); err != nil {\n\t\t\tlog.Fail(err)\n\t\t}\n\t}\n}\n\n\n\nfunc deleteParser(parserName string, dryMode bool, verbose bool) error ", "output": "{\n\tparserPath := config.ParserPath(parserName)\n\n\tif _, err := os.Stat(parserPath); os.IsNotExist(err) {\n\t\tlog.Debug(err)\n\t\treturn errors.New(parserName + \" is not installed\")\n\t}\n\n\tif dryMode {\n\t\tlog.Info(\"parser path:\", parserPath)\n\t\treturn nil\n\t}\n\n\tlog.Debug(\"removing \", parserPath)\n\tif err := os.RemoveAll(parserPath); err != nil {\n\t\tlog.Debug(err)\n\t\treturn errors.New(\"failed to remove \" + parserName)\n\t}\n\n\tif verbose {\n\t\tlog.Success(parserName, \" successfully removed\")\n\t}\n\treturn nil\n}"} {"input": "package proxy\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com/AaronO/gogo-proxy\"\n)\n\nfunc TestRoundrobinEmpty(t *testing.T) {\n\tbalancer := proxy.Roundrobin()\n\n\tif _, err := balancer(nil); err == nil {\n\t\tt.Fatalf(\"Roundrobin should fail when given no hosts\")\n\t}\n}\n\nfunc TestRandomEmpty(t *testing.T) {\n\tbalancer := proxy.Random()\n\n\tif _, err := balancer(nil); err == nil {\n\t\tt.Fatalf(\"Random should fail when given no hosts\")\n\t}\n}\n\n\n\nfunc TestRoundrobin(t *testing.T) ", "output": "{\n\tbalancer := proxy.Roundrobin(\"1\", \"2\", \"3\")\n\n\thosts := []string{}\n\n\tfor i := 0; i < 7; i++ {\n\t\thost, err := balancer(nil)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\thosts = append(hosts, host)\n\t}\n\n\tequal := reflect.DeepEqual(\n\t\thosts,\n\t\t[]string{\"1\", \"2\", \"3\", \"1\", \"2\", \"3\", \"1\"},\n\t)\n\n\tif !equal {\n\t\tt.Fatalf(\"Roundrobin did not generate expected hosts\")\n\t}\n}"} {"input": "package debug\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\n\n\nfunc BenchmarkNoLogging(b *testing.B) {\n\tos.Unsetenv(\"GOPASS_DEBUG\")\n\tinitDebug()\n\n\tfor i := 0; i < b.N; i++ {\n\t\tLog(\"string\")\n\t}\n}\n\nfunc BenchmarkLogging(b *testing.B) ", "output": "{\n\tos.Setenv(\"GOPASS_DEBUG\", \"true\")\n\tdefer func() { os.Unsetenv(\"GOPASS_DEBUG\") }()\n\tinitDebug()\n\n\tfor i := 0; i < b.N; i++ {\n\t\tLog(\"string\")\n\t}\n}"} {"input": "package plan9\n\nimport \"syscall\"\n\n\n\nfunc Getwd() (wd string, err error) {\n\treturn syscall.Getwd()\n}\n\nfunc Chdir(path string) error {\n\treturn syscall.Chdir(path)\n}\n\nfunc fixwd() ", "output": "{\n\tsyscall.Fixwd()\n}"} {"input": "package client\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/cihub/seelog\"\n)\n\n\nconst Succeed = \"\\u2713\"\n\n\nconst Failed = \"\\u2717\"\n\nfunc init() {\n\tseelogConfig := \"conf/seelog.xml.test\"\n\tlogger, err := seelog.LoggerFromConfigAsFile(seelogConfig)\n\tif err != nil {\n\t\terr := fmt.Errorf(\"FOO Error creating Logger from seelog file: %s\", seelogConfig)\n\t\tseelog.Error(err)\n\t}\n\tdefer seelog.Flush()\n\tseelog.ReplaceLogger(logger)\n}\n\n\n\n\n\nfunc Fatal(t *testing.T, msg string, args ...interface{}) {\n\tm := fmt.Sprintf(msg, args...)\n\tt.Fatal(fmt.Sprintf(\"\\t %-80s\", m), Failed)\n}\n\n\nfunc Error(t *testing.T, msg string, args ...interface{}) {\n\tm := fmt.Sprintf(msg, args...)\n\tt.Error(fmt.Sprintf(\"\\t %-80s\", m), Failed)\n}\n\n\nfunc Success(t *testing.T, msg string, args ...interface{}) {\n\tm := fmt.Sprintf(msg, args...)\n\tt.Log(fmt.Sprintf(\"\\t %-80s\", m), Succeed)\n}\n\nfunc Context(t *testing.T, msg string, args ...interface{}) ", "output": "{\n\tt.Log(fmt.Sprintf(msg, args...))\n}"} {"input": "package builders\n\nimport (\n\t\"time\"\n\n\t\"github.com/docker/docker/api/types\"\n)\n\n\n\nfunc Container(name string, builders ...func(container *types.Container)) *types.Container {\n\tcontainer := &types.Container{\n\t\tID: \"container_id\",\n\t\tNames: []string{\"/\" + name},\n\t\tCommand: \"top\",\n\t\tImage: \"busybox:latest\",\n\t\tStatus: \"Up 1 second\",\n\t\tCreated: time.Now().Unix(),\n\t}\n\n\tfor _, builder := range builders {\n\t\tbuilder(container)\n\t}\n\n\treturn container\n}\n\n\nfunc WithLabel(key, value string) func(*types.Container) {\n\treturn func(c *types.Container) {\n\t\tif c.Labels == nil {\n\t\t\tc.Labels = map[string]string{}\n\t\t}\n\t\tc.Labels[key] = value\n\t}\n}\n\n\nfunc WithName(name string) func(*types.Container) {\n\treturn func(c *types.Container) {\n\t\tc.Names = append(c.Names, \"/\"+name)\n\t}\n}\n\n\nfunc WithPort(privateport, publicport uint16, builders ...func(*types.Port)) func(*types.Container) {\n\treturn func(c *types.Container) {\n\t\tif c.Ports == nil {\n\t\t\tc.Ports = []types.Port{}\n\t\t}\n\t\tport := &types.Port{\n\t\t\tPrivatePort: privateport,\n\t\t\tPublicPort: publicport,\n\t\t}\n\t\tfor _, builder := range builders {\n\t\t\tbuilder(port)\n\t\t}\n\t\tc.Ports = append(c.Ports, *port)\n\t}\n}\n\n\n\n\n\nfunc TCP(p *types.Port) {\n\tp.Type = \"tcp\"\n}\n\n\nfunc UDP(p *types.Port) {\n\tp.Type = \"udp\"\n}\n\nfunc IP(ip string) func(*types.Port) ", "output": "{\n\treturn func(p *types.Port) {\n\t\tp.IP = ip\n\t}\n}"} {"input": "package arg2\n\nimport (\n\t\"encoding/binary\"\n\t\"io\"\n\n\t\"github.com/uber/tchannel-go/typed\"\n)\n\n\n\n\n\ntype KeyValIterator struct {\n\tremaining []byte\n\tleftPairCount int\n\tkey []byte\n\tval []byte\n}\n\n\n\n\n\n\n\nfunc (i KeyValIterator) Key() []byte {\n\treturn i.key\n}\n\n\nfunc (i KeyValIterator) Value() []byte {\n\treturn i.val\n}\n\n\nfunc (i KeyValIterator) Remaining() bool {\n\treturn i.leftPairCount > 0\n}\n\n\n\n\n\n\nfunc (i KeyValIterator) Next() (kv KeyValIterator, _ error) {\n\tif i.leftPairCount <= 0 {\n\t\treturn KeyValIterator{}, io.EOF\n\t}\n\n\trbuf := typed.NewReadBuffer(i.remaining)\n\tkeyLen := int(rbuf.ReadUint16())\n\tkey := rbuf.ReadBytes(keyLen)\n\tvalLen := int(rbuf.ReadUint16())\n\tval := rbuf.ReadBytes(valLen)\n\tif rbuf.Err() != nil {\n\t\treturn KeyValIterator{}, rbuf.Err()\n\t}\n\n\tleftPairCount := i.leftPairCount - 1\n\n\tkv = KeyValIterator{\n\t\tremaining: rbuf.Remaining(),\n\t\tleftPairCount: leftPairCount,\n\t\tkey: key,\n\t\tval: val,\n\t}\n\treturn kv, nil\n}\n\nfunc NewKeyValIterator(arg2Payload []byte) (KeyValIterator, error) ", "output": "{\n\tif len(arg2Payload) < 2 {\n\t\treturn KeyValIterator{}, io.EOF\n\t}\n\n\tleftPairCount := binary.BigEndian.Uint16(arg2Payload[0:2])\n\treturn KeyValIterator{\n\t\tleftPairCount: int(leftPairCount),\n\t\tremaining: arg2Payload[2:],\n\t}.Next()\n}"} {"input": "package mcore\n\nimport (\n\t\"log\"\n)\n\ntype StringKeyValueMap map[string]string\n\nfunc NewStringKeyValueMap() StringKeyValueMap {\n\treturn make(map[string]string)\n}\n\n\nfunc (c StringKeyValueMap) Put(key, value string) {\n\tc[key] = value\n}\n\nfunc (c StringKeyValueMap) IsContain(key string) bool {\n\t_, ok := c[key]\n\treturn ok\n}\n\nfunc (c StringKeyValueMap) GetString(key string) string {\n\treturn c.GetStringWithDefault(key, \"\")\n}\n\n\n\nfunc (c StringKeyValueMap) GetInt(key string) int {\n\treturn String(c.GetString(key)).ToIntNoError()\n}\n\nfunc (c StringKeyValueMap) GetBool(key string) bool {\n\treturn String(c.GetString(key)).ToBool()\n}\n\nfunc (c StringKeyValueMap) GetStringWithDefault(key, defaultValue string) string ", "output": "{\n\tif c.IsContain(key) {\n\t\treturn c[key]\n\t}\n\tlog.Printf(\"Error: not contains key: %s\", key)\n\treturn defaultValue\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os/exec\"\n)\n\n\n\nfunc RunLogster(logFile string) {\n\n\tif logFile == \"\" {\n\t\tlogger.Error(\"logfile not found\", \"file\", logFile)\n\t\treturn\n\t}\n\n\tlogsterArgs := LogsterArgs(logFile)\n\n\tlogger.Info(\"logster\", \"args\", logsterArgs)\n\n\tcmd := exec.Command(LogsterPath, logsterArgs...)\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tlogger.Error(\"logster\", \"err\", err.Error())\n\t}\n\n\tlogger.Info(\"logster\", \"output\", string(out))\n\n}\n\nfunc LogsterArgs(logPath string) (args []string) ", "output": "{\n\n\targs = append(args, fmt.Sprintf(\"--output=%s\", Output))\n\n\tif Prefix != \"\" {\n\t\targs = append(args, fmt.Sprintf(\"--metric-prefix=%s\", Prefix))\n\t}\n\n\tif GraphiteHost != \"\" {\n\t\targs = append(args, fmt.Sprintf(\"--graphite-host=%s\", GraphiteHost))\n\t}\n\n\targs = append(args, Parser)\n\targs = append(args, logPath)\n\n\treturn\n}"} {"input": "package otlptracegrpc \n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/otel/exporters/otlp/otlptrace\"\n)\n\n\n\n\n\nfunc NewUnstarted(opts ...Option) *otlptrace.Exporter {\n\treturn otlptrace.NewUnstarted(NewClient(opts...))\n}\n\nfunc New(ctx context.Context, opts ...Option) (*otlptrace.Exporter, error) ", "output": "{\n\treturn otlptrace.New(ctx, NewClient(opts...))\n}"} {"input": "package fs\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n)\n\n\ntype VolumeDevSpec struct {\n\tUnit string\n\tControllerPciSlotNumber string\n}\n\n\nfunc Mkdir(path string) error {\n\tstat, err := os.Lstat(path)\n\tif os.IsNotExist(err) {\n\t\tlog.WithField(\"path\", path).Info(\"Directory doesn't exist, creating it \")\n\t\tif err := os.MkdirAll(path, 0755); err != nil {\n\t\t\tlog.WithFields(log.Fields{\"path\": path,\n\t\t\t\t\"err\": err}).Error(\"Failed to create directory \")\n\t\t\treturn err\n\t\t}\n\t} else if err != nil {\n\t\tlog.WithFields(log.Fields{\"path\": path,\n\t\t\t\"err\": err}).Error(\"Failed to test directory existence \")\n\t\treturn err\n\t}\n\n\tif stat != nil && !stat.IsDir() {\n\t\tmsg := fmt.Sprintf(\"%v already exists and it's not a directory\", path)\n\t\tlog.Error(msg)\n\t\treturn fmt.Errorf(msg)\n\t}\n\treturn nil\n}\n\n\nfunc Rmdir(path string) error {\n\treturn os.Remove(path)\n}\n\n\n\n\nfunc GetMountRootEntries(mountRoot string) ([]string, error) ", "output": "{\n\tvar vols []string\n\tvolumes, err := ioutil.ReadDir(mountRoot)\n\tif err != nil {\n\t\tlog.Errorf(\"Unable to read entries from %s (%v)\", mountRoot, err)\n\t\treturn vols, err\n\t}\n\n\tfor _, vol := range volumes {\n\t\tvols = append(vols, vol.Name())\n\t}\n\treturn vols, nil\n}"} {"input": "package uidgid\n\nimport (\n\t\"os/exec\"\n\t\"syscall\"\n)\n\ntype uidGidMapper struct {\n\tuids []syscall.SysProcIDMap\n\tgids []syscall.SysProcIDMap\n}\n\n\n\nfunc NewUnprivilegedMapper() Mapper {\n\tmaxID := min(MustGetMaxValidUID(), MustGetMaxValidGID())\n\n\treturn uidGidMapper{\n\t\tuids: []syscall.SysProcIDMap{\n\t\t\t{ContainerID: 0, HostID: maxID, Size: 1},\n\t\t\t{ContainerID: 1, HostID: 1, Size: maxID - 1},\n\t\t},\n\t\tgids: []syscall.SysProcIDMap{\n\t\t\t{ContainerID: 0, HostID: maxID, Size: 1},\n\t\t\t{ContainerID: 1, HostID: 1, Size: maxID - 1},\n\t\t},\n\t}\n}\n\nfunc (m uidGidMapper) Apply(cmd *exec.Cmd) {\n\tcmd.SysProcAttr.Credential = &syscall.Credential{\n\t\tUid: uint32(m.uids[0].ContainerID),\n\t\tGid: uint32(m.gids[0].ContainerID),\n\t}\n\n\tcmd.SysProcAttr.UidMappings = m.uids\n\tcmd.SysProcAttr.GidMappings = m.gids\n}\n\nfunc findMapping(idMap []syscall.SysProcIDMap, fromID int) int {\n\tfor _, id := range idMap {\n\t\tif id.Size != 1 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif id.ContainerID == fromID {\n\t\t\treturn id.HostID\n\t\t}\n\t}\n\n\treturn fromID\n}\n\nfunc (m uidGidMapper) Map(fromUid int, fromGid int) (int, int) {\n\treturn findMapping(m.uids, fromUid), findMapping(m.gids, fromGid)\n}\n\nfunc NewPrivilegedMapper() Mapper ", "output": "{\n\tmaxID := min(MustGetMaxValidUID(), MustGetMaxValidGID())\n\n\treturn uidGidMapper{\n\t\tuids: []syscall.SysProcIDMap{\n\t\t\t{ContainerID: maxID, HostID: 0, Size: 1},\n\t\t\t{ContainerID: 1, HostID: 1, Size: maxID - 1},\n\t\t},\n\t\tgids: []syscall.SysProcIDMap{\n\t\t\t{ContainerID: maxID, HostID: 0, Size: 1},\n\t\t\t{ContainerID: 1, HostID: 1, Size: maxID - 1},\n\t\t},\n\t}\n}"} {"input": "package log\n\nimport (\n\t\"io\"\n\t\"sync\"\n)\n\ntype MirrorWriter struct {\n\twriters []io.Writer\n\tlk sync.Mutex\n}\n\nfunc (mw *MirrorWriter) Write(b []byte) (int, error) {\n\tmw.lk.Lock()\n\tvar dropped bool\n\tfor i, w := range mw.writers {\n\t\t_, err := w.Write(b)\n\t\tif err != nil {\n\t\t\tmw.writers[i] = nil\n\t\t\tdropped = true\n\t\t}\n\t}\n\n\tif dropped {\n\t\twriters := mw.writers\n\t\tmw.writers = nil\n\t\tfor _, w := range writers {\n\t\t\tif w != nil {\n\t\t\t\tmw.writers = append(mw.writers, w)\n\t\t\t}\n\t\t}\n\t}\n\tmw.lk.Unlock()\n\treturn len(b), nil\n}\n\nfunc (mw *MirrorWriter) AddWriter(w io.Writer) {\n\tmw.lk.Lock()\n\tmw.writers = append(mw.writers, w)\n\tmw.lk.Unlock()\n}\n\n\n\nfunc (mw *MirrorWriter) Active() (active bool) ", "output": "{\n\tmw.lk.Lock()\n\tactive = len(mw.writers) > 0\n\tmw.lk.Unlock()\n\treturn\n}"} {"input": "package spinlock\n\nimport (\n\t\"fmt\"\n)\n\n\n\nfunc SpinLock() ", "output": "{\n\tfmt.Printf(\"Yo\")\n}"} {"input": "package jsonutil\n\nimport (\n\t\"github.com/buger/jsonparser\"\n\t\"strconv\"\n)\n\nfunc GetString(data []byte, keys ...string) (string, error) {\n\treturn jsonparser.GetString(data, keys...)\n}\n\nfunc MustGetString(data []byte, keys ...string) string {\n\ts, err := GetString(data, keys...)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn s\n}\n\nfunc GetFloat(data []byte, keys ...string) (float64, error) {\n\treturn jsonparser.GetFloat(data, keys...)\n}\n\nfunc MustGetFloat(data []byte, keys ...string) float64 {\n\tf, err := GetFloat(data, keys...)\n\tif err != nil {\n\t\treturn 0.0\n\t}\n\treturn f\n}\n\nfunc GetInt(data []byte, keys ...string) (int64, error) {\n\treturn jsonparser.GetInt(data, keys...)\n}\n\nfunc MustGetInt(data []byte, keys ...string) int64 {\n\ti, err := GetInt(data, keys...)\n\tif err != nil {\n\t\tif s := MustGetString(data, keys...); len(s) == 0 {\n\t\t\treturn 0\n\t\t} else if i, err = strconv.ParseInt(s, 10, 64); err != nil {\n\t\t\treturn 0\n\t\t}\n\t}\n\treturn i\n}\n\n\n\nfunc MustGetBoolean(data []byte, keys ...string) bool {\n\tb, err := GetBoolean(data, keys...)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn b\n}\n\nfunc GetBoolean(data []byte, keys ...string) (bool, error) ", "output": "{\n\treturn jsonparser.GetBoolean(data, keys...)\n}"} {"input": "package cmd\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/kubernetes-incubator/kube-aws/core/controlplane/cluster\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar (\n\tcmdVersion = &cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: \"Print version information and exit\",\n\t\tLong: ``,\n\t\tRun: runCmdVersion,\n\t}\n)\n\n\n\nfunc runCmdVersion(_ *cobra.Command, _ []string) {\n\tfmt.Printf(\"kube-aws version %s\\n\", cluster.VERSION)\n}\n\nfunc init() ", "output": "{\n\tRootCmd.AddCommand(cmdVersion)\n}"} {"input": "package chrootarchive\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"github.com/docker/docker/pkg/reexec\"\n)\n\n\n\nfunc fatal(err error) {\n\tfmt.Fprint(os.Stderr, err)\n\tos.Exit(1)\n}\n\n\n\nfunc flush(r io.Reader) {\n\tio.Copy(ioutil.Discard, r)\n}\n\nfunc init() ", "output": "{\n\treexec.Register(\"docker-applyLayer\", applyLayer)\n\treexec.Register(\"docker-untar\", untar)\n}"} {"input": "package decide\n\nimport (\n\t\"fmt\"\n\t\"github.com/pkg/errors\"\n\texp \"github.com/sjhitchner/go-decide/expression\"\n)\n\n\n\n\n\ntype Node struct {\n\tExpression exp.Expression\n\tPayload []string\n\tTrue []*Node\n\tFalse *Node\n}\n\nfunc NewNode(expression exp.Expression) *Node {\n\treturn &Node{\n\t\texpression,\n\t\tnil,\n\t\tnil,\n\t\tnil,\n\t}\n}\n\nfunc (t Node) Evaluate(ctx exp.Context, payloadMap map[string]struct{}, trace Logger) error {\n\tresult, err := toBool(t.Expression.Evaluate(ctx))\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to evaluate expression %v\", t.Expression)\n\t}\n\n\tif result {\n\t\tfor _, payload := range t.Payload {\n\t\t\tpayloadMap[payload] = struct{}{}\n\t\t}\n\t}\n\n\tif trace != nil {\n\t\ttrace.Appendf(\"EVAL %s %v\", t.Expression, t.Payload)\n\t}\n\n\tif result && len(t.True) > 0 {\n\t\tfor _, trueNode := range t.True {\n\t\t\terr := trueNode.Evaluate(ctx, payloadMap, trace)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\n\t} else if t.False != nil {\n\t\treturn t.False.Evaluate(ctx, payloadMap, trace)\n\n\t} else if result {\n\t\tfor _, payload := range t.Payload {\n\t\t\tpayloadMap[payload] = struct{}{}\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (t Node) String() string {\n\treturn fmt.Sprintf(\"(%s [%s] %s)\", t.True, t.Expression, t.False)\n}\n\nfunc toBool(result interface{}, err error) (bool, error) ", "output": "{\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif result == nil {\n\t\treturn false, nil\n\t}\n\n\tb, ok := result.(bool)\n\tif !ok {\n\t\treturn false, errors.Errorf(\"Expect bool got %v\", result)\n\t}\n\n\treturn b, nil\n}"} {"input": "package extends\n\ntype CEO interface {\n\tManager\n\tdeleteManager()\n\tIsCEO()\n}\n\ntype ceo struct {\n\tManager\n}\n\nfunc (p *ceo) deleteManager() {\n\tDeleteDirectorManager(p.Manager)\n}\n\nfunc (p *ceo) IsCEO() {}\n\ntype overwrittenMethodsOnManager struct {\n\tp Manager\n}\n\nfunc NewCEO(name string) CEO {\n\tom := &overwrittenMethodsOnManager{}\n\tp := NewDirectorManager(om, name)\n\tom.p = p\n\n\treturn &ceo{Manager: p}\n}\n\nfunc DeleteCEO(p CEO) {\n\tp.deleteManager()\n}\n\n\n\nfunc (p *ceo) GetPosition() string ", "output": "{\n\treturn \"CEO\"\n}"} {"input": "package elasticsearch\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/luopengift/gohttp\"\n)\n\nconst (\n\tenter = '\\n'\n)\n\ntype Meta struct {\n\tIndex string `json:\"_index\"`\n\tType string `json:\"_type\"`\n\tId string `json:\"_id,omitempty\"`\n}\n\nfunc NewMeta(_index, _type, _id string) *Meta {\n\treturn &Meta{_index, _type, _id}\n}\n\ntype Bulk struct {\n\tIndex *Meta `json:\"index,omitempty\"`\n\tUpdate *Meta `json:\"update,omitempty\"`\n\tSource []byte `json:\"-\"`\n}\n\nfunc NewBulkIndex(_index, _type, _id string, source []byte) *Bulk {\n\treturn &Bulk{\n\t\tIndex: NewMeta(_index, _type, _id),\n\t\tSource: source,\n\t}\n}\n\n\n\nfunc (b *Bulk) Bytes() ([]byte, error) {\n\tp, err := json.Marshal(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp = append(p, enter)\n\tp = append(p, b.Source...)\n\tp = append(p, enter)\n\treturn p, nil\n}\n\nfunc Send(addr string, p []byte) error {\n\tresp, err := gohttp.NewClient().URLString(\"http://\"+addr).Path(\"/_bulk\").Header(\"Accept\", \"application/json\").Body(p).Post()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.Code() != 200 {\n\t\treturn fmt.Errorf(resp.String())\n\t}\n\treturn nil\n\n}\n\nfunc NewBulkUpdate(_index, _type, _id string, source []byte) *Bulk ", "output": "{\n\treturn &Bulk{\n\t\tUpdate: NewMeta(_index, _type, _id),\n\t\tSource: source,\n\t}\n}"} {"input": "package xmlkey\n\nimport (\n\t\"bytes\"\n\t\"encoding/base64\"\n\t\"encoding/xml\"\n\t\"math/big\"\n)\n\ntype (\n\tkeyXML struct {\n\t\tXMLName xml.Name `xml:\"RSAKeyValue\"`\n\t\tpublicKeyXML\n\t\tprivateKeyXML\n\t}\n\n\tpublicKeyXML struct {\n\t\tModulus, Exponent *bigInt\n\t}\n\tprivateKeyXML struct {\n\t\tP, Q, DP, DQ, D, InverseQ *bigInt\n\t}\n\n\tbigInt struct{ *big.Int }\n)\n\nfunc (k keyXML) HasPublicKey() bool {\n\treturn allNotEmpty(k.Exponent, k.Modulus)\n}\n\nfunc (k keyXML) HasPrivateKey() bool {\n\treturn allNotEmpty(k.D, k.DP, k.DQ, k.InverseQ, k.P, k.Q)\n}\n\nfunc allNotEmpty(bis ...*bigInt) bool {\n\tfor _, bi := range bis {\n\t\tif bi == nil || bi.IsEmpty() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\nfunc (bi *bigInt) MarshalText() ([]byte, error) {\n\ttext := make([]byte, base64.StdEncoding.EncodedLen(len(bi.Bytes())))\n\tbase64.StdEncoding.Encode(text, bi.Bytes())\n\treturn text, nil\n}\n\nfunc (bi bigInt) BigInt() *big.Int {\n\treturn bi.Int\n}\n\nfunc (bi bigInt) Integer() int {\n\treturn int(bi.Int64())\n}\n\nfunc (bi bigInt) IsEmpty() bool {\n\treturn bi.Int == nil\n}\n\nfunc (bi *bigInt) UnmarshalText(text []byte) error ", "output": "{\n\tbs := make([]byte, base64.StdEncoding.DecodedLen(len(text)))\n\tif _, err := base64.StdEncoding.Decode(bs, text); err != nil {\n\t\treturn err\n\t}\n\tif bi.Int == nil {\n\t\tbi.Int = new(big.Int)\n\t}\n\tbi.Int.SetBytes(bytes.TrimRight(bs, \"\\x00\"))\n\treturn nil\n}"} {"input": "package treemap\n\nimport (\n\t\"github.com/emirpasic/gods/containers\"\n\trbt \"github.com/emirpasic/gods/trees/redblacktree\"\n)\n\nfunc assertIteratorImplementation() {\n\tvar _ containers.ReverseIteratorWithKey = (*Iterator)(nil)\n}\n\n\ntype Iterator struct {\n\titerator rbt.Iterator\n}\n\n\nfunc (m *Map) Iterator() Iterator {\n\treturn Iterator{iterator: m.tree.Iterator()}\n}\n\n\n\n\n\nfunc (iterator *Iterator) Next() bool {\n\treturn iterator.iterator.Next()\n}\n\n\n\n\nfunc (iterator *Iterator) Prev() bool {\n\treturn iterator.iterator.Prev()\n}\n\n\n\nfunc (iterator *Iterator) Value() interface{} {\n\treturn iterator.iterator.Value()\n}\n\n\n\nfunc (iterator *Iterator) Key() interface{} {\n\treturn iterator.iterator.Key()\n}\n\n\n\nfunc (iterator *Iterator) Begin() {\n\titerator.iterator.Begin()\n}\n\n\n\n\n\n\n\n\nfunc (iterator *Iterator) First() bool {\n\treturn iterator.iterator.First()\n}\n\n\n\n\nfunc (iterator *Iterator) Last() bool {\n\treturn iterator.iterator.Last()\n}\n\nfunc (iterator *Iterator) End() ", "output": "{\n\titerator.iterator.End()\n}"} {"input": "package storage\n\nimport (\n\t\"time\"\n\n\t\"k8s.io/kubernetes/pkg/runtime\"\n\t\"k8s.io/kubernetes/pkg/watch\"\n)\n\n\n\ntype Versioner interface {\n\tUpdateObject(obj runtime.Object, expiration *time.Time, resourceVersion uint64) error\n\tUpdateList(obj runtime.Object, resourceVersion uint64) error\n\tObjectResourceVersion(obj runtime.Object) (uint64, error)\n}\n\n\n\n\ntype ResponseMeta struct {\n\tTTL int64\n\tExpiration *time.Time\n\tResourceVersion uint64\n}\n\n\n\ntype FilterFunc func(obj runtime.Object) bool\n\n\n\n\n\n\n\ntype UpdateFunc func(input runtime.Object, res ResponseMeta) (output runtime.Object, ttl *uint64, err error)\n\n\n\ntype Interface interface {\n\tBackends() []string\n\n\tVersioner() Versioner\n\n\tCreate(key string, obj, out runtime.Object, ttl uint64) error\n\n\tSet(key string, obj, out runtime.Object, ttl uint64) error\n\n\tDelete(key string, out runtime.Object) error\n\n\tRecursiveDelete(key string, recursive bool) error\n\n\tWatch(key string, resourceVersion uint64, filter FilterFunc) (watch.Interface, error)\n\n\tWatchList(key string, resourceVersion uint64, filter FilterFunc) (watch.Interface, error)\n\n\tGet(key string, objPtr runtime.Object, ignoreNotFound bool) error\n\n\tGetToList(key string, listObj runtime.Object) error\n\n\tList(key string, listObj runtime.Object) error\n\n\tGuaranteedUpdate(key string, ptrToType runtime.Object, ignoreNotFound bool, tryUpdate UpdateFunc) error\n\n\tCodec() runtime.Codec\n}\n\nfunc Everything(runtime.Object) bool ", "output": "{\n\treturn true\n}"} {"input": "package node\n\nimport (\n\t\"context\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n\t\"time\"\n\n\tworkerCmd \"github.com/ohsu-comp-bio/funnel/cmd/worker\"\n\t\"github.com/ohsu-comp-bio/funnel/compute/scheduler\"\n\t\"github.com/ohsu-comp-bio/funnel/config\"\n\t\"github.com/ohsu-comp-bio/funnel/logger\"\n\t\"github.com/ohsu-comp-bio/funnel/util\"\n)\n\n\n\n\nfunc Run(ctx context.Context, conf config.Config, log *logger.Logger) error ", "output": "{\n\tconf.Node.ID = scheduler.GenNodeID()\n\n\tw, err := workerCmd.NewWorker(ctx, conf, log)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tn, err := scheduler.NewNodeProcess(ctx, conf, w.Run, log)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trunctx, cancel := context.WithCancel(context.Background())\n\trunctx = util.SignalContext(ctx, time.Nanosecond, syscall.SIGINT, syscall.SIGTERM)\n\tdefer cancel()\n\n\thupsig := make(chan os.Signal, 1)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-runctx.Done():\n\t\t\t\treturn\n\t\t\tcase <-hupsig:\n\t\t\t\tn.Drain()\n\t\t\t}\n\t\t}\n\t}()\n\tsignal.Notify(hupsig, syscall.SIGHUP)\n\n\tn.Run(runctx)\n\n\treturn nil\n}"} {"input": "package syscall\n\nimport \"unsafe\"\n\nfunc setTimespec(sec, nsec int64) Timespec {\n\treturn Timespec{Sec: sec, Nsec: nsec}\n}\n\nfunc setTimeval(sec, usec int64) Timeval {\n\treturn Timeval{Sec: sec, Usec: usec}\n}\n\nfunc SetKevent(k *Kevent_t, fd, mode, flags int) {\n\tk.Ident = uint64(fd)\n\tk.Filter = int16(mode)\n\tk.Flags = uint16(flags)\n}\n\n\n\nfunc (msghdr *Msghdr) SetControllen(length int) {\n\tmsghdr.Controllen = uint32(length)\n}\n\nfunc (cmsg *Cmsghdr) SetLen(length int) {\n\tcmsg.Len = uint32(length)\n}\n\nfunc (iov *Iovec) SetLen(length int) ", "output": "{\n\tiov.Len = uint64(length)\n}"} {"input": "package server\n\nimport (\n\t\"math/rand\"\n\t\"net/http\"\n\n\t\"github.com/gin-gonic/gin\"\n\tlog \"github.com/macarrie/flemzerd/logging\"\n\t\"github.com/macarrie/flemzerd/notifiers\"\n\t\"github.com/macarrie/flemzerd/notifiers/impl/telegram\"\n)\n\n\n\nfunc getTelegramChatID(c *gin.Context) {\n\tn, err := notifier.GetNotifier(\"telegram\")\n\tif err != nil || n == nil {\n\t\tc.JSON(http.StatusNotFound, err)\n\t\treturn\n\t}\n\n\tt := n.(*telegram.TelegramNotifier)\n\tvar chatID int64\n\tif t != nil {\n\t\tchatID = t.ChatID\n\t} else {\n\t\tchatID = 0\n\t}\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"chat_id\": chatID,\n\t})\n}\n\nfunc getTelegramAuthCode(c *gin.Context) {\n\tn, err := notifier.GetNotifier(\"telegram\")\n\tif err != nil || n == nil {\n\t\tc.JSON(http.StatusNotFound, err)\n\t\treturn\n\t}\n\n\tt := n.(*telegram.TelegramNotifier)\n\tif t.AuthCode == 0 {\n\t\tt.AuthCode = rand.Intn(1000000)\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"auth_code\": t.AuthCode,\n\t})\n}\n\nfunc performTelegramAuth(c *gin.Context) ", "output": "{\n\tn, err := notifier.GetNotifier(\"telegram\")\n\tif err != nil || n == nil {\n\t\tlog.Error(\"TELEGRAM NOTIFIER NOT FOUND\")\n\t\tc.JSON(http.StatusNotFound, err)\n\t\treturn\n\t}\n\n\tt := n.(*telegram.TelegramNotifier)\n\tif t.ChatID != 0 {\n\t\tlog.Error(\"CHAT ID NOT ZERO. EXIT STATUS NO CONTENT\")\n\t\tc.AbortWithStatus(http.StatusNoContent)\n\t\treturn\n\t}\n\n\tgo t.Auth()\n\tc.JSON(http.StatusOK, gin.H{})\n\treturn\n}"} {"input": "package label\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/docker/libcontainer/selinux\"\n)\n\n\n\nfunc FormatMountLabel(src, mountLabel string) string {\n\tif mountLabel != \"\" {\n\t\tswitch src {\n\t\tcase \"\":\n\t\t\tsrc = fmt.Sprintf(\"context=%q\", mountLabel)\n\t\tdefault:\n\t\t\tsrc = fmt.Sprintf(\"%s,context=%q\", src, mountLabel)\n\t\t}\n\t}\n\treturn src\n}\n\nfunc SetProcessLabel(processLabel string) error {\n\tif selinux.SelinuxEnabled() {\n\t\treturn selinux.Setexeccon(processLabel)\n\t}\n\treturn nil\n}\n\nfunc GetProcessLabel() (string, error) {\n\tif selinux.SelinuxEnabled() {\n\t\treturn selinux.Getexeccon()\n\t}\n\treturn \"\", nil\n}\n\nfunc SetFileLabel(path string, fileLabel string) error {\n\tif selinux.SelinuxEnabled() && fileLabel != \"\" {\n\t\treturn selinux.Setfilecon(path, fileLabel)\n\t}\n\treturn nil\n}\n\nfunc GetPidCon(pid int) (string, error) {\n\tif !selinux.SelinuxEnabled() {\n\t\treturn \"\", nil\n\t}\n\treturn selinux.Getpidcon(pid)\n}\n\nfunc Init() {\n\tselinux.SelinuxEnabled()\n}\n\nfunc ReserveLabel(label string) error {\n\tselinux.ReserveLabel(label)\n\treturn nil\n}\n\nfunc GenLabels(options string) (string, string, error) ", "output": "{\n\tif !selinux.SelinuxEnabled() {\n\t\treturn \"\", \"\", nil\n\t}\n\tvar err error\n\tprocessLabel, mountLabel := selinux.GetLxcContexts()\n\tif processLabel != \"\" {\n\t\tvar (\n\t\t\ts = strings.Fields(options)\n\t\t\tl = len(s)\n\t\t)\n\t\tif l > 0 {\n\t\t\tpcon := selinux.NewContext(processLabel)\n\t\t\tfor i := 0; i < l; i++ {\n\t\t\t\to := strings.Split(s[i], \"=\")\n\t\t\t\tpcon[o[0]] = o[1]\n\t\t\t}\n\t\t\tprocessLabel = pcon.Get()\n\t\t\tmountLabel, err = selinux.CopyLevel(processLabel, mountLabel)\n\t\t}\n\t}\n\treturn processLabel, mountLabel, err\n}"} {"input": "package problem0171\n\n\n\n\nfunc titleToNumber(s string) int ", "output": "{\n\tvar res int\n\tfor _, c := range s {\n\t\tres = res*26 + int(c-'A'+1)\n\t}\n\treturn res\n}"} {"input": "package scenery\n\n\nimport \"C\"\nimport (\n\t\"unsafe\"\n)\n\ntype LibraryEnumerator func(path string, ref interface{})\n\ntype lookupRegInfo struct {\n\tenumerator LibraryEnumerator\n\tref interface{}\n}\n\n\nfunc lookupObjectsEnum(cPath *C.char, ref unsafe.Pointer) {\n\tregInfo := (*lookupRegInfo)(ref)\n\tregInfo.enumerator(C.GoString(cPath), regInfo.ref)\n}\n\n\n\nfunc LookupObjects(path string, lat, lon float32, enumerator LibraryEnumerator, ref interface{}) int ", "output": "{\n\tcPath := C.CString(path)\n\tdefer C.free(unsafe.Pointer(cPath))\n\tregInfo := &lookupRegInfo{enumerator, ref}\n\treturn int(C.XPLMLookupObjects(cPath, C.float(lat), C.float(lon), C.XPLMLibraryEnumerator_f(unsafe.Pointer(C.lookupObjectsEnum)), unsafe.Pointer(regInfo)))\n}"} {"input": "package statement\n\nimport (\n\t\"reflect\"\n\n\t\"github.com/richardwilkes/goblin/ast\"\n)\n\n\ntype Continue struct {\n\tast.PosImpl\n}\n\nfunc (stmt *Continue) String() string {\n\treturn \"continue\"\n}\n\n\n\n\nfunc (stmt *Continue) Execute(scope ast.Scope) (reflect.Value, error) ", "output": "{\n\treturn ast.NilValue, ast.ErrContinue\n}"} {"input": "package operations\n\n\n\nimport (\n\t\"github.com/denkhaus/bitshares/types\"\n\t\"github.com/denkhaus/bitshares/util\"\n\t\"github.com/juju/errors\"\n)\n\n\n\ntype CommitteeMemberCreateOperation struct {\n\ttypes.OperationFee\n\tCommitteeMemberAccount types.AccountID `json:\"committee_member_account\"`\n\tURL types.String `json:\"url\"`\n}\n\nfunc (p CommitteeMemberCreateOperation) Type() types.OperationType {\n\treturn types.OperationTypeCommitteeMemberCreate\n}\n\nfunc (p CommitteeMemberCreateOperation) Marshal(enc *util.TypeEncoder) error {\n\tif err := enc.Encode(int8(p.Type())); err != nil {\n\t\treturn errors.Annotate(err, \"encode OperationType\")\n\t}\n\tif err := enc.Encode(p.Fee); err != nil {\n\t\treturn errors.Annotate(err, \"encode Fee\")\n\t}\n\tif err := enc.Encode(p.CommitteeMemberAccount); err != nil {\n\t\treturn errors.Annotate(err, \"encode CommitteeMemberAccount\")\n\t}\n\tif err := enc.Encode(p.URL); err != nil {\n\t\treturn errors.Annotate(err, \"encode URL\")\n\t}\n\n\treturn nil\n}\n\nfunc init() ", "output": "{\n\ttypes.OperationMap[types.OperationTypeCommitteeMemberCreate] = func() types.Operation {\n\t\top := &CommitteeMemberCreateOperation{}\n\t\treturn op\n\t}\n}"} {"input": "package user\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/juju/cmd\"\n\t\"github.com/juju/errors\"\n\t\"github.com/juju/names\"\n\t\"launchpad.net/gnuflag\"\n\n\t\"github.com/juju/juju/cmd/envcmd\"\n)\n\nconst userCredentialsDoc = `\nWrites out the current user and credentials to a file that can be used\nwith 'juju system login' to allow the user to access the same environments\nas the same user from another machine.\n\nExamples:\n\n $ juju user credentials --output staging.creds\n\n # copy the staging.creds file to another machine\n\n $ juju system login staging --server staging.creds --keep-password\n\n\nSee Also:\n juju system login\n`\n\nfunc newCredentialsCommand() cmd.Command {\n\treturn envcmd.WrapSystem(&credentialsCommand{})\n}\n\n\ntype credentialsCommand struct {\n\tUserCommandBase\n\tOutPath string\n}\n\n\n\n\n\nfunc (c *credentialsCommand) SetFlags(f *gnuflag.FlagSet) {\n\tf.StringVar(&c.OutPath, \"o\", \"\", \"specifies the path of the generated file\")\n\tf.StringVar(&c.OutPath, \"output\", \"\", \"\")\n}\n\n\nfunc (c *credentialsCommand) Run(ctx *cmd.Context) error {\n\tcreds, err := c.ConnectionCredentials()\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tfilename := c.OutPath\n\tif filename == \"\" {\n\t\tname := names.NewUserTag(creds.User).Name()\n\t\tfilename = fmt.Sprintf(\"%s.server\", name)\n\t}\n\treturn writeServerFile(c, ctx, creds.User, creds.Password, filename)\n}\n\nfunc (c *credentialsCommand) Info() *cmd.Info ", "output": "{\n\treturn &cmd.Info{\n\t\tName: \"credentials\",\n\t\tPurpose: \"save the credentials and server details to a file\",\n\t\tDoc: userCredentialsDoc,\n\t}\n}"} {"input": "package geom\n\nimport \"math\"\n\n\ntype MultiLineString []LineString\n\n\nfunc (ml MultiLineString) Bounds() *Bounds {\n\tb := NewBounds()\n\tfor _, l := range ml {\n\t\tb.Extend(l.Bounds())\n\t}\n\treturn b\n}\n\n\nfunc (ml MultiLineString) Length() float64 {\n\tlength := 0.\n\tfor _, l := range ml {\n\t\tlength += l.Length()\n\t}\n\treturn length\n}\n\n\n\n\n\nfunc (ml MultiLineString) Distance(p Point) float64 {\n\td := math.Inf(1)\n\tfor _, l := range ml {\n\t\tlDist := l.Distance(p)\n\t\td = math.Min(d, lDist)\n\t}\n\treturn d\n}\n\nfunc (ml MultiLineString) Within(p Polygonal) WithinStatus ", "output": "{\n\tfor _, l := range ml {\n\t\tif l.Within(p) == Outside {\n\t\t\treturn Outside\n\t\t}\n\t}\n\treturn Inside\n}"} {"input": "package luno\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\n\ntype Account struct {\n\tEntity\n\tEmail string `json:\"email\"`\n\tName string `json:\"name\"`\n\tFirstName string `json:\"first_name\"`\n\tLastName string `json:\"last_name\"`\n\tUserName string `json:\"username\"`\n\tCreated string `json:\"created\"`\n\tClosed string `json:\"closed\"`\n}\n\n\n\n\n\nfunc ParseAccount(resp *http.Response) (*Account, error) {\n\trespBytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading luno response body: %v\", err)\n\t}\n\tvar rv Account\n\terr = json.Unmarshal(respBytes, &rv)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing luno account json: '%s' err: %v\", respBytes, err)\n\t}\n\treturn &rv, nil\n}\n\nfunc (a *Account) MarshalForUpdate() ([]byte, error) ", "output": "{\n\ttmp := map[string]interface{}{\n\t\t\"email\": a.Email,\n\t\t\"name\": a.Name,\n\t\t\"first_name\": a.FirstName,\n\t\t\"last_name\": a.LastName,\n\t}\n\treturn json.Marshal(tmp)\n}"} {"input": "package ansiwriter\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\ntype Modifier func() string\n\nfunc escapeANSI(code int) string {\n\treturn fmt.Sprintf(\"\\033[%dm\", code)\n}\n\nfunc Bold() string { return escapeANSI(1) }\nfunc Black() string { return escapeANSI(30) }\nfunc Red() string { return escapeANSI(31) }\nfunc Green() string { return escapeANSI(32) }\n\nfunc Blue() string { return escapeANSI(34) }\nfunc Magenta() string { return escapeANSI(35) }\nfunc Cyan() string { return escapeANSI(36) }\nfunc White() string { return escapeANSI(37) }\n\ntype awr struct {\n\tio.Writer\n\tmodifiers []Modifier\n}\n\n\n\n\nfunc New(w io.Writer, mods ...Modifier) io.Writer {\n\treturn awr{w, mods}\n}\n\nfunc (a awr) Write(b []byte) (n int, err error) {\n\tfor _, mod := range a.modifiers {\n\t\ta.Writer.Write([]byte(mod()))\n\t}\n\tn, err = a.Writer.Write(b)\n\t_, _ = a.Writer.Write([]byte(\"\\033[0m\"))\n\treturn\n}\n\nfunc Yellow() string ", "output": "{ return escapeANSI(33) }"} {"input": "package tarjan\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/gyuho/goraph/graph/gsd\"\n)\n\n\n\nfunc Test_JSON_Contains(test *testing.T) {\n\tg15 := gsd.JSONGraph(\"../../../example_files/testgraph.json\", \"testgraph.015\")\n\ta := g15.FindVertexByID(\"A\")\n\tb := g15.FindVertexByID(\"B\")\n\tovs := a.GetOutVertices()\n\tif !Contains(b, ovs) {\n\t\ttest.Errorf(\"Should contain B in OutVertices but %+v\", Contains(b, ovs))\n\t}\n}\n\nfunc Test_JSON_SCC(test *testing.T) ", "output": "{\n\tg15 := gsd.JSONGraph(\"../../../example_files/testgraph.json\", \"testgraph.015\")\n\tresult15 := SCC(g15)\n\trc15 := \"[[H] [G F] [D C] [E B A]]\"\n\tif fmt.Sprintf(\"%v\", result15) != rc15 {\n\t\ttest.Errorf(\"Should return \\n%+v\\nbut\\n%+v\", result15, rc15)\n\t}\n\n\tg16 := gsd.JSONGraph(\"../../../example_files/testgraph.json\", \"testgraph.016\")\n\tfmt.Println(SCC(g16))\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc parseM3uPlaylist(data string) (songs []*SongRecord) {\n\tvar songIndex int\n\tvar newSong *SongRecord\n\n\tfor _, line := range strings.Split(data, \"\\n\") {\n\t\tline = strings.TrimSpace(line)\n\t\tif !isSongRecord(line) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif isSongRecordHeader(line) {\n\t\t\tsongIndex += 1\n\t\t\tnewSong = extractSongRecordHeader(songIndex, line)\n\t\t} else {\n\t\t\tnewSong.setFilepath(line)\n\t\t\tsongs = append(songs, newSong)\n\t\t}\n\t}\n\treturn songs\n}\n\nfunc isSongRecord(input string) bool {\n\treturn input != \"\" && !strings.HasPrefix(input, \"#EXTM3U\")\n}\n\nfunc isSongRecordHeader(input string) bool {\n\treturn strings.HasPrefix(input, \"#EXTINF:\")\n}\n\n\n\nfunc writePlsPlaylist(songs []*SongRecord) error {\n\tfmt.Println(\"[playlist]\")\n\tfor _, song := range songs {\n\t\tif pls, err := song.ToPls(); err != nil {\n\t\t\treturn err\n\t\t} else {\n\t\t\tfmt.Printf(pls)\n\t\t}\n\t}\n\tfmt.Printf(\"NumberOfEntries=%d\\nVersion=2\\n\", len(songs))\n\treturn nil\n}\n\nfunc extractSongRecordHeader(index int, line string) (s *SongRecord) ", "output": "{\n\tvar title, duration string\n\tif i := strings.IndexAny(line, \"-0123456789\"); i > -1 {\n\t\tconst separator = \",\"\n\t\tline = line[i:]\n\t\tif j := strings.Index(line, separator); j > -1 {\n\t\t\ttitle = line[j+len(separator):]\n\t\t\tduration = line[:j]\n\t\t}\n\t}\n\n\treturn NewSongRecord(index, \"\", title, duration)\n}"} {"input": "package fsettings\n\nimport \"encoding/json\"\n\n\ntype MapGenSettings struct {\n\tTerrainSegmentation string `json:\"terrain_segmentation\"`\n\tWater string `json:\"water\"`\n\tWidth uint `json:\"width\"`\n\tHeight uint `json:\"height\"`\n\tStartingArea string `json:\"starting_area\"`\n\tPeacefulMode bool `json:\"peaceful_mode\"`\n\tAutoplaceControls AutoplaceControls `json:\"autoplace_controls\"`\n}\n\n\n\ntype AutoplaceControls struct {\n\tCoal PlacementControl `json:\"coal\"`\n\tCopperOre PlacementControl `json:\"copper-ore\"`\n\tCrudeOil PlacementControl `json:\"crude-oil\"`\n\tEnemyBase PlacementControl `json:\"enemy-base\"`\n\tIronOre PlacementControl `json:\"iron-ore\"`\n\tStone PlacementControl `json:\"stone\"`\n}\n\ntype PlacementControl struct {\n\tFrequency string `json:\"frequency\"`\n\tSize string `json:\"size\"`\n\tRichness string `json:\"richness\"`\n}\n\n\n\nfunc NewMapGenSettings() MapGenSettings {\n\tnormalLevels := PlacementControl{Frequency: \"normal\", Size: \"normal\", Richness: \"normal\"}\n\treturn MapGenSettings{\n\t\tTerrainSegmentation: \"normal\",\n\t\tWater: \"normal\",\n\t\tWidth: uint(0),\n\t\tHeight: uint(0),\n\t\tStartingArea: \"normal\",\n\t\tPeacefulMode: false,\n\t\tAutoplaceControls: AutoplaceControls{\n\t\t\tCoal: normalLevels,\n\t\t\tCopperOre: normalLevels,\n\t\t\tCrudeOil: normalLevels,\n\t\t\tEnemyBase: normalLevels,\n\t\t\tIronOre: normalLevels,\n\t\t\tStone: normalLevels,\n\t\t},\n\t}\n}\n\nfunc (fs MapGenSettings) String() string ", "output": "{\n\tj, _ := json.MarshalIndent(fs, \"\", \" \")\n\treturn string(j)\n}"} {"input": "package quantity\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\n\ntype Offset Size\n\nconst (\n\tOffsetKiB = Offset(1 << 10)\n\tOffsetMiB = Offset(1 << 20)\n)\n\nfunc (o *Offset) String() string {\n\treturn (*Size)(o).String()\n}\n\n\n\n\nfunc (o *Offset) IECString() string {\n\treturn iecSizeString(int64(*o))\n}\n\nfunc (o *Offset) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar gs string\n\tif err := unmarshal(&gs); err != nil {\n\t\treturn errors.New(`cannot unmarshal gadget offset`)\n\t}\n\n\tvar err error\n\t*o, err = ParseOffset(gs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot parse offset %q: %v\", gs, err)\n\t}\n\treturn err\n}\n\n\n\n\n\nfunc ParseOffset(gs string) (Offset, error) ", "output": "{\n\toffs, err := parseSizeOrOffset(gs)\n\tif offs < 0 {\n\t\treturn 0, errors.New(\"offset cannot be negative\")\n\t}\n\treturn Offset(offs), err\n}"} {"input": "package x11\n\nimport (\n\t\"C\"\n\t\"unsafe\"\n)\n\ntype ConfigureEvent C.XConfigureEvent\n\n\n\nfunc (evt *ConfigureEvent) ToEvent() *Event {\n\treturn (*Event)(unsafe.Pointer(evt))\n}\n\nfunc (evt *ConfigureEvent) Window() Window ", "output": "{\n\treturn Window(evt.window)\n}"} {"input": "package retry\n\nimport (\n\t\"time\"\n)\n\ntype strategyFunc func(now time.Time) Timer\n\n\nfunc (f strategyFunc) NewTimer(now time.Time) Timer {\n\treturn f(now)\n}\n\n\n\n\n\n\ntype countLimitTimer struct {\n\ttimer Timer\n\tremain int\n}\n\nfunc (t *countLimitTimer) NextSleep(now time.Time) (time.Duration, bool) {\n\tif t.remain--; t.remain <= 0 {\n\t\treturn 0, false\n\t}\n\treturn t.timer.NextSleep(now)\n}\n\n\n\nfunc LimitTime(limit time.Duration, strategy Strategy) Strategy {\n\treturn strategyFunc(func(now time.Time) Timer {\n\t\treturn &timeLimitTimer{\n\t\t\ttimer: strategy.NewTimer(now),\n\t\t\tend: now.Add(limit),\n\t\t}\n\t})\n}\n\ntype timeLimitTimer struct {\n\ttimer Timer\n\tend time.Time\n}\n\nfunc (t *timeLimitTimer) NextSleep(now time.Time) (time.Duration, bool) {\n\tsleep, ok := t.timer.NextSleep(now)\n\tif ok && now.Add(sleep).After(t.end) {\n\t\treturn 0, false\n\t}\n\treturn sleep, ok\n}\n\nfunc LimitCount(n int, strategy Strategy) Strategy ", "output": "{\n\treturn strategyFunc(func(now time.Time) Timer {\n\t\treturn &countLimitTimer{\n\t\t\ttimer: strategy.NewTimer(now),\n\t\t\tremain: n,\n\t\t}\n\t})\n}"} {"input": "package associations_test\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com/gobuffalo/pop/associations\"\n\t\"github.com/gobuffalo/pop/nulls\"\n\t\"github.com/stretchr/testify/require\"\n)\n\ntype FooHasMany struct {\n\tID int `db:\"id\"`\n\tBarHasManies *barHasManies `has_many:\"bar_has_manies\"`\n}\n\ntype barHasMany struct {\n\tTitle string `db:\"title\"`\n\tFooHasManyID nulls.Int `db:\"foo_has_many_id\"`\n}\n\ntype barHasManies []barHasMany\n\nfunc Test_Has_Many_Association(t *testing.T) {\n\ta := require.New(t)\n\n\tid := 1\n\tfoo := FooHasMany{ID: 1}\n\n\tas, err := associations.ForStruct(&foo)\n\n\ta.NoError(err)\n\ta.Equal(len(as), 1)\n\ta.Equal(reflect.Slice, as[0].Kind())\n\n\twhere, args := as[0].Constraint()\n\ta.Equal(\"foo_has_many_id = ?\", where)\n\ta.Equal(id, args[0].(int))\n}\n\n\n\nfunc Test_Has_Many_SetValue(t *testing.T) ", "output": "{\n\ta := require.New(t)\n\tfoo := FooHasMany{ID: 1, BarHasManies: &barHasManies{{Title: \"bar\"}}}\n\n\tas, _ := associations.ForStruct(&foo)\n\ta.Equal(len(as), 1)\n\n\tca, ok := as[0].(associations.AssociationAfterCreatable)\n\ta.True(ok)\n\n\tca.AfterSetup()\n\ta.Equal(foo.ID, (*foo.BarHasManies)[0].FooHasManyID.Interface().(int))\n}"} {"input": "package cluster\n\nimport (\n\t\"encoding/binary\"\n\t\"os\"\n)\n\ntype stateFile struct {\n\tHandle *os.File\n\tName string\n\tCount int32\n\tTimestamp int64\n}\n\nfunc newStateFile(name string) *stateFile {\n\tsf := new(stateFile)\n\tsf.Name = name\n\treturn sf\n}\n\nfunc (sf *stateFile) access() error {\n\tvar err error\n\tsf.Handle, err = os.OpenFile(sf.Name, os.O_RDWR|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\nfunc (sf *stateFile) read() error {\n\tsf.Handle.Seek(0, 0)\n\terr := binary.Read(sf.Handle, binary.LittleEndian, &sf.Count)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = binary.Read(sf.Handle, binary.LittleEndian, &sf.Timestamp)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (sf *stateFile) write() error ", "output": "{\n\terr := sf.Handle.Truncate(0)\n\tsf.Handle.Seek(0, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = binary.Write(sf.Handle, binary.LittleEndian, sf.Count)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = binary.Write(sf.Handle, binary.LittleEndian, sf.Timestamp)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSIoTAnalyticsPipeline_DeviceShadowEnrich struct {\n\n\tAttribute string `json:\"Attribute,omitempty\"`\n\n\tName string `json:\"Name,omitempty\"`\n\n\tNext string `json:\"Next,omitempty\"`\n\n\tRoleArn string `json:\"RoleArn,omitempty\"`\n\n\tThingName string `json:\"ThingName,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) AWSCloudFormationType() string {\n\treturn \"AWS::IoTAnalytics::Pipeline.DeviceShadowEnrich\"\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) SetDeletionPolicy(policy policies.DeletionPolicy) ", "output": "{\n\tr._deletionPolicy = policy\n}"} {"input": "package roles\n\nimport (\n\t\"testing\"\n\n\t\"github.com/rackspace/gophercloud/pagination\"\n\tth \"github.com/rackspace/gophercloud/testhelper\"\n\t\"github.com/rackspace/gophercloud/testhelper/client\"\n)\n\n\n\nfunc TestAddUserRole(t *testing.T) {\n\tth.SetupHTTP()\n\tdefer th.TeardownHTTP()\n\n\tMockAddUserRoleResponse(t)\n\n\terr := AddUserRole(client.ServiceClient(), \"{tenant_id}\", \"{user_id}\", \"{role_id}\").ExtractErr()\n\n\tth.AssertNoErr(t, err)\n}\n\nfunc TestDeleteUserRole(t *testing.T) {\n\tth.SetupHTTP()\n\tdefer th.TeardownHTTP()\n\n\tMockDeleteUserRoleResponse(t)\n\n\terr := DeleteUserRole(client.ServiceClient(), \"{tenant_id}\", \"{user_id}\", \"{role_id}\").ExtractErr()\n\n\tth.AssertNoErr(t, err)\n}\n\nfunc TestRole(t *testing.T) ", "output": "{\n\tth.SetupHTTP()\n\tdefer th.TeardownHTTP()\n\n\tMockListRoleResponse(t)\n\n\tcount := 0\n\n\terr := List(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) {\n\t\tcount++\n\t\tactual, err := ExtractRoles(page)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to extract users: %v\", err)\n\t\t\treturn false, err\n\t\t}\n\n\t\texpected := []Role{\n\t\t\tRole{\n\t\t\t\tID: \"123\",\n\t\t\t\tName: \"compute:admin\",\n\t\t\t\tDescription: \"Nova Administrator\",\n\t\t\t},\n\t\t}\n\n\t\tth.CheckDeepEquals(t, expected, actual)\n\n\t\treturn true, nil\n\t})\n\n\tth.AssertNoErr(t, err)\n\tth.AssertEquals(t, 1, count)\n}"} {"input": "package violetear\n\nimport (\n\t\"net/http\"\n\t\"time\"\n)\n\n\ntype ResponseWriter struct {\n\thttp.ResponseWriter\n\trequestID string\n\tsize, status int\n\tstart time.Time\n}\n\n\nfunc NewResponseWriter(w http.ResponseWriter, rid string) *ResponseWriter {\n\treturn &ResponseWriter{\n\t\tResponseWriter: w,\n\t\trequestID: rid,\n\t\tstart: time.Now(),\n\t\tstatus: http.StatusOK,\n\t}\n}\n\n\nfunc (w *ResponseWriter) Status() int {\n\treturn w.status\n}\n\n\nfunc (w *ResponseWriter) Size() int {\n\treturn w.size\n}\n\n\nfunc (w *ResponseWriter) RequestTime() string {\n\treturn time.Since(w.start).String()\n}\n\n\nfunc (w *ResponseWriter) RequestID() string {\n\treturn w.requestID\n}\n\n\n\nfunc (w *ResponseWriter) Write(data []byte) (int, error) {\n\tsize, err := w.ResponseWriter.Write(data)\n\tw.size += size\n\treturn size, err\n}\n\n\n\n\n\nfunc (w *ResponseWriter) WriteHeader(statusCode int) ", "output": "{\n\tw.status = statusCode\n\tw.ResponseWriter.WriteHeader(statusCode)\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"reflect\"\n)\n\ntype User struct{\n Id int\n Name string\n Age int\n}\n\n\n\nfunc main(){\n var u User\n u = User{1, \"ok\", 12}\n info(u)\n}\n\nfunc info(o interface{}){\n t := reflect.TypeOf(o)\n fmt.Println(\"Type:\", t.Name())\n\n v := reflect.ValueOf(o)\n fmt.Println(\"Fields:\")\n\n for i:= 0; i < t.NumField(); i++{\n f := t.Field(i)\n val := v.Field(i).Interface()\n fmt.Printf(\"%6s: %v = %v\\n\", f.Name, f.Type, val)\n }\n \n for i:= 0; i < t.NumMethod(); i++{\n m := t.Method(i)\n fmt.Printf(\"%6s: %v\\n\", m.Name)\n }\n}\n\nfunc (u User) Hello()", "output": "{\n fmt.Println(\"Hello World.\")\n}"} {"input": "package listener\n\nimport (\n\t\"net\"\n\n\t\"github.com/gorilla/websocket\"\n)\n\ntype websocketConn struct {\n\tnet.Conn\n}\n\n\n\nfunc NewWebsocketConn(conn *websocket.Conn) net.Conn ", "output": "{\n\treturn &websocketConn{\n\t\tConn: conn.UnderlyingConn(),\n\t}\n}"} {"input": "package cli\n\nimport (\n\t\"os\"\n\t\"fmt\"\n)\n\n\ntype Cmd interface {\n\tKey() string\n\tDescription() string\n\tExecute(args []string) error\n\tPrintUsage()\n}\n\n\n\ntype CmdHandler interface {\n\tRegisterCmd(Cmd)\n\tHandle()\n\tHandleCmd(key string, args []string)\n\tPrintUsage()\n}\n\n\n\n\nfunc initCmdHandler() *cmdHandler {\n\th := new(cmdHandler)\n\th.cmds = make(map[string]Cmd)\n\treturn h\n}\n\ntype cmdHandler struct {\n\tcmds map[string]Cmd\n}\n\nfunc (h *cmdHandler) RegisterCmd(cmd Cmd) {\n\tkey := cmd.Key()\n\th.cmds[key] = cmd\n}\n\nfunc (h *cmdHandler) Handle() {\n\targs := os.Args\n\tif args == nil || len(args) < 2 {\n\t\th.handleUsageError(\"Insufficient arguments\")\n\t\treturn\n\t} \n\tkey := args[1]\n\tcmdArgs := args[2:]\n\th.HandleCmd(key, cmdArgs)\n}\n\nfunc (h *cmdHandler) PrintUsage() {\n}\n\nfunc (h *cmdHandler) HandleCmd(key string, args []string) {\n\tcmd := h.cmds[key]\n\tif cmd == nil {\n\t\th.handleUsageError(\"Unrecognized command: \" + key)\n\t\treturn\n\t}\n\terr := cmd.Execute(args)\n\tif err != nil {\n\t\th.handleError(err)\n\t}\n}\n\n\nfunc (h *cmdHandler) handleUsageError(message string) {\n\tfmt.Println(message)\n\th.PrintUsage()\n}\n\n\nfunc (h *cmdHandler) handleError(err error) {\n\tfmt.Println(err)\n}\n\nfunc NewCmdHandler() CmdHandler ", "output": "{\n\th := initCmdHandler()\n\th.RegisterCmd(NewBuildCmd())\n\treturn h\n}"} {"input": "package gli\n\nimport \"fmt\"\n\nconst _BaseType_name = \"BaseTypeFloatBaseTypeIntBaseTypeUnsignedIntBaseTypeBool\"\n\nvar _BaseType_index = [...]uint8{0, 13, 24, 43, 55}\n\n\n\nfunc (i BaseType) String() string ", "output": "{\n\ti -= 1\n\tif i >= BaseType(len(_BaseType_index)-1) {\n\t\treturn fmt.Sprintf(\"BaseType(%d)\", i+1)\n\t}\n\treturn _BaseType_name[_BaseType_index[i]:_BaseType_index[i+1]]\n}"} {"input": "package chipmunk\n\nimport \"github.com/dataarts/chipmunk/vect\"\n\nconst (\n\terrorBias = 0.00179701029991443 \n)\n\ntype ConstraintCallback interface {\n\tCollisionPreSolve(constraint Constraint)\n\tCollisionPostSolve(constraint Constraint)\n}\n\ntype Constraint interface {\n\tConstraint() *BasicConstraint\n\tPreSolve()\n\tPostSolve()\n\tPreStep(dt vect.Float)\n\tApplyCachedImpulse(dt_coef vect.Float)\n\tApplyImpulse()\n\tImpulse() vect.Float\n}\n\ntype BasicConstraint struct {\n\tBodyA, BodyB *Body\n\tspace *Space\n\tMaxForce vect.Float\n\tErrorBias vect.Float\n\tMaxBias vect.Float\n\tCallbackHandler ConstraintCallback\n\tUserData Data\n}\n\nfunc NewConstraint(a, b *Body) BasicConstraint {\n\treturn BasicConstraint{BodyA: a, BodyB: b, MaxForce: Inf, MaxBias: Inf, ErrorBias: errorBias}\n}\n\nfunc (this *BasicConstraint) Constraint() *BasicConstraint {\n\treturn this\n}\n\nfunc (this *BasicConstraint) PreStep(dt vect.Float) {\n\tpanic(\"empty constraint\")\n}\n\nfunc (this *BasicConstraint) ApplyCachedImpulse(dt_coef vect.Float) {\n\tpanic(\"empty constraint\")\n}\n\n\n\nfunc (this *BasicConstraint) Impulse() vect.Float {\n\tpanic(\"empty constraint\")\n}\n\nfunc (this *BasicConstraint) PreSolve() {\n\tif this.CallbackHandler != nil {\n\t\tthis.CallbackHandler.CollisionPreSolve(this)\n\t}\n}\n\nfunc (this *BasicConstraint) PostSolve() {\n\tif this.CallbackHandler != nil {\n\t\tthis.CallbackHandler.CollisionPostSolve(this)\n\t}\n}\n\nfunc (this *BasicConstraint) ApplyImpulse() ", "output": "{\n\tpanic(\"empty constraint\")\n}"} {"input": "package polymorphichelpers\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\tapi \"k8s.io/kubernetes/pkg/apis/core\"\n\t\"k8s.io/kubernetes/pkg/apis/extensions\"\n)\n\n\n\nfunc getPorts(spec api.PodSpec) []string {\n\tresult := []string{}\n\tfor _, container := range spec.Containers {\n\t\tfor _, port := range container.Ports {\n\t\t\tresult = append(result, strconv.Itoa(int(port.ContainerPort)))\n\t\t}\n\t}\n\treturn result\n}\n\n\nfunc getServicePorts(spec api.ServiceSpec) []string {\n\tresult := []string{}\n\tfor _, servicePort := range spec.Ports {\n\t\tresult = append(result, strconv.Itoa(int(servicePort.Port)))\n\t}\n\treturn result\n}\n\nfunc portsForObject(object runtime.Object) ([]string, error) ", "output": "{\n\tswitch t := object.(type) {\n\tcase *api.ReplicationController:\n\t\treturn getPorts(t.Spec.Template.Spec), nil\n\tcase *api.Pod:\n\t\treturn getPorts(t.Spec), nil\n\tcase *api.Service:\n\t\treturn getServicePorts(t.Spec), nil\n\tcase *extensions.Deployment:\n\t\treturn getPorts(t.Spec.Template.Spec), nil\n\tcase *extensions.ReplicaSet:\n\t\treturn getPorts(t.Spec.Template.Spec), nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"cannot extract ports from %T\", object)\n\t}\n}"} {"input": "package fake\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n\tv1alpha1 \"k8s.io/kops/pkg/client/clientset_generated/clientset/typed/kops/v1alpha1\"\n)\n\ntype FakeKopsV1alpha1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeKopsV1alpha1) Clusters(namespace string) v1alpha1.ClusterInterface {\n\treturn &FakeClusters{c, namespace}\n}\n\nfunc (c *FakeKopsV1alpha1) Federations(namespace string) v1alpha1.FederationInterface {\n\treturn &FakeFederations{c, namespace}\n}\n\n\n\n\n\nfunc (c *FakeKopsV1alpha1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeKopsV1alpha1) InstanceGroups(namespace string) v1alpha1.InstanceGroupInterface ", "output": "{\n\treturn &FakeInstanceGroups{c, namespace}\n}"} {"input": "package main\n import (\n \"fmt\"\n )\n\n \n\n func f() {\n fmt.Println(\"a\")\n panic(\"a bug occur\")\n fmt.Println(\"c\")\n }\n\n func main() {\n g()\n fmt.Println(\"x\")\n }\n\nfunc g() ", "output": "{\n defer func() {\n fmt.Println(\"b\")\n if err := recover();err != nil {\n fmt.Println(err)\n }\n fmt.Println(\"d\")\n }()\n f()\n fmt.Println(\"e\")\n }"} {"input": "package prometheus\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"text/template\"\n\n\t\"github.com/pkg/errors\"\n\n\ttm \"github.com/supergiant/control/pkg/templatemanager\"\n\t\"github.com/supergiant/control/pkg/workflows/steps\"\n)\n\nconst StepName = \"prometheus\"\n\ntype Config struct {\n\tRBACEnabled bool\n}\n\ntype Step struct {\n\tscript *template.Template\n}\n\n\n\nfunc Init() {\n\ttpl, err := tm.GetTemplate(StepName)\n\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"template %s not found\", StepName))\n\t}\n\n\tsteps.RegisterStep(StepName, New(tpl))\n}\n\nfunc New(script *template.Template) *Step {\n\tt := &Step{\n\t\tscript: script,\n\t}\n\n\treturn t\n}\n\nfunc (s *Step) Run(ctx context.Context, out io.Writer, config *steps.Config) error {\n\terr := steps.RunTemplate(ctx, s.script, config.Runner, out, toStepCfg(config))\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"install prometheus step\")\n\t}\n\n\treturn nil\n}\n\nfunc (s *Step) Name() string {\n\treturn StepName\n}\n\nfunc (s *Step) Description() string {\n\treturn \"Install prometheus\"\n}\n\nfunc (s *Step) Depends() []string {\n\treturn nil\n}\n\nfunc toStepCfg(c *steps.Config) Config {\n\treturn Config{\n\t\tRBACEnabled: c.Kube.RBACEnabled,\n\t}\n}\n\nfunc (s *Step) Rollback(context.Context, io.Writer, *steps.Config) error ", "output": "{\n\treturn nil\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n)\n\n\n\n\nfunc Set(key string, value interface{}, dur time.Duration) error {\n\n\tif err := DB.Set(\"cache\", key, value); err != nil {\n\t\treturn err\n\t}\n\n\tif dur.Seconds() > 0 {\n\t\tgo func() {\n\t\t\ttime.Sleep(dur)\n\t\t\tDelete(key)\n\t\t}()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc Get(key string) interface{} {\n\tvar i interface{}\n\n\tDB.Get(\"cache\", key, &i)\n\n\treturn i\n}\n\n\n\n\nfunc Delete(key string) error ", "output": "{\n\treturn DB.Delete(\"cache\", key)\n}"} {"input": "package dlp \n\nimport (\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc/metadata\"\n)\n\n\n\n\nfunc DefaultAuthScopes() []string {\n\treturn []string{\n\t\t\"https:www.googleapis.com/auth/cloud-platform\",\n\t}\n}\n\nfunc insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context ", "output": "{\n\tout, _ := metadata.FromOutgoingContext(ctx)\n\tout = out.Copy()\n\tfor _, md := range mds {\n\t\tfor k, v := range md {\n\t\t\tout[k] = append(out[k], v...)\n\t\t}\n\t}\n\treturn metadata.NewOutgoingContext(ctx, out)\n}"} {"input": "package circular\n\nimport (\n\t\"errors\"\n)\n\n\ntype Buffer struct {\n\tsize int \n\tn int \n\tdata []byte \n\twrite, read int \n}\n\n\nfunc NewBuffer(size int) *Buffer {\n\n\treturn &Buffer{\n\t\tsize: size,\n\t\tdata: make([]byte, size),\n\t}\n}\n\n\n\n\n\nfunc (b *Buffer) WriteByte(c byte) error {\n\tif b.write == b.read && b.n > 0 {\n\t\treturn errors.New(\"buffer is full\")\n\t}\n\tb.Overwrite(c)\n\treturn nil\n}\n\n\nfunc (b *Buffer) Overwrite(c byte) {\n\tif b.read == b.write && b.n > 0 {\n\t\tb.read = (b.read + 1) % b.size\n\t\tb.n--\n\t}\n\tb.data[b.write] = c\n\tb.write = (b.write + 1) % b.size\n\tb.n++\n}\n\n\nfunc (b *Buffer) Reset() {\n\t*b = Buffer{\n\t\tsize: b.size,\n\t\tdata: make([]byte, b.size),\n\t}\n}\n\nfunc (b *Buffer) ReadByte() (byte, error) ", "output": "{\n\tif b.n == 0 {\n\t\treturn 0, errors.New(\"no bytes read\")\n\t}\n\td := b.data[b.read]\n\tb.read = (b.read + 1) % b.size\n\tb.n--\n\treturn d, nil\n}"} {"input": "package naming\n\nimport (\n\t\"github.com/snapcore/snapd/snapdenv\"\n)\n\nvar (\n\tprodWellKnownSnapIDs = map[string]string{\n\t\t\"core\": \"99T7MUlRhtI3U0QFgl5mXXESAiSwt776\",\n\t\t\"snapd\": \"PMrrV4ml8uWuEUDBT8dSGnKUYbevVhc4\",\n\t\t\"core18\": \"CSO04Jhav2yK0uz97cr0ipQRyqg0qQL6\",\n\t\t\"core20\": \"DLqre5XGLbDqg9jPtiAhRRjDuPVa5X1q\",\n\t}\n\n\tstagingWellKnownSnapIDs = map[string]string{\n\t\t\"core\": \"xMNMpEm0COPZy7jq9YRwWVLCD9q5peow\",\n\t\t\"snapd\": \"Z44rtQD1v4r1LXGPCDZAJO3AOw1EDGqy\",\n\t\t\"core18\": \"NhSvwckvNdvgdiVGlsO1vYmi3FPdTZ9U\",\n\t\t\"core20\": \"\",\n\t}\n)\n\nvar wellKnownSnapIDs = prodWellKnownSnapIDs\n\n\n\n\n\nfunc WellKnownSnapID(snapName string) string {\n\treturn wellKnownSnapIDs[snapName]\n}\n\nfunc UseStagingIDs(staging bool) (restore func()) {\n\told := wellKnownSnapIDs\n\tif staging {\n\t\twellKnownSnapIDs = stagingWellKnownSnapIDs\n\t} else {\n\t\twellKnownSnapIDs = prodWellKnownSnapIDs\n\t}\n\treturn func() {\n\t\twellKnownSnapIDs = old\n\t}\n}\n\nfunc init() ", "output": "{\n\tif snapdenv.UseStagingStore() {\n\t\twellKnownSnapIDs = stagingWellKnownSnapIDs\n\t}\n}"} {"input": "package geddit\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\ntype Submission struct {\n\tAuthor string `json:\"author\"`\n\tTitle string `json:\"title\"`\n\tURL string `json:\"url\"`\n\tDomain string `json:\"domain\"`\n\tSubreddit string `json:\"subreddit\"`\n\tSubredditID string `json:\"subreddit_id\"`\n\tFullID string `json:\"name\"`\n\tID string `json:\"id\"`\n\tPermalink string `json:\"permalink\"`\n\tSelftext string `json:\"selftext\"`\n\tThumbnailURL string `json:\"thumbnail\"`\n\tDateCreated float64 `json:\"created_utc\"`\n\tNumComments int `json:\"num_comments\"`\n\tScore int `json:\"score\"`\n\tUps int `json:\"ups\"`\n\tDowns int `json:\"downs\"`\n\tIsNSFW bool `json:\"over_18\"`\n\tIsSelf bool `json:\"is_self\"`\n\tWasClicked bool `json:\"clicked\"`\n\tIsSaved bool `json:\"saved\"`\n\tBannedBy *string `json:\"banned_by\"`\n}\n\nfunc (h Submission) voteID() string { return h.FullID }\n\nfunc (h Submission) replyID() string { return h.FullID }\n\n\nfunc (h *Submission) FullPermalink() string {\n\treturn \"https://reddit.com\" + h.Permalink\n}\n\n\nfunc (h *Submission) String() string {\n\tplural := \"\"\n\tif h.NumComments != 1 {\n\t\tplural = \"s\"\n\t}\n\tcomments := fmt.Sprintf(\"%d comment%s\", h.NumComments, plural)\n\treturn fmt.Sprintf(\"%d - %s (%s)\", h.Score, h.Title, comments)\n}\n\nfunc (h Submission) deleteID() string ", "output": "{ return h.FullID }"} {"input": "package Plugin\n\nimport \"github.com/MPjct/GoMP/MySQLProtocol\"\n\ntype Plugin_interface interface {\n\tinit(context MySQLProtocol.Context)\n\tread_handshake(context MySQLProtocol.Context)\n\tsend_handshake(context MySQLProtocol.Context)\n\tread_auth(context MySQLProtocol.Context)\n\tsend_auth(context MySQLProtocol.Context)\n\tread_auth_result(context MySQLProtocol.Context)\n\tsend_auth_result(context MySQLProtocol.Context)\n\tread_query(context MySQLProtocol.Context)\n\tsend_query(context MySQLProtocol.Context)\n\tread_query_result(context MySQLProtocol.Context)\n\tsend_query_result(context MySQLProtocol.Context)\n\tcleanup(context MySQLProtocol.Context)\n}\n\ntype Plugin struct {\n}\n\nfunc (plugin *Plugin) init(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_handshake(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_handshake(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_auth(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_auth(context MySQLProtocol.Context) {\n\treturn\n}\n\n\n\nfunc (plugin *Plugin) send_auth_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_query(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_query(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_query_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_query_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) cleanup(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_auth_result(context MySQLProtocol.Context) ", "output": "{\n\treturn\n}"} {"input": "package abi\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com/etherbanking/go-etherbanking/crypto\"\n)\n\n\n\n\n\n\n\n\n\ntype Method struct {\n\tName string\n\tConst bool\n\tInputs []Argument\n\tOutputs []Argument\n}\n\n\n\n\n\n\n\n\n\n\nfunc (m Method) Sig() string {\n\ttypes := make([]string, len(m.Inputs))\n\ti := 0\n\tfor _, input := range m.Inputs {\n\t\ttypes[i] = input.Type.String()\n\t\ti++\n\t}\n\treturn fmt.Sprintf(\"%v(%v)\", m.Name, strings.Join(types, \",\"))\n}\n\nfunc (m Method) String() string {\n\tinputs := make([]string, len(m.Inputs))\n\tfor i, input := range m.Inputs {\n\t\tinputs[i] = fmt.Sprintf(\"%v %v\", input.Name, input.Type)\n\t}\n\toutputs := make([]string, len(m.Outputs))\n\tfor i, output := range m.Outputs {\n\t\tif len(output.Name) > 0 {\n\t\t\toutputs[i] = fmt.Sprintf(\"%v \", output.Name)\n\t\t}\n\t\toutputs[i] += output.Type.String()\n\t}\n\tconstant := \"\"\n\tif m.Const {\n\t\tconstant = \"constant \"\n\t}\n\treturn fmt.Sprintf(\"function %v(%v) %sreturns(%v)\", m.Name, strings.Join(inputs, \", \"), constant, strings.Join(outputs, \", \"))\n}\n\nfunc (m Method) Id() []byte {\n\treturn crypto.Keccak256([]byte(m.Sig()))[:4]\n}\n\nfunc (method Method) pack(args ...interface{}) ([]byte, error) ", "output": "{\n\tif len(args) != len(method.Inputs) {\n\t\treturn nil, fmt.Errorf(\"argument count mismatch: %d for %d\", len(args), len(method.Inputs))\n\t}\n\tvar variableInput []byte\n\n\tvar ret []byte\n\tfor i, a := range args {\n\t\tinput := method.Inputs[i]\n\t\tpacked, err := input.Type.pack(reflect.ValueOf(a))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"`%s` %v\", method.Name, err)\n\t\t}\n\n\t\tif input.Type.requiresLengthPrefix() {\n\t\t\toffset := len(method.Inputs)*32 + len(variableInput)\n\t\t\tret = append(ret, packNum(reflect.ValueOf(offset))...)\n\t\t\tvariableInput = append(variableInput, packed...)\n\t\t} else {\n\t\t\tret = append(ret, packed...)\n\t\t}\n\t}\n\tret = append(ret, variableInput...)\n\n\treturn ret, nil\n}"} {"input": "package gumbleffmpeg \n\nimport (\n\t\"io\"\n\t\"os/exec\"\n)\n\n\ntype Source interface {\n\targuments() []string\n\tstart(*exec.Cmd) error\n\tdone()\n}\n\n\n\ntype sourceFile string\n\n\nfunc SourceFile(filename string) Source {\n\treturn sourceFile(filename)\n}\n\nfunc (s sourceFile) arguments() []string {\n\treturn []string{\"-i\", string(s)}\n}\n\nfunc (sourceFile) start(*exec.Cmd) error {\n\treturn nil\n}\n\nfunc (sourceFile) done() {\n}\n\n\n\ntype sourceReader struct {\n\tr io.ReadCloser\n}\n\n\nfunc SourceReader(r io.ReadCloser) Source {\n\treturn &sourceReader{r}\n}\n\nfunc (*sourceReader) arguments() []string {\n\treturn []string{\"-i\", \"-\"}\n}\n\nfunc (s *sourceReader) start(cmd *exec.Cmd) error {\n\tcmd.Stdin = s.r\n\treturn nil\n}\n\nfunc (s *sourceReader) done() {\n\ts.r.Close()\n}\n\n\n\ntype sourceExec struct {\n\tname string\n\targ []string\n\n\tcmd *exec.Cmd\n}\n\n\n\nfunc SourceExec(name string, arg ...string) Source {\n\treturn &sourceExec{\n\t\tname: name,\n\t\targ: arg,\n\t}\n}\n\nfunc (*sourceExec) arguments() []string {\n\treturn []string{\"-i\", \"-\"}\n}\n\nfunc (s *sourceExec) start(cmd *exec.Cmd) error {\n\ts.cmd = exec.Command(s.name, s.arg...)\n\tr, err := s.cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmd.Stdin = r\n\tif err := s.cmd.Start(); err != nil {\n\t\tcmd.Stdin = nil\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\nfunc (s *sourceExec) done() ", "output": "{\n\tif s.cmd != nil {\n\t\tif p := s.cmd.Process; p != nil {\n\t\t\tp.Kill()\n\t\t}\n\t\ts.cmd.Wait()\n\t}\n}"} {"input": "package iso20022\n\n\ntype RepoCallRequestStatus8Choice struct {\n\n\tCode *RepoCallRequestStatus1Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification30 `xml:\"Prtry\"`\n}\n\nfunc (r *RepoCallRequestStatus8Choice) SetCode(value string) {\n\tr.Code = (*RepoCallRequestStatus1Code)(&value)\n}\n\n\n\nfunc (r *RepoCallRequestStatus8Choice) AddProprietary() *GenericIdentification30 ", "output": "{\n\tr.Proprietary = new(GenericIdentification30)\n\treturn r.Proprietary\n}"} {"input": "package cli\n\nimport \"github.com/scaleway/scaleway-cli/pkg/commands\"\n\nvar cmdRm = &Command{\n\tExec: runRm,\n\tUsageLine: \"rm [OPTIONS] SERVER [SERVER...]\",\n\tDescription: \"Remove one or more servers\",\n\tHelp: \"Remove one or more servers.\",\n\tExamples: `\n $ scw rm myserver\n $ scw rm -f myserver\n $ scw rm my-stopped-server my-second-stopped-server\n $ scw rm $(scw ps -q)\n $ scw rm $(scw ps | grep mysql | awk '{print $1}')\n`,\n}\n\n\n\n\nvar rmHelp bool \nvar rmForce bool \n\nfunc runRm(cmd *Command, rawArgs []string) error {\n\tif rmHelp {\n\t\treturn cmd.PrintUsage()\n\t}\n\tif len(rawArgs) < 1 {\n\t\treturn cmd.PrintShortUsage()\n\t}\n\n\targs := commands.RmArgs{\n\t\tServers: rawArgs,\n\t\tForce: rmForce,\n\t}\n\tctx := cmd.GetContext(rawArgs)\n\treturn commands.RunRm(ctx, args)\n}\n\nfunc init() ", "output": "{\n\tcmdRm.Flag.BoolVar(&rmHelp, []string{\"h\", \"-help\"}, false, \"Print usage\")\n\tcmdRm.Flag.BoolVar(&rmForce, []string{\"f\", \"-force\"}, false, \"Force the removal of a server\")\n}"} {"input": "package ipfs\n\n\n\n\nimport (\n\t\"github.com/go-openapi/runtime\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\nfunc New(transport runtime.ClientTransport, formats strfmt.Registry) *Client {\n\treturn &Client{transport: transport, formats: formats}\n}\n\n\ntype Client struct {\n\ttransport runtime.ClientTransport\n\tformats strfmt.Registry\n}\n\n\nfunc (a *Client) ArchiveURL(params *ArchiveURLParams) (*ArchiveURLCreated, error) {\n\tif params == nil {\n\t\tparams = NewArchiveURLParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"archiveUrl\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/archive\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &ArchiveURLReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*ArchiveURLCreated), nil\n\n}\n\n\n\n\nfunc (a *Client) SetTransport(transport runtime.ClientTransport) ", "output": "{\n\ta.transport = transport\n}"} {"input": "package commands\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/asciinema/asciinema/api\"\n)\n\ntype AuthCommand struct {\n\tapi api.API\n}\n\nfunc NewAuthCommand(api api.API) *AuthCommand {\n\treturn &AuthCommand{api}\n}\n\n\n\nfunc (c *AuthCommand) Execute() error ", "output": "{\n\tfmt.Println(\"Open the following URL in a browser to register your API token and assign any recorded asciicasts to your profile:\")\n\tfmt.Println(c.api.AuthUrl())\n\n\treturn nil\n}"} {"input": "package engine\n\nimport \"syscall\"\n\n\ntype windowsFileLock struct {\n\tfd syscall.Handle\n}\n\nfunc (fl *windowsFileLock) release() error {\n\treturn syscall.Close(fl.fd)\n}\n\n\n\nfunc newFileLock(name string) (fileLock, error) ", "output": "{\n\tp, err := syscall.UTF16PtrFromString(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfd, err := syscall.CreateFile(p,\n\t\tsyscall.GENERIC_READ|syscall.GENERIC_WRITE,\n\t\t0, nil, syscall.CREATE_ALWAYS,\n\t\tsyscall.FILE_ATTRIBUTE_NORMAL,\n\t\t0,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &windowsFileLock{fd: fd}, nil\n}"} {"input": "package signals\n\nimport (\n\t\"os\"\n\t\"os/signal\"\n)\n\nvar onlyOneSignalHandler = make(chan struct{})\n\n\n\n\n\n\nfunc SetupSignalHandler() (stopCh <-chan struct{}) ", "output": "{\n\tclose(onlyOneSignalHandler) \n\n\tstop := make(chan struct{})\n\tc := make(chan os.Signal, 2)\n\tsignal.Notify(c, shutdownSignals...)\n\tgo func() {\n\t\t<-c\n\t\tclose(stop)\n\t\t<-c\n\t\tos.Exit(1) \n\t}()\n\n\treturn stop\n}"} {"input": "package main\n\nimport (\n \"errors\"\n \"testing\"\n \"time\"\n\n \"github.com/aws/aws-sdk-go/service/iam\"\n \"github.com/aws/aws-sdk-go/service/iam/iamiface\"\n)\n\n\ntype mockIAMClient struct {\n iamiface.IAMAPI\n}\n\n\n\nfunc TestCreateAccountAlias(t *testing.T) {\n thisTime := time.Now()\n nowString := thisTime.Format(\"2006-01-02 15:04:05 Monday\")\n t.Log(\"Starting unit test at \" + nowString)\n\n \n alias := \"test-alias\"\n\n mockSvc := &mockIAMClient{}\n\n err := MakeAccountAlias(mockSvc, &alias)\n if err != nil {\n t.Fatal(err)\n }\n\n t.Log(\"Created account alias \" + alias)\n}\n\nfunc (m *mockIAMClient) CreateAccountAlias(input *iam.CreateAccountAliasInput) (*iam.CreateAccountAliasOutput, error) ", "output": "{\n \n if input.AccountAlias == nil || *input.AccountAlias == \"\" {\n return nil, errors.New(\"CreateAccountAliasInput.AccountAlias cannot be nil or an empty string\")\n }\n\n resp := iam.CreateAccountAliasOutput{}\n return &resp, nil\n}"} {"input": "package imagick\n\n\nimport \"C\"\nimport (\n\t\"runtime\"\n\t\"sync\"\n\t\"sync/atomic\"\n)\n\nvar (\n\tinitOnce sync.Once\n\tterminateOnce *sync.Once\n\n\tcanTerminate = make(chan struct{}, 1)\n\n\tenvSemaphore = make(chan struct{}, 1)\n\n\tmagickWandCounter int64\n\tdrawingWandCounter int64\n\tpixelIteratorCounter int64\n\tpixelWandCounter int64\n)\n\n\nfunc Initialize() {\n\tenvSemaphore <- struct{}{}\n\tdefer func() {\n\t\t<-envSemaphore\n\t}()\n\n\tinitOnce.Do(func() {\n\t\tC.MagickWandGenesis()\n\t\tterminateOnce = &sync.Once{}\n\t\tsetCanTerminate()\n\t})\n}\n\n\n\nfunc Terminate() {\n\tenvSemaphore <- struct{}{}\n\tdefer func() {\n\t\t<-envSemaphore\n\t}()\n\n\tif terminateOnce != nil {\n\t\tterminateOnce.Do(func() {\n\t\t\truntime.GC()\n\t\t\tterminate()\n\t\t})\n\t}\n}\n\n\n\nfunc terminate() {\n\t<-canTerminate\n\tC.MagickWandTerminus()\n\tinitOnce = sync.Once{}\n}\n\n\n\n\n\nfunc unsetCanTerminate() {\n\tselect {\n\tcase <-canTerminate:\n\tdefault:\n\t}\n}\n\n\nfunc isImageMagickCleaned() bool {\n\tif atomic.LoadInt64(&magickWandCounter) != 0 || atomic.LoadInt64(&drawingWandCounter) != 0 || atomic.LoadInt64(&pixelIteratorCounter) != 0 || atomic.LoadInt64(&pixelWandCounter) != 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc setCanTerminate() ", "output": "{\n\tif isImageMagickCleaned() {\n\t\tselect {\n\t\tcase canTerminate <- struct{}{}:\n\t\tdefault:\n\t\t}\n\t}\n}"} {"input": "package perf\n\nimport (\n\t\"github.com/golang/glog\"\n\t\"net/http\"\n\t\"net/http/pprof\"\n)\n\n\n\n\nfunc Init(pprofBind []string) ", "output": "{\n\tpprofServeMux := http.NewServeMux()\n\tpprofServeMux.HandleFunc(\"/debug/pprof/\", pprof.Index)\n\tpprofServeMux.HandleFunc(\"/debug/pprof/cmdline\", pprof.Cmdline)\n\tpprofServeMux.HandleFunc(\"/debug/pprof/profile\", pprof.Profile)\n\tpprofServeMux.HandleFunc(\"/debug/pprof/symbol\", pprof.Symbol)\n\tfor _, addr := range pprofBind {\n\t\tgo func() {\n\t\t\tif err := http.ListenAndServe(addr, pprofServeMux); err != nil {\n\t\t\t\tglog.Errorf(\"http.ListenAndServe(\\\"%s\\\", pprofServeMux) error(%v)\", addr, err)\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}()\n\t}\n}"} {"input": "package utils\n\nimport (\n\t\"code.google.com/p/goauth2/oauth\"\n\t\"github.com/google/go-github/github\"\n\t\"github.com/pinterb/hsc/config\"\n)\n\n\ntype Utils struct {\n\tclient *github.Client\n\tconfig *config.Config\n\n\tUsers *UserUtils\n}\n\n\ntype Response struct {\n\t*github.Response\n}\n\n\n\n\n\nfunc NewResponse(r *github.Response) *Response {\n\tresp := &Response{Response: r}\n\treturn resp\n}\n\nfunc NewUtils(config *config.Config) *Utils ", "output": "{\n\n\tclient := github.NewClient(nil)\n\tif config != nil {\n\t\tt := &oauth.Transport{\n\t\t\tToken: &oauth.Token{AccessToken: config.Token},\n\t\t}\n\n\t\tclient = github.NewClient(t.Client())\n\t}\n\n\tu := &Utils{config: config, client: client}\n\tu.Users = &UserUtils{Utils: u}\n\n\treturn u\n}"} {"input": "package pop_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/gobuffalo/pop\"\n\t\"github.com/stretchr/testify/require\"\n)\n\n\n\nfunc Test_AddLookupPaths(t *testing.T) {\n\tr := require.New(t)\n\tpop.AddLookupPaths(\"./foo\")\n\tr.Contains(pop.LookupPaths(), \"./foo\")\n}\n\nfunc Test_LoadsConnectionsFromConfig(t *testing.T) ", "output": "{\n\tr := require.New(t)\n\n\tconns := pop.Connections\n\tr.Equal(5, len(conns))\n}"} {"input": "package v1\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n\t\"k8s.io/client-go/pkg/apis/extensions/v1beta1\"\n)\n\nconst (\n\tIotDaemonSetKind = \"IotDaemonSet\"\n\tIotDaemonSetType = \"iotdaemonsets\"\n)\n\ntype IotDaemonSet struct {\n\tmetav1.TypeMeta `json:\",inline\"`\n\tMetadata metav1.ObjectMeta `json:\"metadata,omitempty\"`\n\tSpec v1beta1.DaemonSetSpec `json:\"spec,omitempty\"`\n\tStatus v1beta1.DaemonSetStatus `json:\"status,omitempty\"`\n}\n\ntype IotDaemonSetList struct {\n\tmetav1.TypeMeta `json:\",inline\"`\n\tMetadata metav1.ListMeta `json:\"metadata,omitempty\"`\n\tItems []IotDaemonSet `json:\"items\"`\n}\n\n\n\nfunc (iotDaemonSet *IotDaemonSet) GetObjectMeta() *metav1.ObjectMeta {\n\treturn &iotDaemonSet.Metadata\n}\n\nfunc (iotDaemonSetList *IotDaemonSetList) GetObjectKind() schema.ObjectKind {\n\treturn &iotDaemonSetList.TypeMeta\n}\n\nfunc (iotDaemonSetList *IotDaemonSetList) GetListMeta() metav1.List {\n\treturn &iotDaemonSetList.Metadata\n}\n\nfunc (iotDaemonSet *IotDaemonSet) GetObjectKind() schema.ObjectKind ", "output": "{\n\treturn &iotDaemonSet.TypeMeta\n}"} {"input": "package iso20022\n\n\ntype OriginalItem4 struct {\n\n\tOriginalItemIdentification *Max35Text `xml:\"OrgnlItmId\"`\n\n\tOriginalEndToEndIdentification *Max35Text `xml:\"OrgnlEndToEndId,omitempty\"`\n\n\tAmount *ActiveOrHistoricCurrencyAndAmount `xml:\"Amt\"`\n\n\tExpectedValueDate *ISODate `xml:\"XpctdValDt,omitempty\"`\n\n\tOriginalItemReference *OriginalItemReference3 `xml:\"OrgnlItmRef,omitempty\"`\n}\n\nfunc (o *OriginalItem4) SetOriginalItemIdentification(value string) {\n\to.OriginalItemIdentification = (*Max35Text)(&value)\n}\n\n\n\nfunc (o *OriginalItem4) SetAmount(value, currency string) {\n\to.Amount = NewActiveOrHistoricCurrencyAndAmount(value, currency)\n}\n\nfunc (o *OriginalItem4) SetExpectedValueDate(value string) {\n\to.ExpectedValueDate = (*ISODate)(&value)\n}\n\nfunc (o *OriginalItem4) AddOriginalItemReference() *OriginalItemReference3 {\n\to.OriginalItemReference = new(OriginalItemReference3)\n\treturn o.OriginalItemReference\n}\n\nfunc (o *OriginalItem4) SetOriginalEndToEndIdentification(value string) ", "output": "{\n\to.OriginalEndToEndIdentification = (*Max35Text)(&value)\n}"} {"input": "package local \n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/tiborvass/docker/errdefs\"\n\t\"github.com/pkg/errors\"\n)\n\ntype optsConfig struct{}\n\n\n\nfunc (r *Root) scopedPath(realPath string) bool {\n\tif strings.HasPrefix(realPath, filepath.Join(r.scope, volumesPathName)) && realPath != filepath.Join(r.scope, volumesPathName) {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc setOpts(v *localVolume, opts map[string]string) error {\n\tif len(opts) > 0 {\n\t\treturn errdefs.InvalidParameter(errors.New(\"options are not supported on this platform\"))\n\t}\n\treturn nil\n}\n\nfunc (v *localVolume) needsMount() bool {\n\treturn false\n}\n\nfunc (v *localVolume) mount() error {\n\treturn nil\n}\n\nfunc (v *localVolume) postMount() error {\n\treturn nil\n}\n\n\n\nfunc (v *localVolume) CreatedAt() (time.Time, error) ", "output": "{\n\tfileInfo, err := os.Stat(v.path)\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\tft := fileInfo.Sys().(*syscall.Win32FileAttributeData).CreationTime\n\treturn time.Unix(0, ft.Nanoseconds()), nil\n}"} {"input": "package connectivity\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth\"\n\t\"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials\"\n\n\t\"github.com/denverdino/aliyungo/common\"\n)\n\n\ntype Config struct {\n\tAccessKey string\n\tSecretKey string\n\tRegion common.Region\n\tRegionId string\n\tSecurityToken string\n\tOtsInstanceName string\n\tLogEndpoint string\n\tAccountId string\n\tFcEndpoint string\n\tMNSEndpoint string\n}\n\n\n\nfunc (c *Config) validateRegion() error {\n\n\tfor _, valid := range common.ValidRegions {\n\t\tif c.Region == valid {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"Not a valid region: %s\", c.Region)\n}\n\nfunc (c *Config) getAuthCredential(stsSupported bool) auth.Credential {\n\tif stsSupported {\n\t\treturn credentials.NewStsTokenCredential(c.AccessKey, c.SecretKey, c.SecurityToken)\n\t}\n\n\treturn credentials.NewAccessKeyCredential(c.AccessKey, c.SecretKey)\n}\n\nfunc (c *Config) loadAndValidate() error ", "output": "{\n\terr := c.validateRegion()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package bender\n\nimport (\n\t\"log\"\n\n\t\"github.com/pinterest/bender/hist\"\n)\n\n\ntype Recorder func(interface{})\n\n\nfunc Record(c chan interface{}, recorders ...Recorder) {\n\tfor msg := range c {\n\t\tfor _, recorder := range recorders {\n\t\t\trecorder(msg)\n\t\t}\n\t}\n}\n\nfunc logMessage(l *log.Logger, msg interface{}) {\n\tl.Printf(\"%+v\", msg)\n}\n\n\n\n\n\nfunc NewHistogramRecorder(h *hist.Histogram) Recorder {\n\treturn func(msg interface{}) {\n\t\tswitch msg := msg.(type) {\n\t\tcase *StartEvent:\n\t\t\th.Start(int(msg.Start))\n\t\tcase *EndEvent:\n\t\t\th.End(int(msg.End))\n\t\tcase *EndRequestEvent:\n\t\t\telapsed := int(msg.End - msg.Start)\n\t\t\tif msg.Err == nil {\n\t\t\t\th.Add(elapsed)\n\t\t\t} else {\n\t\t\t\th.AddError(elapsed)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc NewLoggingRecorder(l *log.Logger) Recorder ", "output": "{\n\treturn func(msg interface{}) {\n\t\tlogMessage(l, msg)\n\t}\n}"} {"input": "package cloudformation\n\n\n\ntype AWSKinesisFirehoseDeliveryStream_EncryptionConfiguration struct {\n\n\tKMSEncryptionConfig *AWSKinesisFirehoseDeliveryStream_KMSEncryptionConfig `json:\"KMSEncryptionConfig,omitempty\"`\n\n\tNoEncryptionConfig string `json:\"NoEncryptionConfig,omitempty\"`\n}\n\n\n\n\nfunc (r *AWSKinesisFirehoseDeliveryStream_EncryptionConfiguration) AWSCloudFormationType() string ", "output": "{\n\treturn \"AWS::KinesisFirehose::DeliveryStream.EncryptionConfiguration\"\n}"} {"input": "package config\n\nimport (\n\t\"encoding/xml\"\n)\n\ntype defXMLReader struct {\n\topts ReaderOptions\n}\n\n\nfunc NewXMLReader(opts ...ReaderOptionFunc) Reader {\n\tr := &defXMLReader{}\n\tfor _, o := range opts {\n\t\to(&r.opts)\n\t}\n\treturn r\n}\n\nfunc (p *defXMLReader) Read(model interface{}) error {\n\tdata, err := ReadXMLFile(p.opts.filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ParseXMLConfig(data, model)\n}\n\nfunc (*defXMLReader) Dump(v interface{}) ([]byte, error) {\n\treturn xml.Marshal(v)\n}\n\nfunc (*defXMLReader) ParseData(data []byte, model interface{}) error {\n\treturn ParseXMLConfig(data, model)\n}\n\n\n\n\n\nfunc ParseXMLConfig(data []byte, model interface{}) error {\n\treturn xml.Unmarshal(data, model)\n}\n\nfunc ReadXMLFile(name string) ([]byte, error) ", "output": "{\n\tdata, _, err := filesRepo.Read(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}"} {"input": "package app\n\n\n\n\nimport \"C\"\nimport (\n\t\"runtime\"\n\t\"sync\"\n\n\t\"grate/backend/mobile/event\"\n\t\"grate/backend/mobile/geom\"\n\t\"grate/backend/mobile/gl\"\n)\n\nvar cb Callbacks\n\n\n\n\nfunc onResize(w, h int) {\n\tgeom.PixelsPerPt = 72\n\tgeom.Width = geom.Pt(float32(w)/ geom.PixelsPerPt)\n\tgeom.Height = geom.Pt(float32(h)/ geom.PixelsPerPt)\n\tgl.Viewport(0, 0, w, h);\n}\n\nvar events struct {\n\tsync.Mutex\n\tpending []event.Touch\n}\n\nfunc sendTouch(ty event.TouchType, x, y float32) {\n\tevents.Lock()\n\tevents.pending = append(events.pending, event.Touch{\n\t\tType: ty,\n\t\tLoc: geom.Point{\n\t\t\tX: geom.Pt(float32(x)/ geom.PixelsPerPt),\n\t\t\tY: geom.Pt(float32(y)/ geom.PixelsPerPt),\n\t\t},\n\t})\n\tevents.Unlock()\n}\n\n\nfunc onTouchStart(x, y float32) { sendTouch(event.TouchStart, x, y) }\n\n\nfunc onTouchMove(x, y float32) { sendTouch(event.TouchMove, x, y) }\n\n\nfunc onTouchEnd(x, y float32) { sendTouch(event.TouchEnd, x, y) }\n\nvar started bool\n\n\nfunc onDraw() {\n\tif !started {\n\t\tcb.Start()\n\t\tstarted = true\n\t}\n\n\tevents.Lock()\n\tpending := events.pending\n\tevents.pending = nil\n\tevents.Unlock()\n\n\tfor _, e := range pending {\n\t\tif cb.Touch != nil {\n\t\t\tcb.Touch(e)\n\t\t}\n\t}\n\tif cb.Draw != nil {\n\t\tcb.Draw()\n\t}\n}\n\nfunc run(callbacks Callbacks) ", "output": "{\n\truntime.LockOSThread()\n\tcb = callbacks\n\tC.runApp()\n}"} {"input": "package expr\n\nimport (\n\t\"github.com/grafana/metrictank/api/models\"\n)\n\ntype FuncUnique struct {\n\tin []GraphiteFunc\n}\n\n\n\nfunc (s *FuncUnique) Signature() ([]Arg, []Arg) {\n\treturn []Arg{\n\t\tArgSeriesLists{val: &s.in}}, []Arg{ArgSeriesList{}}\n}\n\nfunc (s *FuncUnique) Context(context Context) Context {\n\treturn context\n}\n\nfunc (s *FuncUnique) Exec(dataMap DataMap) ([]models.Series, error) {\n\tseries, _, err := consumeFuncs(dataMap, s.in)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tseenNames := make(map[string]bool)\n\tvar uniqueSeries []models.Series\n\tfor _, serie := range series {\n\t\tif _, ok := seenNames[serie.Target]; !ok {\n\t\t\tseenNames[serie.Target] = true\n\t\t\tuniqueSeries = append(uniqueSeries, serie)\n\t\t}\n\t}\n\treturn uniqueSeries, nil\n}\n\nfunc NewUnique() GraphiteFunc ", "output": "{\n\treturn &FuncUnique{}\n}"} {"input": "package test_helpers\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\tdatatypes \"github.com/maximilien/softlayer-go/data_types\"\n)\n\ntype MockProductPackageService struct{}\n\nfunc (mock *MockProductPackageService) GetName() string {\n\treturn \"Mock_Product_Package_Service\"\n}\n\nfunc (mock *MockProductPackageService) GetItemsByType(packageType string) ([]datatypes.SoftLayer_Product_Item, error) {\n\tresponse, _ := ReadJsonTestFixtures(\"services\", \"SoftLayer_Product_Package_getItemsByType_virtual_server.json\")\n\n\tproductItems := []datatypes.SoftLayer_Product_Item{}\n\tjson.Unmarshal(response, &productItems)\n\n\treturn productItems, nil\n}\n\nfunc (mock *MockProductPackageService) GetItemPrices(packageId int) ([]datatypes.SoftLayer_Product_Item_Price, error) {\n\treturn []datatypes.SoftLayer_Product_Item_Price{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetItemPricesBySize(packageId int, size int) ([]datatypes.SoftLayer_Product_Item_Price, error) {\n\treturn []datatypes.SoftLayer_Product_Item_Price{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetItems(packageId int) ([]datatypes.SoftLayer_Product_Item, error) {\n\treturn []datatypes.SoftLayer_Product_Item{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetPackagesByType(packageType string) ([]datatypes.Softlayer_Product_Package, error) {\n\treturn []datatypes.Softlayer_Product_Package{}, errors.New(\"Not supported\")\n}\n\n\n\nfunc (mock *MockProductPackageService) GetOnePackageByType(packageType string) (datatypes.Softlayer_Product_Package, error) ", "output": "{\n\treturn datatypes.Softlayer_Product_Package{}, errors.New(\"Not supported\")\n}"} {"input": "package gconv_test\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\ntype testStruct struct {\n\tId int\n\tName string\n}\n\nvar ptr = []*testStruct{\n\t{\n\t\tId: 1,\n\t\tName: \"test1\",\n\t},\n\t{\n\t\tId: 2,\n\t\tName: \"test2\",\n\t},\n}\n\nfunc init() {\n\tfor i := 1; i <= 1000; i++ {\n\t\tptr = append(ptr, &testStruct{\n\t\t\tId: 1,\n\t\t\tName: \"test1\",\n\t\t})\n\t}\n}\n\n\n\nfunc Benchmark_Reflect_ValueOf_Kind(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\treflect.ValueOf(ptr).Kind()\n\t}\n}\n\nfunc Benchmark_Reflect_ValueOf_Interface(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\treflect.ValueOf(ptr).Interface()\n\t}\n}\n\nfunc Benchmark_Reflect_ValueOf_Len(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\treflect.ValueOf(ptr).Len()\n\t}\n}\n\nfunc Benchmark_Reflect_ValueOf(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\treflect.ValueOf(ptr)\n\t}\n}"} {"input": "package json\n\nimport (\n\t\"encoding/json\"\n)\n\nvar nullValue = []byte(\"null\")\n\n\ntype JsonString string\n\nfunc (s JsonString) MarshalJSON() ([]byte, error) {\n\tif s == \"\" {\n\t\treturn nullValue, nil\n\t}\n\n\treturn json.Marshal(string(s))\n}\n\n\ntype RawJsonForm string\n\n\n\nfunc (s RawJsonForm) MarshalJSON() ([]byte, error) ", "output": "{\n\treturn []byte(s), nil\n}"} {"input": "package cmd\n\nimport (\n\t\"github.com/gsamokovarov/jump/cli\"\n\t\"github.com/gsamokovarov/jump/config\"\n)\n\nconst version = \"0.40.0\"\n\nfunc versionCmd(cli.Args, config.Config) error {\n\tcli.Outf(\"%s\\n\", version)\n\n\treturn nil\n}\n\n\n\nfunc init() ", "output": "{\n\tcli.RegisterCommand(\"--version\", \"Show version.\", versionCmd)\n}"} {"input": "package envflags_test\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/goodfoo/envflags\"\n)\n\n\n\n\n\n\nfunc Example() ", "output": "{\n\tflags := envflags.New() \n\n\ti := flags.Int(\"ival\", 1, \"provide and ival as a parameter or env var\")\n\ts := flags.String(\"sval\", \"flags\", \"provide a sval as a parameter or env var\")\n\n\tflags.Bool(\"test.v\", false, \"verbosity\")\n\n\tos.Setenv(\"SVAL\", \"awesome flags!\")\n\n\tflags.Parse()\n\n\tfmt.Printf(\"i = %d\\ns = %s\", *i, *s)\n}"} {"input": "package blockchain\n\n\n\n\n\n\n\n\ntype MemberProvisioningState string\n\nconst (\n\tDeleting MemberProvisioningState = \"Deleting\"\n\tFailed MemberProvisioningState = \"Failed\"\n\tNotSpecified MemberProvisioningState = \"NotSpecified\"\n\tStale MemberProvisioningState = \"Stale\"\n\tSucceeded MemberProvisioningState = \"Succeeded\"\n\tUpdating MemberProvisioningState = \"Updating\"\n)\n\n\nfunc PossibleMemberProvisioningStateValues() []MemberProvisioningState {\n\treturn []MemberProvisioningState{Deleting, Failed, NotSpecified, Stale, Succeeded, Updating}\n}\n\n\ntype NameAvailabilityReason string\n\nconst (\n\tNameAvailabilityReasonAlreadyExists NameAvailabilityReason = \"AlreadyExists\"\n\tNameAvailabilityReasonInvalid NameAvailabilityReason = \"Invalid\"\n\tNameAvailabilityReasonNotSpecified NameAvailabilityReason = \"NotSpecified\"\n)\n\n\nfunc PossibleNameAvailabilityReasonValues() []NameAvailabilityReason {\n\treturn []NameAvailabilityReason{NameAvailabilityReasonAlreadyExists, NameAvailabilityReasonInvalid, NameAvailabilityReasonNotSpecified}\n}\n\n\ntype NodeProvisioningState string\n\nconst (\n\tNodeProvisioningStateDeleting NodeProvisioningState = \"Deleting\"\n\tNodeProvisioningStateFailed NodeProvisioningState = \"Failed\"\n\tNodeProvisioningStateNotSpecified NodeProvisioningState = \"NotSpecified\"\n\tNodeProvisioningStateSucceeded NodeProvisioningState = \"Succeeded\"\n\tNodeProvisioningStateUpdating NodeProvisioningState = \"Updating\"\n)\n\n\n\n\n\ntype Protocol string\n\nconst (\n\tProtocolCorda Protocol = \"Corda\"\n\tProtocolNotSpecified Protocol = \"NotSpecified\"\n\tProtocolParity Protocol = \"Parity\"\n\tProtocolQuorum Protocol = \"Quorum\"\n)\n\n\nfunc PossibleProtocolValues() []Protocol {\n\treturn []Protocol{ProtocolCorda, ProtocolNotSpecified, ProtocolParity, ProtocolQuorum}\n}\n\nfunc PossibleNodeProvisioningStateValues() []NodeProvisioningState ", "output": "{\n\treturn []NodeProvisioningState{NodeProvisioningStateDeleting, NodeProvisioningStateFailed, NodeProvisioningStateNotSpecified, NodeProvisioningStateSucceeded, NodeProvisioningStateUpdating}\n}"} {"input": "package lexer\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc EqualSentences(a, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc AssertNextSentence(l *Lexer, t *testing.T, a []string) {\n\tb, _ := l.NextSentence()\n\n\tif !EqualSentences(a, b) {\n\t\tt.Errorf(\"bad sentence: '%s' VS '%s'\", a, b)\n\t}\n}\n\nfunc TestLexer(t *testing.T) {\n\ts := strings.NewReader(`foo bar; spaces \"and quotes\"; \"es\\\"ca\\\\p e\"`)\n\tz := New(s)\n\n\tAssertNextSentence(z, t, []string{\"foo\", \"bar\"})\n\tAssertNextSentence(z, t, []string{\"spaces\", \"and quotes\"})\n\tAssertNextSentence(z, t, []string{`es\"ca\\p e`})\n}\n\n\n\nfunc TestSplit(t *testing.T) ", "output": "{\n\tss, err := Split(\"foo bar baz\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif len(ss) != 1 {\n\t\tt.Errorf(\"bad result: %s\", ss)\n\t}\n\tif !EqualSentences(ss[0], []string{\"foo\", \"bar\", \"baz\"}) {\n\t\tt.Errorf(\"bad result: %s\", ss)\n\t}\n}"} {"input": "package enumflag\n\nimport \"fmt\"\n\ntype enumFlag struct {\n\ttarget *string\n\toptions []string\n}\n\n\nfunc New(target *string, options ...string) *enumFlag {\n\treturn &enumFlag{target: target, options: options}\n}\n\n\n\nfunc (f *enumFlag) Set(value string) error {\n\tfor _, v := range f.options {\n\t\tif v == value {\n\t\t\t*f.target = value\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"expected one of %q\", f.options)\n}\n\nfunc (f *enumFlag) String() string ", "output": "{\n\treturn *f.target\n}"} {"input": "package aws\n\nimport (\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/helper/resource\"\n)\n\n\n\nconst testAccCheckAwsEcsContainerDefinitionDataSourceConfig = `\nresource \"aws_ecs_cluster\" \"default\" {\n name = \"terraformecstest1\"\n}\n\nresource \"aws_ecs_task_definition\" \"mongo\" {\n family = \"mongodb\"\n container_definitions = <` was not provided\")\n\tc.Check(s.Stdout(), Equals, \"\")\n\tc.Check(s.Stderr(), Equals, \"\")\n}\n\n\n\nfunc (s *SnapKeysSuite) TestDeleteKey(c *C) {\n\trest, err := snap.Parser(snap.Client()).ParseArgs([]string{\"delete-key\", \"another\"})\n\tc.Assert(err, IsNil)\n\tc.Assert(rest, DeepEquals, []string{})\n\tc.Check(s.Stdout(), Equals, \"\")\n\tc.Check(s.Stderr(), Equals, \"\")\n\t_, err = snap.Parser(snap.Client()).ParseArgs([]string{\"keys\", \"--json\"})\n\tc.Assert(err, IsNil)\n\texpectedResponse := []snap.Key{\n\t\t{\n\t\t\tName: \"default\",\n\t\t\tSha3_384: \"g4Pks54W_US4pZuxhgG_RHNAf_UeZBBuZyGRLLmMj1Do3GkE_r_5A5BFjx24ZwVJ\",\n\t\t},\n\t}\n\tvar obtainedResponse []snap.Key\n\tjson.Unmarshal(s.stdout.Bytes(), &obtainedResponse)\n\tc.Check(obtainedResponse, DeepEquals, expectedResponse)\n\tc.Check(s.Stderr(), Equals, \"\")\n}\n\nfunc (s *SnapKeysSuite) TestDeleteKeyNonexistent(c *C) ", "output": "{\n\t_, err := snap.Parser(snap.Client()).ParseArgs([]string{\"delete-key\", \"nonexistent\"})\n\tc.Assert(err, NotNil)\n\tc.Check(err.Error(), Equals, \"cannot find key named \\\"nonexistent\\\" in GPG keyring\")\n\tc.Check(s.Stdout(), Equals, \"\")\n\tc.Check(s.Stderr(), Equals, \"\")\n}"} {"input": "package main\n\nimport (\n\t\"github.com/trasa/watchmud-message\"\n)\n\nfunc (c *Client) handleSayResponse(resp *message.SayResponse) {\n\tif resp.Success {\n\t\tUIPrintf(\"You say '%s'\\n\", resp.Value)\n\t} else {\n\t\tif resp.GetResultCode() == \"NOT_IN_A_ROOM\" {\n\t\t\tUIPrintln(\"You yell into the darkness.\")\n\t\t} else {\n\t\t\tUIPrintResponseError(resp, resp.GetResultCode())\n\t\t}\n\t}\n}\n\n\n\nfunc (c *Client) handleTellNotification(note *message.TellNotification) {\n\tif note.GetSuccess() {\n\t\tUIPrintf(\"%s tells you '%s'.\\n\", note.Sender, note.Value)\n\t} else {\n\t\tUIPrintResponseError(note, note.GetResultCode())\n\t}\n}\n\nfunc (c *Client) handleTellResponse(resp *message.TellResponse) {\n\tif resp.GetSuccess() {\n\t\tUIPrintln(\"sent.\")\n\t} else if resp.GetResultCode() == \"TO_PLAYER_NOT_FOUND\" {\n\t\tUIPrintln(\"Nobody here by that name.\")\n\t} else {\n\t\tUIPrintResponseError(resp, resp.GetResultCode())\n\t}\n}\n\nfunc (c *Client) handleTellAllResponse(resp *message.TellAllResponse) {\n\tif resp.GetSuccess() {\n\t\tUIPrintln(\"sent.\")\n\t} else {\n\t\tUIPrintResponseError(resp, resp.GetResultCode())\n\t}\n}\n\nfunc (c *Client) handleTellAllNotification(note *message.TellAllNotification) {\n\tif note.GetSuccess() {\n\t\tUIPrintf(\"tell_all %s> %s\", note.Sender, note.Value)\n\t} else {\n\t\tUIPrintResponseError(note, note.GetResultCode())\n\t}\n}\n\nfunc (c *Client) handleSayNotification(note *message.SayNotification) ", "output": "{\n\tif note.Success {\n\t\tUIPrintf(\"%s says '%s'.\\n\", note.Sender, note.Value)\n\t} else {\n\t\tUIPrintResponseError(note, note.GetResultCode())\n\t}\n}"} {"input": "package app\n\nimport (\n\t. \"strconv\"\n\t\"time\"\n)\n\ntype User struct {\n\tId int64\n\tNom string\n\tPrenom string\n\tEmail string\n\tPassword string\n\tCreatedAt time.Time\n\tUpdatedAt time.Time\n}\n\n\nfunc (u User) Save() {\n\tdb.Save(&u)\n}\n\n\nfunc (u User) Update() {\n\tdb.First(&u, &u.Id).Update(&u)\n}\n\n\nfunc (u User) Delete() {\n\tdb.Delete(&u)\n}\n\n\n\n\n\n\nfunc (u User) GetList() []User {\n\tvar users []User\n\tdb.Find(&users)\n\treturn users\n}\n\nfunc (u User) GetById() User ", "output": "{\n\tdb.Where(\"id = ?\", Itoa(int(u.Id))).Find(&u)\n\treturn u\n}"} {"input": "package trie\n\nimport (\n\t\"sync\"\n\n\t\"github.com/jellevandenhooff/keytree/crypto\"\n)\n\n\n\nfunc (n *Node) ParallelHash(m int) crypto.Hash ", "output": "{\n\tif n == nil {\n\t\treturn crypto.EmptyHash\n\t}\n\n\twork := []*Node{n}\n\tfor len(work) < m {\n\t\tif work[0].Children[0] == nil || work[0].Children[1] == nil {\n\t\t\tbreak\n\t\t}\n\t\twork = append(work[1:], work[0].Children[0], work[0].Children[1])\n\t}\n\tm = len(work)\n\n\tvar wg sync.WaitGroup\n\twg.Add(m)\n\n\tfor i := 0; i < m; i++ {\n\t\tgo func(i int) {\n\t\t\twork[i].Hash()\n\t\t\twg.Done()\n\t\t}(i)\n\t}\n\n\twg.Wait()\n\n\treturn n.Hash()\n}"} {"input": "package servicecontrol\n\nimport (\n\t\"log\"\n\t\"os\"\n)\n\nvar (\n\tsshServiceName = \"ssh\"\n\tdisableSshFilename = \"/etc/ssh/sshd_not_to_be_run\"\n)\n\ntype SshService struct {\n\tdefaults *ServiceControlSettings\n}\n\nfunc getSshSettings() *ServiceControlSettings {\n\tis_enabled := true\n\tinfo, _ := os.Stat(disableSshFilename)\n\tif info != nil {\n\t\tis_enabled = false\n\t}\n\n\treturn &ServiceControlSettings{\n\t\tEnabled: is_enabled,\n\t}\n}\n\nfunc NewSshService() *SshService {\n\treturn &SshService{\n\t\tdefaults: getSshSettings(),\n\t}\n}\n\nfunc (s *SshService) IsAvailable() bool {\n\treturn true\n}\n\nfunc (s *SshService) GetDefaults() *ServiceControlSettings {\n\treturn s.defaults\n}\n\n\n\nfunc (s *SshService) QuerySettings() (*ServiceControlSettings, error) {\n\treturn getSshSettings(), nil\n}\n\nfunc init() {\n\tRegisterService(\"ssh\", NewSshService())\n}\n\nfunc (s *SshService) ApplySettings(settings *ServiceControlSettings) error ", "output": "{\n\tvar action string\n\trunning, statusErr := isServiceRunning(sshServiceName)\n\tif settings.Enabled {\n\t\tif running && statusErr == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\taction = \"start\"\n\t\tif err := removeFile(disableSshFilename); err != nil {\n\t\t\tlog.Println(\"Could not enable ssh service\", err)\n\t\t}\n\t} else {\n\t\tif !running && statusErr == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\taction = \"stop\"\n\t\tif err := touchFile(disableSshFilename); err != nil {\n\t\t\tlog.Println(\"Could not disable ssh service\", err)\n\t\t}\n\t}\n\n\treturn runServiceCommand(sshServiceName, action)\n}"} {"input": "package v1beta1\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io/api/core/v1\"\n\tpolicy \"k8s.io/api/policy/v1beta1\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n)\n\n\n\ntype PodDisruptionBudgetListerExpansion interface {\n\tGetPodPodDisruptionBudgets(pod *v1.Pod) ([]*policy.PodDisruptionBudget, error)\n}\n\n\n\ntype PodDisruptionBudgetNamespaceListerExpansion interface{}\n\n\n\n\nfunc (s *podDisruptionBudgetLister) GetPodPodDisruptionBudgets(pod *v1.Pod) ([]*policy.PodDisruptionBudget, error) ", "output": "{\n\tvar selector labels.Selector\n\n\tlist, err := s.PodDisruptionBudgets(pod.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar pdbList []*policy.PodDisruptionBudget\n\tfor i := range list {\n\t\tpdb := list[i]\n\t\tselector, err = metav1.LabelSelectorAsSelector(pdb.Spec.Selector)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) {\n\t\t\tcontinue\n\t\t}\n\t\tpdbList = append(pdbList, pdb)\n\t}\n\n\tif len(pdbList) == 0 {\n\t\treturn nil, fmt.Errorf(\"could not find PodDisruptionBudget for pod %s in namespace %s with labels: %v\", pod.Name, pod.Namespace, pod.Labels)\n\t}\n\n\treturn pdbList, nil\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sort\"\n\n\tpb \"github.com/wish/eventmaster/proto\"\n\t\"github.com/pkg/errors\"\n)\n\n\n\nfunc listDC(ctx context.Context, c pb.EventMasterClient) error ", "output": "{\n\tdcs, err := c.GetDCs(ctx, &pb.EmptyRequest{})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"getting dcs\")\n\t}\n\ts := []string{}\n\tfor _, dc := range dcs.Results {\n\t\ts = append(s, dc.DCName)\n\t}\n\tsort.Strings(s)\n\tfor _, t := range s {\n\t\tfmt.Println(t)\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/aodin/volta/config\"\n\t\"github.com/codegangsta/cli\"\n\t\"github.com/codegangsta/envy/lib\"\n\n\t\"github.com/aodin/groupthink/server\"\n)\n\nfunc main() {\n\tenvy.Bootstrap()\n\n\tapp := cli.NewApp()\n\tapp.Name = \"groupthink\"\n\tapp.Usage = \"Start the groupthink server\"\n\tapp.Action = startServer\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName: \"log, l\",\n\t\t\tValue: \"\",\n\t\t\tUsage: \"Sets the log output file path\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"config, c\",\n\t\t\tValue: \"./settings.json\",\n\t\t\tUsage: \"Sets the configuration file\",\n\t\t},\n\t}\n\tapp.Run(os.Args)\n}\n\nfunc startServer(c *cli.Context) {\n\tlogF := c.String(\"log\")\n\tfile := c.String(\"config\")\n\tif logF != \"\" {\n\t\tif err := os.MkdirAll(filepath.Dir(logF), 0776); err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t\tl, err := os.OpenFile(logF, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)\n\t\tif err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t\tdefer l.Close()\n\t\tlog.SetOutput(l)\n\t}\n\tconf := connect(file)\n\tlog.Panic(server.New(conf).ListenAndServe())\n}\n\n\n\nfunc connect(file string) config.Config ", "output": "{\n\tconf, err := config.ParseFile(file)\n\tif err != nil {\n\t\tlog.Panicf(\"groupthink: could not parse configuration: %s\", err)\n\t}\n\treturn conf\n}"} {"input": "package control\n\nimport (\n\t\"context\"\n\t\"sync\"\n)\n\nvar (\n\tBuildSessionConfigs = buildSessionConfigs\n\tComputeDiff = computeDiff\n\tNewPathPolForEnteringAS = newPathPolForEnteringAS\n\tNewPrefixWatcher = newPrefixWatcher\n\n\tCopyPathPolicy = copyPathPolicy\n\tBuildRoutingChains = buildRoutingChains\n)\n\ntype ConjunctionPathPol = conjuctionPathPol\ntype Diff = diff\n\n\n\nfunc (w *GatewayWatcher) RunAllPrefixWatchersOnceForTest(ctx context.Context) {\n\tvar wg sync.WaitGroup\n\tfor _, wi := range w.currentWatchers {\n\t\twi := wi\n\t\twi.prefixWatcher.resetRunMarker()\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\twi.prefixWatcher.Run(ctx)\n\t\t}()\n\t}\n\twg.Wait()\n}\n\nfunc (w *prefixWatcher) resetRunMarker() {\n\tw.runMarkerLock.Lock()\n\tdefer w.runMarkerLock.Unlock()\n\tw.runMarker = false\n}\n\nfunc (w *GatewayWatcher) RunOnce(ctx context.Context) ", "output": "{\n\tw.run(ctx)\n}"} {"input": "package compute_test\n\nimport (\n\t\"context\"\n\n\tcompute \"cloud.google.com/go/compute/apiv1\"\n\t\"google.golang.org/api/iterator\"\n\tcomputepb \"google.golang.org/genproto/googleapis/cloud/compute/v1\"\n)\n\nfunc ExampleNewAcceleratorTypesRESTClient() {\n\tctx := context.Background()\n\tc, err := compute.NewAcceleratorTypesRESTClient(ctx)\n\tif err != nil {\n\t}\n\tdefer c.Close()\n\n\t_ = c\n}\n\nfunc ExampleAcceleratorTypesClient_AggregatedList() {\n\tctx := context.Background()\n\tc, err := compute.NewAcceleratorTypesRESTClient(ctx)\n\tif err != nil {\n\t}\n\tdefer c.Close()\n\n\treq := &computepb.AggregatedListAcceleratorTypesRequest{\n\t}\n\tit := c.AggregatedList(ctx, req)\n\tfor {\n\t\tresp, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t}\n\t\t_ = resp\n\t}\n}\n\n\n\nfunc ExampleAcceleratorTypesClient_List() {\n\tctx := context.Background()\n\tc, err := compute.NewAcceleratorTypesRESTClient(ctx)\n\tif err != nil {\n\t}\n\tdefer c.Close()\n\n\treq := &computepb.ListAcceleratorTypesRequest{\n\t}\n\tit := c.List(ctx, req)\n\tfor {\n\t\tresp, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t}\n\t\t_ = resp\n\t}\n}\n\nfunc ExampleAcceleratorTypesClient_Get() ", "output": "{\n\tctx := context.Background()\n\tc, err := compute.NewAcceleratorTypesRESTClient(ctx)\n\tif err != nil {\n\t}\n\tdefer c.Close()\n\n\treq := &computepb.GetAcceleratorTypeRequest{\n\t}\n\tresp, err := c.Get(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\n\t\"github.com/pkg/errors\"\n)\n\n\ntype User struct {\n\tName string `json:\"name\"`\n\tID string `json:\"id\"`\n\tIP string `json:\"ip,omitempty\"`\n\tAdmin bool `json:\"admin\"`\n\tBlocked bool `json:\"block,omitempty\"`\n\tVerified bool `json:\"verified,omitempty\"`\n}\n\ntype contextKey string\n\n\n\nfunc MustGetUserInfo(r *http.Request) User {\n\tuser, err := GetUserInfo(r)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn user\n}\n\n\n\n\n\nfunc SetUserInfo(r *http.Request, user User) *http.Request {\n\tctx := r.Context()\n\tctx = context.WithValue(ctx, contextKey(\"user\"), user)\n\treturn r.WithContext(ctx)\n}\n\nfunc GetUserInfo(r *http.Request) (user User, err error) ", "output": "{\n\n\tctx := r.Context()\n\tif ctx == nil {\n\t\treturn User{}, errors.New(\"no info about user\")\n\t}\n\tif u, ok := ctx.Value(contextKey(\"user\")).(User); ok {\n\t\treturn u, nil\n\t}\n\n\treturn User{}, errors.New(\"user can't be parsed\")\n}"} {"input": "package ansiwriter\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\ntype Modifier func() string\n\nfunc escapeANSI(code int) string {\n\treturn fmt.Sprintf(\"\\033[%dm\", code)\n}\n\nfunc Bold() string { return escapeANSI(1) }\nfunc Black() string { return escapeANSI(30) }\nfunc Red() string { return escapeANSI(31) }\nfunc Green() string { return escapeANSI(32) }\nfunc Yellow() string { return escapeANSI(33) }\nfunc Blue() string { return escapeANSI(34) }\nfunc Magenta() string { return escapeANSI(35) }\n\nfunc White() string { return escapeANSI(37) }\n\ntype awr struct {\n\tio.Writer\n\tmodifiers []Modifier\n}\n\n\n\n\nfunc New(w io.Writer, mods ...Modifier) io.Writer {\n\treturn awr{w, mods}\n}\n\nfunc (a awr) Write(b []byte) (n int, err error) {\n\tfor _, mod := range a.modifiers {\n\t\ta.Writer.Write([]byte(mod()))\n\t}\n\tn, err = a.Writer.Write(b)\n\t_, _ = a.Writer.Write([]byte(\"\\033[0m\"))\n\treturn\n}\n\nfunc Cyan() string ", "output": "{ return escapeANSI(36) }"} {"input": "package discovery\n\nimport (\n\t\"fmt\"\n\t\"github.com/spencergibb/go-nuvem/util\"\n\t\"github.com/spf13/viper\"\n\t\"net\"\n\t\"strconv\"\n)\n\ntype StaticDiscovery struct {\n\tNamespace string\n\tInstances []string\n}\n\nfunc (s *StaticDiscovery) Configure(namespace string) {\n\tif s.Namespace != \"\" {\n\t\tfmt.Errorf(\"%s already inited: %s\", StaticFactoryKey, s.Namespace)\n\t\treturn\n\t}\n\ts.Namespace = namespace\n\tinstances := viper.GetStringSlice(util.GetStaticRegistryKey(s))\n\tfmt.Printf(\"instances %+v\\n\", instances)\n\ts.Instances = instances\n}\n\nfunc (s *StaticDiscovery) GetIntances() []util.Instance {\n\tinstances := make([]util.Instance, len(s.Instances))\n\n\tfor i, config := range s.Instances {\n\t\thost, portStr, err := net.SplitHostPort(config)\n\n\t\tport, err := strconv.Atoi(portStr)\n\n\t\tprint(err) \n\n\t\tinstances[i] = util.Instance{Host: host, Port: port}\n\t}\n\n\treturn instances\n}\n\nfunc (s *StaticDiscovery) GetNamespace() string {\n\treturn s.Namespace\n}\n\n\n\nvar StaticFactoryKey = \"StaticDiscovery\"\n\nfunc init() {\n\tprintln(\"registering static discovery\")\n\tRegister(StaticFactoryKey, NewStaticDiscovery)\n}\n\nfunc NewStaticDiscovery() Discovery ", "output": "{\n\treturn &StaticDiscovery{}\n}"} {"input": "package utils\n\nfunc Min(a int64, b int64) int64 {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n\n\n\nfunc Max(a int64, b int64) int64 ", "output": "{\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}"} {"input": "package govaluate\n\ntype lexerStream struct {\n\tsource []rune\n\tposition int\n\tlength int\n}\n\n\n\nfunc (l *lexerStream) readCharacter() rune {\n\n\tvar character rune\n\n\tcharacter = l.source[l.position]\n\tl.position++\n\treturn character\n}\n\nfunc (l *lexerStream) rewind(amount int) {\n\tl.position -= amount\n}\n\nfunc (l lexerStream) canRead() bool {\n\treturn l.position < l.length\n}\n\nfunc newLexerStream(source string) *lexerStream ", "output": "{\n\n\tvar ret *lexerStream\n\tvar runes []rune\n\n\tfor _, character := range source {\n\t\trunes = append(runes, character)\n\t}\n\n\tret = new(lexerStream)\n\tret.source = runes\n\tret.length = len(runes)\n\treturn ret\n}"} {"input": "package gohtml\n\nimport \"testing\"\n\nconst (\n\tunformattedHTML = `This is a title.

Line1
Line2


`\n\tformattedHTML = `\n\n \n \n This is a title.\n \n \n \n

\n Line1\n
\n Line2\n

\n
\n \n\n`\n)\n\n\n\nfunc TestFormatBytes(t *testing.T) {\n\tactual := string(FormatBytes([]byte(unformattedHTML)))\n\tif actual != formattedHTML {\n\t\tt.Errorf(\"Invalid result. [expected: %s][actual: %s]\", formattedHTML, actual)\n\t}\n}\n\nfunc TestFormatWithLineNo(t *testing.T) {\n\tactual := FormatWithLineNo(unformattedHTML)\n\texpected := ` 1 \n 2 \n 3 \n 4 \n 5 This is a title.\n 6 \n 7 \n 8 \n 9

\n10 Line1\n11
\n12 Line2\n13

\n14
\n15 \n16 \n17 `\n\tif actual != expected {\n\t\tt.Errorf(\"Invalid result. [expected: %s][actual: %s]\", expected, actual)\n\t}\n}\n\nfunc TestFormat(t *testing.T) ", "output": "{\n\tactual := Format(unformattedHTML)\n\tif actual != formattedHTML {\n\t\tt.Errorf(\"Invalid result. [expected: %s][actual: %s]\", formattedHTML, actual)\n\t}\n}"} {"input": "package namespaces\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n\n\t\"github.com/dotcloud/docker/pkg/term\"\n)\n\ntype TtyTerminal struct {\n\tstdin io.Reader\n\tstdout, stderr io.Writer\n\tmaster *os.File\n\tstate *term.State\n}\n\nfunc (t *TtyTerminal) Resize(h, w int) error {\n\treturn term.SetWinsize(t.master.Fd(), &term.Winsize{Height: uint16(h), Width: uint16(w)})\n}\n\nfunc (t *TtyTerminal) SetMaster(master *os.File) {\n\tt.master = master\n}\n\n\n\n\n\nfunc (t *TtyTerminal) setupWindow(master, parent *os.File) (*term.State, error) {\n\tws, err := term.GetWinsize(parent.Fd())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := term.SetWinsize(master.Fd(), ws); err != nil {\n\t\treturn nil, err\n\t}\n\treturn term.SetRawTerminal(parent.Fd())\n}\n\nfunc (t *TtyTerminal) Close() error {\n\tterm.RestoreTerminal(os.Stdin.Fd(), t.state)\n\treturn t.master.Close()\n}\n\nfunc (t *TtyTerminal) Attach(command *exec.Cmd) error ", "output": "{\n\tgo io.Copy(t.stdout, t.master)\n\tgo io.Copy(t.master, t.stdin)\n\n\tstate, err := t.setupWindow(t.master, os.Stdin)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tt.state = state\n\treturn err\n}"} {"input": "package archive\n\nimport (\n\t\"testing\"\n)\n\nfunc TestCanonicalTarNameForPath(t *testing.T) {\n\tcases := []struct {\n\t\tin, expected string\n\t\tshouldFail bool\n\t}{\n\t\t{\"foo\", \"foo\", false},\n\t\t{\"foo/bar\", \"___\", true}, \n\t\t{`foo\\bar`, \"foo/bar\", false},\n\t\t{`foo\\bar`, \"foo/bar/\", false},\n\t}\n\tfor _, v := range cases {\n\t\tif out, err := canonicalTarNameForPath(v.in); err != nil && !v.shouldFail {\n\t\t\tt.Fatalf(\"cannot get canonical name for path: %s: %v\", v.in, err)\n\t\t} else if v.shouldFail && err == nil {\n\t\t\tt.Fatalf(\"canonical path call should have pailed with error. in=%s out=%s\", v.in, out)\n\t\t} else if !v.shouldFail && out != v.expected {\n\t\t\tt.Fatalf(\"wrong canonical tar name. expected:%s got:%s\", v.expected, out)\n\t\t}\n\t}\n}\n\n\n\nfunc TestCanonicalTarName(t *testing.T) ", "output": "{\n\tcases := []struct {\n\t\tin string\n\t\tisDir bool\n\t\texpected string\n\t}{\n\t\t{\"foo\", false, \"foo\"},\n\t\t{\"foo\", true, \"foo/\"},\n\t\t{`foo\\bar`, false, \"foo/bar\"},\n\t\t{`foo\\bar`, true, \"foo/bar/\"},\n\t}\n\tfor _, v := range cases {\n\t\tif out, err := canonicalTarName(v.in, v.isDir); err != nil {\n\t\t\tt.Fatalf(\"cannot get canonical name for path: %s: %v\", v.in, err)\n\t\t} else if out != v.expected {\n\t\t\tt.Fatalf(\"wrong canonical tar name. expected:%s got:%s\", v.expected, out)\n\t\t}\n\t}\n}"} {"input": "package gnr\n\nimport (\n\t\"math\"\n)\n\ntype FalloffFunc func(ir *InteractionResult) *InteractionResult\ntype FlatShader struct {\n\tObject\n\tFalloffFunc\n}\n\nfunc (fs *FlatShader) RayInteraction(r *Ray) []*InteractionResult {\n\tirs := fs.Object.RayInteraction(r)\n\tirs = InteractionResultSlice(irs).SelectInteractionResult(fs.FalloffFunc)\n\treturn irs\n}\n\n\n\nfunc NewLinearFalloffFunc(lightDir *Vector3f) FalloffFunc ", "output": "{\n\treturn func(ir *InteractionResult) *InteractionResult {\n\t\tcosAngle := VectorProduct(lightDir, ir.Normal) / lightDir.Magnitude() / ir.Normal.Magnitude()\n\t\tangle := math.Acos(cosAngle)\n\t\tir.Color = VLerpCap(0, math.Pi, ColorBlack, ir.Color)(angle)\n\t\treturn ir\n\t}\n}"} {"input": "package binlogplayer\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"vitess.io/vitess/go/sqltypes\"\n)\n\ntype fakeDBClient struct {\n}\n\n\n\nfunc NewFakeDBClient() DBClient {\n\treturn &fakeDBClient{}\n}\n\nfunc (dc *fakeDBClient) DBName() string {\n\treturn \"db\"\n}\n\nfunc (dc *fakeDBClient) Connect() error {\n\treturn nil\n}\n\n\n\nfunc (dc *fakeDBClient) Commit() error {\n\treturn nil\n}\n\nfunc (dc *fakeDBClient) Rollback() error {\n\treturn nil\n}\n\nfunc (dc *fakeDBClient) Close() {\n}\n\nfunc (dc *fakeDBClient) ExecuteFetch(query string, maxrows int) (qr *sqltypes.Result, err error) {\n\tquery = strings.ToLower(query)\n\tswitch {\n\tcase strings.HasPrefix(query, \"insert\"):\n\t\treturn &sqltypes.Result{InsertID: 1}, nil\n\tcase strings.HasPrefix(query, \"update\"):\n\t\treturn &sqltypes.Result{RowsAffected: 1}, nil\n\tcase strings.HasPrefix(query, \"delete\"):\n\t\treturn &sqltypes.Result{RowsAffected: 1}, nil\n\tcase strings.HasPrefix(query, \"select\"):\n\t\tif strings.Contains(query, \"where\") {\n\t\t\treturn sqltypes.MakeTestResult(\n\t\t\t\tsqltypes.MakeTestFields(\n\t\t\t\t\t\"id|state|source\",\n\t\t\t\t\t\"int64|varchar|varchar\",\n\t\t\t\t),\n\t\t\t\t`1|Running|keyspace:\"ks\" shard:\"0\" key_range: `,\n\t\t\t), nil\n\t\t}\n\t\treturn &sqltypes.Result{}, nil\n\tcase strings.HasPrefix(query, \"use\"):\n\t\treturn &sqltypes.Result{}, nil\n\t}\n\treturn nil, fmt.Errorf(\"unexpected: %v\", query)\n}\n\nfunc (dc *fakeDBClient) Begin() error ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"plugin\"\n\n\tgb \"github.com/transitorykris/goldblum\"\n)\n\n\n\n\nfunc (s *Server) DynamicHandler() http.HandlerFunc {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\ts.log.Debugln(r.Method, r.URL.Path, r.RemoteAddr)\n\t\tso, err := s.lookupSO(r.Method, r.URL.Path)\n\t\tif err != nil {\n\t\t\ts.log.Errorln(err)\n\t\t\tgb.Response(w, &gb.EmptyResponse{}, http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\t\tp, err := plugin.Open(so)\n\t\tif err != nil {\n\t\t\ts.log.Errorln(err)\n\t\t\tgb.Response(w, &gb.EmptyResponse{}, http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\thandler, err := p.Lookup(\"Handler\")\n\t\tif err != nil {\n\t\t\ts.log.Errorln(err)\n\t\t\tgb.Response(w, &gb.EmptyResponse{}, http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tg := &gb.Goldblum{\n\t\t\tDB: s.db,\n\t\t\tLog: s.log,\n\t\t}\n\t\thandler.(func(*gb.Goldblum, http.ResponseWriter, *http.Request))(g, w, r)\n\t})\n}\n\nfunc (s *Server) lookupSO(method string, path string) (string, error) ", "output": "{\n\tvar e Endpoint\n\terr := s.db.Get(&e, \"SELECT `id`, `version` FROM endpoint WHERE `method`=? AND `path`=?\", method, path)\n\tso := fmt.Sprintf(\"/%d/%d-%d.so\", e.ID, e.ID, e.Version)\n\ts.log.Infoln(\"SO is at\", so)\n\treturn so, err\n}"} {"input": "package assertions\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"os/exec\"\n)\n\n\n\nfunc NewSimpleTempDir(prefix string) string {\n\tdirpath, err := ioutil.TempDir(\".\", prefix)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn dirpath\n}\n\nfunc SimpleTempFile(dirpath string) *os.File {\n\n\tf, err := ioutil.TempFile(dirpath, \"diff_file_\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn f\n}\n\nfunc Diffb(a string, b string) []byte ", "output": "{\n\n\tdirpath := NewSimpleTempDir(\"diffdir_\")\n\tdefer os.RemoveAll(dirpath)\n\n\tfa := SimpleTempFile(dirpath)\n\tfmt.Fprintf(fa, \"%s\\n\", a)\n\tfa.Close()\n\n\tfb := SimpleTempFile(dirpath)\n\tfmt.Fprintf(fb, \"%s\\n\", b)\n\tfb.Close()\n\n\tco, err := exec.Command(\"diff\", \"-b\", fa.Name(), fb.Name()).CombinedOutput()\n\tif err != nil {\n\t}\n\treturn co\n}"} {"input": "package iso20022\n\n\ntype FinancialInstrumentDetails24 struct {\n\n\tFinancialInstrumentIdentification *SecurityIdentification19 `xml:\"FinInstrmId\"`\n\n\tFinancialInstrumentAttributes *FinancialInstrumentAttributes63 `xml:\"FinInstrmAttrbts,omitempty\"`\n\n\tSubBalance []*IntraPositionDetails40 `xml:\"SubBal\"`\n}\n\nfunc (f *FinancialInstrumentDetails24) AddFinancialInstrumentIdentification() *SecurityIdentification19 {\n\tf.FinancialInstrumentIdentification = new(SecurityIdentification19)\n\treturn f.FinancialInstrumentIdentification\n}\n\nfunc (f *FinancialInstrumentDetails24) AddFinancialInstrumentAttributes() *FinancialInstrumentAttributes63 {\n\tf.FinancialInstrumentAttributes = new(FinancialInstrumentAttributes63)\n\treturn f.FinancialInstrumentAttributes\n}\n\n\n\nfunc (f *FinancialInstrumentDetails24) AddSubBalance() *IntraPositionDetails40 ", "output": "{\n\tnewValue := new(IntraPositionDetails40)\n\tf.SubBalance = append(f.SubBalance, newValue)\n\treturn newValue\n}"} {"input": "package midi\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype TimeSignature struct {\n\tNumerator uint8\n\tDenominator uint8\n\tClocksPerTick uint8\n\tThirtySecondNotesPerQuarter uint8\n}\n\n\n\n\nfunc (ts *TimeSignature) String() string {\n\treturn fmt.Sprintf(\"%d/%d - %d clocks per tick - %d\", ts.Numerator, ts.Denum(), ts.ClocksPerTick, ts.ThirtySecondNotesPerQuarter)\n}\n\nfunc (ts *TimeSignature) Denum() int ", "output": "{\n\treturn int(math.Exp2(float64(ts.Denominator)))\n}"} {"input": "package utils\n\nimport (\n\t\"os\"\n)\n\n\n\nfunc DirExist(path string) bool {\n\tstat, err := os.Stat(path)\n\treturn err == nil || os.IsExist(err) || stat.IsDir()\n}\n\nfunc FileExist(filename string) bool ", "output": "{\n\tstat, err := os.Stat(filename)\n\treturn err == nil || os.IsExist(err) || (!stat.IsDir())\n}"} {"input": "package actor\n\nfunc NewRestartingStrategy() SupervisorStrategy {\n\treturn &restartingStrategy{}\n}\n\ntype restartingStrategy struct{}\n\n\n\nfunc (strategy *restartingStrategy) HandleFailure(actorSystem *ActorSystem, supervisor Supervisor, child *PID, rs *RestartStatistics, reason interface{}, message interface{}) ", "output": "{\n\tlogFailure(actorSystem, child, reason, RestartDirective)\n\tsupervisor.RestartChildren(child)\n}"} {"input": "package testutils\n\n\ntype BlockingRW struct{ nilChan chan struct{} }\n\nfunc (rw *BlockingRW) Read(p []byte) (n int, err error) {\n\t<-rw.nilChan\n\treturn\n}\n\nfunc (rw *BlockingRW) Write(p []byte) (n int, err error) {\n\t<-rw.nilChan\n\treturn\n}\n\n\ntype NoopRW struct{}\n\nfunc (rw *NoopRW) Read(p []byte) (n int, err error) {\n\treturn len(p), nil\n}\n\n\n\nfunc (rw *NoopRW) Write(p []byte) (n int, err error) ", "output": "{\n\treturn len(p), nil\n}"} {"input": "package chipmunk\n\nimport \"github.com/dataarts/chipmunk/vect\"\n\nconst (\n\terrorBias = 0.00179701029991443 \n)\n\ntype ConstraintCallback interface {\n\tCollisionPreSolve(constraint Constraint)\n\tCollisionPostSolve(constraint Constraint)\n}\n\ntype Constraint interface {\n\tConstraint() *BasicConstraint\n\tPreSolve()\n\tPostSolve()\n\tPreStep(dt vect.Float)\n\tApplyCachedImpulse(dt_coef vect.Float)\n\tApplyImpulse()\n\tImpulse() vect.Float\n}\n\ntype BasicConstraint struct {\n\tBodyA, BodyB *Body\n\tspace *Space\n\tMaxForce vect.Float\n\tErrorBias vect.Float\n\tMaxBias vect.Float\n\tCallbackHandler ConstraintCallback\n\tUserData Data\n}\n\nfunc NewConstraint(a, b *Body) BasicConstraint {\n\treturn BasicConstraint{BodyA: a, BodyB: b, MaxForce: Inf, MaxBias: Inf, ErrorBias: errorBias}\n}\n\nfunc (this *BasicConstraint) Constraint() *BasicConstraint {\n\treturn this\n}\n\nfunc (this *BasicConstraint) PreStep(dt vect.Float) {\n\tpanic(\"empty constraint\")\n}\n\nfunc (this *BasicConstraint) ApplyCachedImpulse(dt_coef vect.Float) {\n\tpanic(\"empty constraint\")\n}\n\nfunc (this *BasicConstraint) ApplyImpulse() {\n\tpanic(\"empty constraint\")\n}\n\nfunc (this *BasicConstraint) Impulse() vect.Float {\n\tpanic(\"empty constraint\")\n}\n\n\n\nfunc (this *BasicConstraint) PostSolve() {\n\tif this.CallbackHandler != nil {\n\t\tthis.CallbackHandler.CollisionPostSolve(this)\n\t}\n}\n\nfunc (this *BasicConstraint) PreSolve() ", "output": "{\n\tif this.CallbackHandler != nil {\n\t\tthis.CallbackHandler.CollisionPreSolve(this)\n\t}\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n)\n\nfunc Commafy(i interface{}) string {\n\tvar n int64\n\tswitch i.(type) {\n\tcase int:\n\t\tn = int64(i.(int))\n\tcase int64:\n\t\tn = i.(int64)\n\tcase int32:\n\t\tn = int64(i.(int32))\n\t}\n\tif n > 1000 {\n\t\tr := n % 1000\n\t\tn = n / 1000\n\t\treturn fmt.Sprintf(\"%s,%03d\", Commafy(n), r)\n\t}\n\treturn fmt.Sprintf(\"%d\", n)\n}\n\n\n\nfunc PercSuffix(i float64) string {\n\tswitch int(i*100) % 10 {\n\tcase 1:\n\t\treturn \"st\"\n\tcase 2:\n\t\treturn \"nd\"\n\tcase 3:\n\t\treturn \"rd\"\n\t}\n\treturn \"th\"\n}\n\nfunc NanoSecondToHuman(v float64) string {\n\tvar suffix string\n\tswitch {\n\tcase v > 1000000000:\n\t\tv /= 1000000000\n\t\tsuffix = \"s\"\n\tcase v > 1000000:\n\t\tv /= 1000000\n\t\tsuffix = \"ms\"\n\tcase v > 1000:\n\t\tv /= 1000\n\t\tsuffix = \"us\"\n\tdefault:\n\t\tsuffix = \"ns\"\n\t}\n\treturn fmt.Sprintf(\"%0.1f%s\", v, suffix)\n}\n\nfunc FloatToPercent(i float64) string ", "output": "{\n\treturn fmt.Sprintf(\"%.0f\", i*100.0)\n}"} {"input": "package models\n\nimport \"testing\"\n\nfunc TestGetEntityName(t *testing.T) {\n\t_, err := GetEntityName(2)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n}\n\n\nfunc TestGetSystemName(t *testing.T) {\n\t_, err := GetSystemName(30000001)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n}\n\nfunc TestGetCelestialName(t *testing.T) {\n\t_, err := GetCelestialName(30000001)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n}\n\nfunc TestGetTypeName(t *testing.T) ", "output": "{\n\t_, err := GetTypeName(2)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n}"} {"input": "package sol\n\n\ntype Operator interface {\n\tWrap(string) string \n}\n\n\nfunc Function(name string, col Columnar) ColumnElem {\n\treturn col.Column().AddOperator(FuncClause{Name: name})\n}\n\n\nfunc Avg(col Columnar) ColumnElem {\n\treturn Function(AVG, col)\n}\n\n\nfunc Count(col Columnar) ColumnElem {\n\treturn Function(COUNT, col)\n}\n\n\nfunc Date(col Columnar) ColumnElem {\n\treturn Function(DATE, col)\n}\n\n\n\nfunc DatePart(part string, col Columnar) ColumnElem {\n\treturn col.Column().AddOperator(\n\t\tFuncClause{Name: DATEPART},\n\t).AddOperator(\n\t\tArrayClause{clauses: []Clause{String(part)}, post: true, sep: \", \"},\n\t)\n}\n\n\nfunc Max(col Columnar) ColumnElem {\n\treturn Function(MAX, col)\n}\n\n\nfunc Min(col Columnar) ColumnElem {\n\treturn Function(MIN, col)\n}\n\n\n\n\n\nfunc Sum(col Columnar) ColumnElem {\n\treturn Function(SUM, col)\n}\n\n\nfunc Variance(col Columnar) ColumnElem {\n\treturn Function(VARIANCE, col)\n}\n\nfunc StdDev(col Columnar) ColumnElem ", "output": "{\n\treturn Function(STDDEV, col)\n}"} {"input": "package local\n\nimport (\n\t\"context\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/grafana/loki/pkg/storage/chunk\"\n)\n\ntype TableClient struct {\n\tdirectory string\n}\n\n\n\n\nfunc (c *TableClient) ListTables(ctx context.Context) ([]string, error) {\n\tboltDbFiles := []string{}\n\terr := filepath.Walk(c.directory, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !info.IsDir() {\n\t\t\tboltDbFiles = append(boltDbFiles, info.Name())\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn boltDbFiles, nil\n}\n\nfunc (c *TableClient) CreateTable(ctx context.Context, desc chunk.TableDesc) error {\n\tfile, err := os.OpenFile(filepath.Join(c.directory, desc.Name), os.O_CREATE|os.O_RDONLY, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn file.Close()\n}\n\nfunc (c *TableClient) DeleteTable(ctx context.Context, name string) error {\n\treturn os.Remove(filepath.Join(c.directory, name))\n}\n\nfunc (c *TableClient) DescribeTable(ctx context.Context, name string) (desc chunk.TableDesc, isActive bool, err error) {\n\treturn chunk.TableDesc{\n\t\tName: name,\n\t}, true, nil\n}\n\nfunc (c *TableClient) UpdateTable(ctx context.Context, current, expected chunk.TableDesc) error {\n\treturn nil\n}\n\nfunc (*TableClient) Stop() {}\n\nfunc NewTableClient(directory string) (chunk.TableClient, error) ", "output": "{\n\treturn &TableClient{directory: directory}, nil\n}"} {"input": "package log\n\nimport \"gopkg.in/inconshreveable/log15.v2\"\n\nvar (\n\tLogger log15.Logger\n)\n\n\n\n\n\nfunc Interactive() {\n\tLogger.SetHandler(log15.MultiHandler(\n\t\tlog15.LvlFilterHandler(\n\t\t\tlog15.LvlError,\n\t\t\tlog15.StderrHandler)))\n}\n\n\nfunc Debug(msg string, ctx ...interface{}) { Logger.Debug(msg, ctx...) }\nfunc Info(msg string, ctx ...interface{}) { Logger.Info(msg, ctx...) }\nfunc Warn(msg string, ctx ...interface{}) { Logger.Warn(msg, ctx...) }\nfunc Error(msg string, ctx ...interface{}) { Logger.Error(msg, ctx...) }\nfunc Crit(msg string, ctx ...interface{}) { Logger.Crit(msg, ctx...) }\n\nfunc init() ", "output": "{\n\tLogger = log15.New()\n\tLogger.SetHandler(log15.DiscardHandler())\n}"} {"input": "package eureka\n\nimport (\n\t\"encoding/xml\"\n\t\"strings\"\n)\n\nfunc (c *Client) GetApplications() (*Applications, error) {\n\tresponse, err := c.Get(\"apps\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar applications *Applications = new(Applications)\n\terr = xml.Unmarshal(response.Body, applications)\n\treturn applications, err\n}\n\n\n\nfunc (c *Client) GetInstance(appId, instanceId string) (*InstanceInfo, error) {\n\tvalues := []string{\"apps\", appId, instanceId}\n\tpath := strings.Join(values, \"/\")\n\tresponse, err := c.Get(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar instance *InstanceInfo = new(InstanceInfo)\n\terr = xml.Unmarshal(response.Body, instance)\n\treturn instance, err\n}\n\nfunc (c *Client) GetVIP(vipId string) (*Applications, error) {\n\tvalues := []string{\"vips\", vipId}\n\tpath := strings.Join(values, \"/\")\n\tresponse, err := c.Get(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar applications *Applications = new(Applications)\n\terr = xml.Unmarshal(response.Body, applications)\n\treturn applications, err\n}\n\nfunc (c *Client) GetSVIP(svipId string) (*Applications, error) {\n\tvalues := []string{\"svips\", svipId}\n\tpath := strings.Join(values, \"/\")\n\tresponse, err := c.Get(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar applications *Applications = new(Applications)\n\terr = xml.Unmarshal(response.Body, applications)\n\treturn applications, err\n}\n\nfunc (c *Client) GetApplication(appId string) (*Application, error) ", "output": "{\n\tvalues := []string{\"apps\", appId}\n\tpath := strings.Join(values, \"/\")\n\tresponse, err := c.Get(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar application *Application = new(Application)\n\terr = xml.Unmarshal(response.Body, application)\n\treturn application, err\n}"} {"input": "package cli\n\n\ntype Command struct {\n\tName string\n\tDescription string\n\tAction Action\n}\n\n\ntype Commands []*Command\n\n\nfunc (c Commands) Len() int {\n\treturn len(c)\n}\n\n\n\n\n\nfunc (c Commands) Swap(i, j int) {\n\tc[i], c[j] = c[j], c[i]\n}\n\nfunc (c Commands) ActionForName(name string) Action {\n\tfor _, command := range c {\n\t\tif name == command.Name {\n\t\t\treturn command.Action\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (c Commands) Less(i, j int) bool ", "output": "{\n\treturn c[i].Name < c[j].Name\n}"} {"input": "package api\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"github.com/nordsieck/defect\"\n)\n\nconst (\n\tPlaylistItems = \"https://www.googleapis.com/youtube/v3/playlistItems\"\n\n\tKey = \"key\"\n\tPart = \"part\"\n\tContentDetails = \"contentDetails\"\n\tPlaylistID = \"playlistId\"\n\tMaxResults = \"maxResults\"\n\tPageToken = \"pageToken\"\n\n\tErrDeserializeInput = defect.Error(\"Unable to deserialize input\")\n\n\tMaxPlaylistItems = \"50\" \n)\n\n\n\nfunc PlaylistVideos(key, playlist string) ([]string, error) {\n\tfullList := []string{}\n\n\ttoken := \"\"\n\tfor {\n\t\tvar list []string\n\t\tvar err error\n\t\tlist, token, err = GetPlaylistFragment(key, playlist, token)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfullList = append(fullList, list...)\n\t\tif token == \"\" {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn fullList, nil\n}\n\nfunc GetPlaylistFragment(key, playlist, token string) (videoIDs []string, pageToken string, e error) ", "output": "{\n\tparams := url.Values{\n\t\tKey: {key},\n\t\tPart: {ContentDetails},\n\t\tPlaylistID: {playlist},\n\t\tMaxResults: {MaxPlaylistItems},\n\t}\n\tif token != \"\" {\n\t\tparams[PageToken] = []string{token}\n\t}\n\tresp, err := http.Get(PlaylistItems + \"?\" + params.Encode())\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\tpl, err := DeserializePlaylist(resp.Body)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\treturn pl.VideoIDs(), pl.NextPageToken, nil\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/hyperledger/fabric/common/channelconfig\"\n\tab \"github.com/hyperledger/fabric/protos/orderer\"\n)\n\n\ntype Orderer struct {\n\tConsensusTypeVal string\n\tBatchSizeVal *ab.BatchSize\n\tBatchTimeoutVal time.Duration\n\tKafkaBrokersVal []string\n\tMaxChannelsCountVal uint64\n\tOrganizationsVal map[string]channelconfig.Org\n\tCapabilitiesVal channelconfig.OrdererCapabilities\n}\n\n\nfunc (scm *Orderer) ConsensusType() string {\n\treturn scm.ConsensusTypeVal\n}\n\n\nfunc (scm *Orderer) BatchSize() *ab.BatchSize {\n\treturn scm.BatchSizeVal\n}\n\n\nfunc (scm *Orderer) BatchTimeout() time.Duration {\n\treturn scm.BatchTimeoutVal\n}\n\n\nfunc (scm *Orderer) KafkaBrokers() []string {\n\treturn scm.KafkaBrokersVal\n}\n\n\n\n\n\nfunc (scm *Orderer) Organizations() map[string]channelconfig.Org {\n\treturn scm.OrganizationsVal\n}\n\n\nfunc (scm *Orderer) Capabilities() channelconfig.OrdererCapabilities {\n\treturn scm.CapabilitiesVal\n}\n\n\ntype OrdererCapabilities struct {\n\tSupportedErr error\n\n\tSetChannelModPolicyDuringCreateVal bool\n\n\tResubmissionVal bool\n}\n\n\nfunc (oc *OrdererCapabilities) Supported() error {\n\treturn oc.SupportedErr\n}\n\n\nfunc (oc *OrdererCapabilities) SetChannelModPolicyDuringCreate() bool {\n\treturn oc.SetChannelModPolicyDuringCreateVal\n}\n\n\nfunc (oc *OrdererCapabilities) Resubmission() bool {\n\treturn oc.ResubmissionVal\n}\n\nfunc (scm *Orderer) MaxChannelsCount() uint64 ", "output": "{\n\treturn scm.MaxChannelsCountVal\n}"} {"input": "package types\n\n\n\n\nimport (\n\t\"github.com/jcmturner/gofork/encoding/asn1\"\n)\n\n\n\n\nfunc NewKrbFlags() asn1.BitString {\n\tf := asn1.BitString{}\n\tf.Bytes = make([]byte, 4)\n\tf.BitLength = len(f.Bytes) * 8\n\treturn f\n}\n\n\nfunc SetFlags(f *asn1.BitString, j []int) {\n\tfor _, i := range j {\n\t\tSetFlag(f, i)\n\t}\n}\n\n\nfunc SetFlag(f *asn1.BitString, i int) {\n\tfor l := len(f.Bytes); l < 4; l++ {\n\t\t(*f).Bytes = append((*f).Bytes, byte(0))\n\t\t(*f).BitLength = len((*f).Bytes) * 8\n\t}\n\tb := i / 8\n\tp := uint(7 - (i - 8*b))\n\t(*f).Bytes[b] = (*f).Bytes[b] | (1 << p)\n}\n\n\nfunc UnsetFlags(f *asn1.BitString, j []int) {\n\tfor _, i := range j {\n\t\tUnsetFlag(f, i)\n\t}\n}\n\n\nfunc UnsetFlag(f *asn1.BitString, i int) {\n\tfor l := len(f.Bytes); l < 4; l++ {\n\t\t(*f).Bytes = append((*f).Bytes, byte(0))\n\t\t(*f).BitLength = len((*f).Bytes) * 8\n\t}\n\tb := i / 8\n\tp := uint(7 - (i - 8*b))\n\t(*f).Bytes[b] = (*f).Bytes[b] &^ (1 << p)\n}\n\n\n\n\nfunc IsFlagSet(f *asn1.BitString, i int) bool ", "output": "{\n\tb := i / 8\n\tp := uint(7 - (i - 8*b))\n\tif (*f).Bytes[b]&(1< 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\nfunc (m *OpenpitrixCreateReleaseRequest) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\n\n\nfunc (m *OpenpitrixCreateReleaseRequest) UnmarshalBinary(b []byte) error ", "output": "{\n\tvar res OpenpitrixCreateReleaseRequest\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}"} {"input": "package datasource\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/golang/glog\"\n\tcadvisorClient \"github.com/google/cadvisor/client\"\n\tcadvisor \"github.com/google/cadvisor/info/v1\"\n\t\"k8s.io/heapster/sources/api\"\n)\n\ntype cadvisorSource struct{}\n\nfunc (self *cadvisorSource) parseStat(containerInfo *cadvisor.ContainerInfo) *api.Container {\n\tcontainer := &api.Container{\n\t\tName: containerInfo.Name,\n\t\tSpec: containerInfo.Spec,\n\t\tStats: sampleContainerStats(containerInfo.Stats),\n\t}\n\tif len(containerInfo.Aliases) > 0 {\n\t\tcontainer.Name = containerInfo.Aliases[0]\n\t}\n\n\treturn container\n}\n\n\n\nfunc (self *cadvisorSource) GetAllContainers(host Host, start, end time.Time) (subcontainers []*api.Container, root *api.Container, err error) {\n\turl := fmt.Sprintf(\"http:%s:%d/\", host.IP, host.Port)\n\tclient, err := cadvisorClient.NewClient(url)\n\tif err != nil {\n\t\treturn\n\t}\n\tsubcontainers, root, err = self.getAllContainers(client, start, end)\n\tif err != nil {\n\t\tglog.Errorf(\"failed to get stats from cadvisor %q - %v\\n\", url, err)\n\t}\n\treturn\n}\n\nfunc (self *cadvisorSource) getAllContainers(client *cadvisorClient.Client, start, end time.Time) (subcontainers []*api.Container, root *api.Container, err error) ", "output": "{\n\tallContainers, err := client.SubcontainersInfo(\"/\",\n\t\t&cadvisor.ContainerInfoRequest{Start: start, End: end})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tfor _, containerInfo := range allContainers {\n\t\tcontainer := self.parseStat(&containerInfo)\n\t\tif containerInfo.Name == \"/\" {\n\t\t\troot = container\n\t\t} else {\n\t\t\tsubcontainers = append(subcontainers, container)\n\t\t}\n\t}\n\n\treturn subcontainers, root, nil\n}"} {"input": "package networkloadbalancer\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ChangeNetworkLoadBalancerCompartmentRequest struct {\n\n\tNetworkLoadBalancerId *string `mandatory:\"true\" contributesTo:\"path\" name:\"networkLoadBalancerId\"`\n\n\tChangeNetworkLoadBalancerCompartmentDetails `contributesTo:\"body\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ChangeNetworkLoadBalancerCompartmentRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ChangeNetworkLoadBalancerCompartmentRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request ChangeNetworkLoadBalancerCompartmentRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request ChangeNetworkLoadBalancerCompartmentRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype ChangeNetworkLoadBalancerCompartmentResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response ChangeNetworkLoadBalancerCompartmentResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response ChangeNetworkLoadBalancerCompartmentResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package widgets\n\nimport (\n\t\"strings\"\n\n\t\"github.com/ambientsound/pms/songlist\"\n\t\"github.com/ambientsound/pms/style\"\n\t\"github.com/gdamore/tcell\"\n\t\"github.com/gdamore/tcell/views\"\n)\n\ntype ColumnheadersWidget struct {\n\tcolumns songlist.Columns\n\tview views.View\n\n\tstyle.Styled\n\tviews.WidgetWatchers\n}\n\nfunc NewColumnheadersWidget() (c *ColumnheadersWidget) {\n\tc = &ColumnheadersWidget{}\n\tc.columns = make(songlist.Columns, 0)\n\treturn\n}\n\nfunc (c *ColumnheadersWidget) SetColumns(cols songlist.Columns) {\n\tc.columns = cols\n}\n\n\n\nfunc (c *ColumnheadersWidget) SetView(v views.View) {\n\tc.view = v\n}\n\nfunc (c *ColumnheadersWidget) Size() (int, int) {\n\tx, y := c.view.Size()\n\ty = 1\n\treturn x, y\n}\n\nfunc (w *ColumnheadersWidget) Resize() {\n}\n\nfunc (w *ColumnheadersWidget) HandleEvent(ev tcell.Event) bool {\n\treturn false\n}\n\nfunc (c *ColumnheadersWidget) Draw() ", "output": "{\n\tx := 0\n\ty := 0\n\tfor i := range c.columns {\n\t\tcol := c.columns[i]\n\t\ttitle := []rune(strings.Title(col.Tag()))\n\t\tp := 0\n\t\tfor _, r := range title {\n\t\t\tc.view.SetContent(x+p, y, r, nil, c.Style(\"header\"))\n\t\t\tp++\n\t\t}\n\t\tx += col.Width()\n\t}\n}"} {"input": "package client\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n\t\"os\"\n)\n\nfunc dump(v interface{}) {\n\tencodeJSON(os.Stdout, v)\n}\n\n\n\nfunc encodeJSON(w io.Writer, v interface{}) ", "output": "{\n\tenc := json.NewEncoder(w)\n\n\tenc.SetIndent(\"\", \" \")\n\n\tenc.Encode(v)\n}"} {"input": "package filehash\n\nimport (\n\t\"crypto/sha1\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/cloudfoundry/gofileutils/fileutils\"\n)\n\ntype Hash []byte\n\nfunc Zero() Hash {\n\treturn Hash(make([]byte, sha1.Size))\n}\n\n\nfunc New(filePath string) Hash {\n\tfileInfo, err := os.Lstat(filePath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif fileInfo.IsDir() {\n\t\tpanic(\"cannot compute hash of directory\")\n\t} else {\n\t\thash := sha1.New()\n\t\terr = fileutils.CopyPathToWriter(filePath, hash)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn Hash(hash.Sum(nil))\n\t}\n}\n\nfunc (k Hash) String() string {\n\treturn fmt.Sprintf(\"%x\", string(k))\n}\n\n\n\nfunc (h1 Hash) Combine(h2 Hash) {\n\tif len(h1) != len(h2) {\n\t\tpanic(\"Invalid hash length\")\n\t}\n\tfor i, b := range h1 {\n\t\th1[i] = b ^ h2[i]\n\t}\n}\n\nfunc (h1 Hash) Remove(h2 Hash) {\n\th1.Combine(h2)\n}\n\nfunc StringToHash(s string) Hash ", "output": "{\n\tvar sh string\n\tif _, err := fmt.Sscanf(s, \"%x\", &sh); err != nil {\n\t\tpanic(err)\n\t}\n\treturn Hash(sh)\n}"} {"input": "package cmd\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/spf13/cobra\"\n\n\t\"k8s.io/kubernetes/pkg/kubectl\"\n\tcmdutil \"k8s.io/kubernetes/pkg/kubectl/cmd/util\"\n)\n\nconst (\n\tserviceAccountLong = `\nCreate a service account with the specified name.`\n\n\tserviceAccountExample = ` # Create a new service account named my-service-account\n $ kubectl create serviceaccount my-service-account`\n)\n\n\n\n\n\nfunc CreateServiceAccount(f *cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error {\n\tname, err := NameFromCommandArgs(cmd, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar generator kubectl.StructuredGenerator\n\tswitch generatorName := cmdutil.GetFlagString(cmd, \"generator\"); generatorName {\n\tcase cmdutil.ServiceAccountV1GeneratorName:\n\t\tgenerator = &kubectl.ServiceAccountGeneratorV1{Name: name}\n\tdefault:\n\t\treturn cmdutil.UsageError(cmd, fmt.Sprintf(\"Generator: %s not supported.\", generatorName))\n\t}\n\treturn RunCreateSubcommand(f, cmd, cmdOut, &CreateSubcommandOptions{\n\t\tName: name,\n\t\tStructuredGenerator: generator,\n\t\tDryRun: cmdutil.GetFlagBool(cmd, \"dry-run\"),\n\t\tOutputFormat: cmdutil.GetFlagString(cmd, \"output\"),\n\t})\n}\n\nfunc NewCmdCreateServiceAccount(f *cmdutil.Factory, cmdOut io.Writer) *cobra.Command ", "output": "{\n\tcmd := &cobra.Command{\n\t\tUse: \"serviceaccount NAME [--dry-run]\",\n\t\tAliases: []string{\"sa\"},\n\t\tShort: \"Create a service account with the specified name.\",\n\t\tLong: serviceAccountLong,\n\t\tExample: serviceAccountExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\terr := CreateServiceAccount(f, cmdOut, cmd, args)\n\t\t\tcmdutil.CheckErr(err)\n\t\t},\n\t}\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddGeneratorFlags(cmd, cmdutil.ServiceAccountV1GeneratorName)\n\treturn cmd\n}"} {"input": "package glacier\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"github.com/rdwilliamson/aws\"\n)\n\n\ntype Connection struct {\n\tClient *http.Client\n\n\tSignature *aws.Signature\n}\n\nfunc (c *Connection) client() *http.Client {\n\tif c.Client == nil {\n\t\treturn http.DefaultClient\n\t}\n\treturn c.Client\n}\n\n\nfunc (c *Connection) vault(vault string) string {\n\treturn \"https://\" + c.Signature.Region.Glacier + \"/-/vaults/\" + vault\n}\n\n\nfunc (c *Connection) policy(policy string) string {\n\treturn \"https://\" + c.Signature.Region.Glacier + \"/-/policies/\" + policy\n}\n\n\n\n\n\n\n\n\nfunc toHex(x []byte) string {\n\treturn fmt.Sprintf(\"%x\", x)\n}\n\n\n\ntype parameters url.Values\n\n\n\nfunc (p parameters) add(key, value string) {\n\turl.Values(p).Add(key, value)\n}\n\n\n\nfunc (p parameters) encode() string {\n\tif encoded := url.Values(p).Encode(); encoded != \"\" {\n\t\treturn \"?\" + encoded\n\t}\n\treturn \"\"\n}\n\nfunc NewConnection(secret, access string, r *aws.Region) *Connection ", "output": "{\n\treturn &Connection{\n\t\tSignature: aws.NewSignature(secret, access, r, \"glacier\"),\n\t}\n}"} {"input": "package nom\n\nimport (\n\t\"encoding/gob\"\n\t\"fmt\"\n)\n\n\nconst (\n\tPortFlood UID = \"Ports.PortBcast\"\n\tPortAll UID = \"Ports.PortAll\"\n)\n\n\ntype PacketIn struct {\n\tNode UID\n\tInPort UID\n\tBufferID PacketBufferID\n\tPacket Packet\n}\n\n\n\n\ntype PacketOut struct {\n\tNode UID\n\tInPort UID\n\tBufferID PacketBufferID\n\tPacket Packet\n\tActions []Action\n}\n\n\ntype Packet []byte\n\n\nfunc (p Packet) DstMAC() MACAddr {\n\treturn MACAddr{p[0], p[1], p[2], p[3], p[4], p[5]}\n}\n\n\nfunc (p Packet) SrcMAC() MACAddr {\n\treturn MACAddr{p[6], p[7], p[8], p[9], p[10], p[11]}\n}\n\n\n\n\ntype PacketBufferID uint32\n\nfunc init() {\n\tgob.Register(Packet{})\n\tgob.Register(PacketBufferID(0))\n\tgob.Register(PacketIn{})\n\tgob.Register(PacketOut{})\n}\n\nfunc (in PacketIn) String() string ", "output": "{\n\treturn fmt.Sprintf(\"packet in on switch %s port %s\", in.Node, in.InPort)\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\n\t\"sigs.k8s.io/yaml\"\n)\n\n\n\n\nfunc DumpJSON(r interface{}) string ", "output": "{\n\tout, err := yaml.Marshal(r)\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"!!!!!\\nUnable to stringify %T: %v\\n!!!!!\", r, err)\n\t}\n\treturn string(out)\n}"} {"input": "package db\n\nimport (\n\t\"hg/messages\"\n\t\"fmt\"\n\t\"gopkg.in/mgo.v2\"\n)\n\nconst (\n\tmongoURL = \"127.0.0.1:27017\"\n)\n\nfunc persist(operation string,historyEntry messages.HistoryMessage) {\n\tfmt.Println(\"Do db operation\")\n\tsession, err := mgo.Dial(mongoURL)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer session.Close()\n\n\thistoryCollection := session.DB(\"historys\").C(\"history\")\n\n\tswitch operation {\n\tcase \"Insert\":\n\t\terr = historyCollection.Insert(historyEntry)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Can't insert document: %v\\n\", err)\n\t\t\tpanic(err)\n\t\t}\n\tcase \"Update\":\n\t\tfmt.Println(\"Update method is not supported yet!\")\n\tcase \"Delete\":\n\t\tfmt.Println(\"Delete method is not supported yet!\")\n\tcase \"Put\":\n\t\tfmt.Println(\"Put method is not supported yet!\")\n\t}\n}\n\n\n\nfunc RecordHistory(historyEntry messages.HistoryMessage)", "output": "{\n\tfmt.Println(\"Start to record history object\")\n\tpersist(\"Insert\",historyEntry)\n}"} {"input": "package v1\n\n\n\ntype PodAffinityApplyConfiguration struct {\n\tRequiredDuringSchedulingIgnoredDuringExecution []PodAffinityTermApplyConfiguration `json:\"requiredDuringSchedulingIgnoredDuringExecution,omitempty\"`\n\tPreferredDuringSchedulingIgnoredDuringExecution []WeightedPodAffinityTermApplyConfiguration `json:\"preferredDuringSchedulingIgnoredDuringExecution,omitempty\"`\n}\n\n\n\n\n\n\n\n\nfunc (b *PodAffinityApplyConfiguration) WithRequiredDuringSchedulingIgnoredDuringExecution(values ...*PodAffinityTermApplyConfiguration) *PodAffinityApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRequiredDuringSchedulingIgnoredDuringExecution\")\n\t\t}\n\t\tb.RequiredDuringSchedulingIgnoredDuringExecution = append(b.RequiredDuringSchedulingIgnoredDuringExecution, *values[i])\n\t}\n\treturn b\n}\n\n\n\n\nfunc (b *PodAffinityApplyConfiguration) WithPreferredDuringSchedulingIgnoredDuringExecution(values ...*WeightedPodAffinityTermApplyConfiguration) *PodAffinityApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPreferredDuringSchedulingIgnoredDuringExecution\")\n\t\t}\n\t\tb.PreferredDuringSchedulingIgnoredDuringExecution = append(b.PreferredDuringSchedulingIgnoredDuringExecution, *values[i])\n\t}\n\treturn b\n}\n\nfunc PodAffinity() *PodAffinityApplyConfiguration ", "output": "{\n\treturn &PodAffinityApplyConfiguration{}\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strconv\"\n)\n\nfunc main() {\n\n\tif len(os.Args) == 1 {\n\t\tfmt.Println(\"Please provide either a file path or a number input\")\n\n\t} else {\n\n\t\tinput := os.Args[1]\n\t\tfile, err := os.Open(input)\n\n\t\tif check(err) == false {\n\t\t\tdefer file.Close()\n\n\t\t\treader := bufio.NewReader(file)\n\t\t\tscanner := bufio.NewScanner(reader)\n\n\t\t\tfor scanner.Scan() {\n\t\t\t\tvalue := scanner.Text()\n\t\t\t\tif value == \"#\" {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tvalue = cleanString(value)\n\n\t\t\t\tnum := stringToInt(value)\n\t\t\t\tif num <= 15 {\n\t\t\t\t\tfmt.Println(factorial(num))\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else if check(err) == true {\n\t\t\tintInput := stringToInt(input)\n\n\t\t\toutput := factorial(intInput)\n\t\t\tfmt.Println(output)\n\n\t\t}\n\n\t}\n\n}\n\n\n\nfunc stringToInt(input string) int64 {\n\tresult, _ := strconv.ParseInt(input, 10, 0)\n\treturn result\n}\n\nfunc check(e error) bool {\n\tif e != nil {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc cleanString(value string) (result string) {\n\n\tr := regexp.MustCompile(`\\d+`)\n\tmatches := r.FindAllString(value, -1)\n\n\tfor _, value := range matches {\n\t\tresult += value\n\t}\n\n\treturn\n}\n\nfunc factorial(number int64) (factor int64) ", "output": "{\n\tfactor = 1\n\n\tif number == 1 {\n\t\treturn\n\t} else {\n\n\t\tvar counter int64 = 1\n\n\t\tfor i := counter; i <= number; i++ {\n\t\t\tfactor = factor * i\n\t\t}\n\t\treturn\n\t}\n\n\treturn\n}"} {"input": "package common\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n\n\t\"github.com/axgle/mahonia\"\n\t\"github.com/saintfish/chardet\"\n)\n\n\nfunc RequestURL(url string) (*http.Response, error) {\n\tclient := &http.Client{}\n\treq, _ := http.NewRequest(\"GET\", url, nil)\n\treq.Header.Set(\"User-Agent\", GetUserAgent())\n\tresponse, err := client.Do(req)\n\treturn response, err\n}\n\n\nfunc QuickestURL(index int, url string) int {\n\t_, err := http.Get(url)\n\tif err != nil {\n\t\treturn -1\n\t}\n\treturn index\n}\n\n\nfunc DetectBody(body []byte) string {\n\tvar bodyString string\n\tdetector := chardet.NewTextDetector()\n\tresult, err := detector.DetectBest(body)\n\tif err != nil {\n\t\treturn string(body)\n\t}\n\tif strings.Contains(strings.ToLower(result.Charset), \"utf\") {\n\t\tbodyString = string(body)\n\t} else {\n\t\tbodyString = mahonia.NewDecoder(\"gbk\").ConvertString(string(body))\n\t}\n\treturn bodyString\n}\n\n\nfunc StringInSlice(domain string, list []string) bool {\n\tfor _, eachDomain := range list {\n\t\tif domain == eachDomain {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\n\nfunc ReturnDomain(currentURL string) string ", "output": "{\n\turlParse, _ := url.Parse(currentURL)\n\tdomain := urlParse.Host\n\treturn domain\n}"} {"input": "package model\n\n\ntype Weight struct {\n\ttime int\n\trequirements map[*Reward]int\n}\n\n\n\n\n\nfunc (weight *Weight) Requirements() map[*Reward]int {\n\treturn weight.requirements\n}\n\n\nfunc (weight *Weight) AddRequirement(reward *Reward, quantity int) {\n\tweight.requirements[reward] = quantity\n}\n\n\nfunc CreateWeight(time int) *Weight {\n\tweight := new(Weight)\n\tweight.time = time\n\tweight.requirements = make(map[*Reward]int)\n\treturn weight\n}\n\n\ntype ByTime []*Weight\n\n\nfunc (a ByTime) Len() int {\n\treturn len(a)\n}\n\n\nfunc (a ByTime) Swap(i, j int) {\n\ta[i], a[j] = a[j], a[i]\n}\n\n\nfunc (a ByTime) Less(i, j int) bool {\n\treturn a[i].Time() < a[j].Time()\n}\n\nfunc (weight *Weight) Time() int ", "output": "{\n\treturn weight.time\n}"} {"input": "package apimachinery\n\nimport \"github.com/onsi/ginkgo\"\n\n\n\n\nfunc SIGDescribe(text string, body func()) bool ", "output": "{\n\treturn ginkgo.Describe(\"[sig-api-machinery] \"+text, body)\n}"} {"input": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/dhrapson/resembleio/configure\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\nvar defaultYamlFileName = \"resemble.yml\"\n\nfunc main() {\n\targsWithoutProg := os.Args[1:]\n\tconfigYaml, err := GetConfigData(argsWithoutProg)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(\"Starting Resemble...\")\n\tserviceType, err := configure.ConfigureService(configYaml)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tfmt.Println(\"Configuring Resemble as\", serviceType.Name(), \"...\")\n\tserviceType.Configure()\n\tfmt.Println(\"Starting Resemble Service...\")\n\tserviceType.Serve()\n\tfmt.Println(\"Stopping Resemble Service...\")\n}\n\n\n\nfunc getFileContent(name string) (content string, err error) {\n\tfilename, _ := filepath.Abs(name)\n\tconfigYaml, err := ioutil.ReadFile(filename)\n\treturn string(configYaml), err\n}\n\nfunc fileExists(name string) bool {\n\tif _, err := os.Stat(name); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc GetConfigData(cmdLineArgs []string) (configYaml string, err error) ", "output": "{\n\tvar yamlFileName string\n\n\tif len(cmdLineArgs) > 0 && len(cmdLineArgs[0]) > 0 {\n\t\tyamlFileName = cmdLineArgs[0]\n\t\tif !fileExists(yamlFileName) {\n\t\t\treturn \"\", errors.New(yamlFileName + \" cannot be found\")\n\t\t}\n\t\tfmt.Println(\"Using provided config file \" + yamlFileName)\n\t\tconfigYaml, err = getFileContent(yamlFileName)\n\t} else if fileExists(defaultYamlFileName) {\n\t\tfmt.Println(\"Using default config file \" + defaultYamlFileName)\n\t\tconfigYaml, err = getFileContent(defaultYamlFileName)\n\t} else {\n\t\tfmt.Println(\"No config file available, initializing empty. You may configure via API\")\n\t}\n\treturn configYaml, err\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSDynamoDBTable_TimeToLiveSpecification struct {\n\n\tAttributeName string `json:\"AttributeName,omitempty\"`\n\n\tEnabled bool `json:\"Enabled\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) AWSCloudFormationType() string {\n\treturn \"AWS::DynamoDB::Table.TimeToLiveSpecification\"\n}\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\n\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSDynamoDBTable_TimeToLiveSpecification) Metadata() map[string]interface{} ", "output": "{\n\treturn r._metadata\n}"} {"input": "package cleaner\n\nimport (\n\t\"github.com/juju/juju/state\"\n)\n\ntype Patcher interface {\n\tPatchValue(ptr, value interface{})\n}\n\n\n\nfunc PatchState(p Patcher, st StateInterface) ", "output": "{\n\tp.PatchValue(&getState, func(*state.State) StateInterface {\n\t\treturn st\n\t})\n}"} {"input": "package reporters\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/onsi/ginkgo/config\"\n\t\"github.com/onsi/ginkgo/types\"\n\t\"k8s.io/klog/v2\"\n)\n\n\n\n\ntype DetailsReporter struct {\n\tWriter io.Writer\n}\n\n\n\nfunc NewDetailsReporterWithWriter(w io.Writer) *DetailsReporter {\n\treturn &DetailsReporter{\n\t\tWriter: w,\n\t}\n}\n\n\n\nfunc NewDetailsReporterFile(filename string) *DetailsReporter {\n\tabsPath, err := filepath.Abs(filename)\n\tif err != nil {\n\t\tklog.Errorf(\"%#v\\n\", err)\n\t\tpanic(err)\n\t}\n\tf, err := os.Create(absPath)\n\tif err != nil {\n\t\tklog.Errorf(\"%#v\\n\", err)\n\t\tpanic(err)\n\t}\n\treturn NewDetailsReporterWithWriter(f)\n}\n\n\nfunc (reporter *DetailsReporter) SpecSuiteWillBegin(cfg config.GinkgoConfigType, summary *types.SuiteSummary) {\n}\n\n\nfunc (reporter *DetailsReporter) SpecSuiteDidEnd(summary *types.SuiteSummary) {}\n\n\n\n\n\nfunc (reporter *DetailsReporter) SpecWillRun(specSummary *types.SpecSummary) {}\n\n\nfunc (reporter *DetailsReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) {}\n\n\nfunc (reporter *DetailsReporter) AfterSuiteDidRun(setupSummary *types.SetupSummary) {\n\tif c, ok := reporter.Writer.(io.Closer); ok {\n\t\tc.Close()\n\t}\n}\n\nfunc (reporter *DetailsReporter) SpecDidComplete(specSummary *types.SpecSummary) ", "output": "{\n\tb, err := json.Marshal(specSummary)\n\tif err != nil {\n\t\tklog.Errorf(\"Error in detail reporter: %v\", err)\n\t\treturn\n\t}\n\t_, err = reporter.Writer.Write(b)\n\tif err != nil {\n\t\tklog.Errorf(\"Error saving test details in detail reporter: %v\", err)\n\t\treturn\n\t}\n\t_, err = fmt.Fprintln(reporter.Writer, \"\")\n\tif err != nil {\n\t\tklog.Errorf(\"Error saving test details in detail reporter: %v\", err)\n\t\treturn\n\t}\n}"} {"input": "package system \n\nimport (\n\t\"bufio\"\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\n\n\n\n\n\n\nfunc parseMemInfo(reader io.Reader) (*MemInfo, error) {\n\tmeminfo := &MemInfo{}\n\tscanner := bufio.NewScanner(reader)\n\tmemAvailable := int64(-1)\n\tfor scanner.Scan() {\n\t\tparts := strings.Fields(scanner.Text())\n\n\t\tif len(parts) < 3 || parts[2] != \"kB\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tsize, err := strconv.Atoi(parts[1])\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tbytes := int64(size) * 1024\n\n\t\tswitch parts[0] {\n\t\tcase \"MemTotal:\":\n\t\t\tmeminfo.MemTotal = bytes\n\t\tcase \"MemFree:\":\n\t\t\tmeminfo.MemFree = bytes\n\t\tcase \"MemAvailable:\":\n\t\t\tmemAvailable = bytes\n\t\tcase \"SwapTotal:\":\n\t\t\tmeminfo.SwapTotal = bytes\n\t\tcase \"SwapFree:\":\n\t\t\tmeminfo.SwapFree = bytes\n\t\t}\n\n\t}\n\tif memAvailable != -1 {\n\t\tmeminfo.MemFree = memAvailable\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn meminfo, nil\n}\n\nfunc ReadMemInfo() (*MemInfo, error) ", "output": "{\n\tfile, err := os.Open(\"/proc/meminfo\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\treturn parseMemInfo(file)\n}"} {"input": "package test\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/pilosa/pilosa\"\n)\n\n\nfunc NewCluster(n int) *pilosa.Cluster {\n\tc := pilosa.NewCluster()\n\tc.ReplicaN = 1\n\tc.Hasher = NewModHasher()\n\n\tfor i := 0; i < n; i++ {\n\t\tc.Nodes = append(c.Nodes, &pilosa.Node{\n\t\t\tScheme: \"http\",\n\t\t\tHost: fmt.Sprintf(\"host%d\", i),\n\t\t})\n\t}\n\n\treturn c\n}\n\n\ntype ModHasher struct{}\n\n\nfunc NewModHasher() *ModHasher { return &ModHasher{} }\n\nfunc (*ModHasher) Hash(key uint64, n int) int { return int(key) % n }\n\n\ntype ConstHasher struct {\n\ti int\n}\n\n\nfunc NewConstHasher(i int) *ConstHasher { return &ConstHasher{i: i} }\n\n\n\nfunc (h *ConstHasher) Hash(key uint64, n int) int ", "output": "{ return h.i }"} {"input": "package common\n\nimport (\n\t\"fmt\"\n\n\tv3 \"github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3\"\n\t\"github.com/rancher/rancher/pkg/ref\"\n\t\"github.com/sirupsen/logrus\"\n)\n\nfunc GetRuleID(groupID string, ruleName string) string {\n\treturn fmt.Sprintf(\"%s_%s\", groupID, ruleName)\n}\n\nfunc GetGroupID(namespace, name string) string {\n\treturn fmt.Sprintf(\"%s:%s\", namespace, name)\n}\n\n\n\nfunc GetAlertManagerDaemonsetName(appName string) string {\n\treturn fmt.Sprintf(\"alertmanager-%s\", appName)\n}\n\nfunc formatProjectDisplayName(projectDisplayName, projectID string) string {\n\treturn fmt.Sprintf(\"%s (ID: %s)\", projectDisplayName, projectID)\n}\n\nfunc formatClusterDisplayName(clusterDisplayName, clusterID string) string {\n\treturn fmt.Sprintf(\"%s (ID: %s)\", clusterDisplayName, clusterID)\n}\n\nfunc GetClusterDisplayName(clusterName string, clusterLister v3.ClusterLister) string {\n\tcluster, err := clusterLister.Get(\"\", clusterName)\n\tif err != nil {\n\t\tlogrus.Warnf(\"Failed to get cluster for %s: %v\", clusterName, err)\n\t\treturn clusterName\n\t}\n\n\treturn formatClusterDisplayName(cluster.Spec.DisplayName, clusterName)\n}\n\nfunc GetProjectDisplayName(projectID string, projectLister v3.ProjectLister) string {\n\tclusterName, projectName := ref.Parse(projectID)\n\tproject, err := projectLister.Get(clusterName, projectName)\n\tif err != nil {\n\t\tlogrus.Warnf(\"Failed to get project %s: %v\", projectID, err)\n\t\treturn projectID\n\t}\n\n\treturn formatProjectDisplayName(project.Spec.DisplayName, projectID)\n}\n\nfunc GetAlertManagerSecretName(appName string) string ", "output": "{\n\treturn fmt.Sprintf(\"alertmanager-%s\", appName)\n}"} {"input": "package gcetasks\n\nimport (\n\t\"encoding/json\"\n\n\t\"k8s.io/kops/upup/pkg/fi\"\n)\n\n\n\n\ntype realAddress Address\n\n\n\n\nvar _ fi.HasLifecycle = &Address{}\n\n\nfunc (o *Address) GetLifecycle() *fi.Lifecycle {\n\treturn o.Lifecycle\n}\n\n\nfunc (o *Address) SetLifecycle(lifecycle fi.Lifecycle) {\n\to.Lifecycle = &lifecycle\n}\n\nvar _ fi.HasName = &Address{}\n\n\nfunc (o *Address) GetName() *string {\n\treturn o.Name\n}\n\n\nfunc (o *Address) SetName(name string) {\n\to.Name = &name\n}\n\n\nfunc (o *Address) String() string {\n\treturn fi.TaskAsString(o)\n}\n\nfunc (o *Address) UnmarshalJSON(data []byte) error ", "output": "{\n\tvar jsonName string\n\tif err := json.Unmarshal(data, &jsonName); err == nil {\n\t\to.Name = &jsonName\n\t\treturn nil\n\t}\n\n\tvar r realAddress\n\tif err := json.Unmarshal(data, &r); err != nil {\n\t\treturn err\n\t}\n\t*o = Address(r)\n\treturn nil\n}"} {"input": "package model\n\nimport (\n\t\"fmt\"\n\tnative_time \"time\"\n)\n\n\n\n\n\n\n\n\ntype Timestamp int64\n\nconst (\n\tMinimumTick = native_time.Second\n\tsecond = int64(native_time.Second / MinimumTick)\n)\n\n\nfunc (t Timestamp) Equal(o Timestamp) bool {\n\treturn t == o\n}\n\n\nfunc (t Timestamp) Before(o Timestamp) bool {\n\treturn t < o\n}\n\n\nfunc (t Timestamp) After(o Timestamp) bool {\n\treturn t > o\n}\n\n\nfunc (t Timestamp) Add(d native_time.Duration) Timestamp {\n\treturn t + Timestamp(d/MinimumTick)\n}\n\n\n\n\n\nfunc (t Timestamp) Time() native_time.Time {\n\treturn native_time.Unix(int64(t)/second, (int64(t) % second))\n}\n\n\n\nfunc (t Timestamp) Unix() int64 {\n\treturn int64(t) / second\n}\n\n\nfunc (t Timestamp) String() string {\n\treturn fmt.Sprint(int64(t))\n}\n\n\nfunc Now() Timestamp {\n\treturn TimestampFromTime(native_time.Now())\n}\n\n\nfunc TimestampFromTime(t native_time.Time) Timestamp {\n\treturn TimestampFromUnix(t.Unix())\n}\n\n\nfunc TimestampFromUnix(t int64) Timestamp {\n\treturn Timestamp(t * second)\n}\n\nfunc (t Timestamp) Sub(o Timestamp) native_time.Duration ", "output": "{\n\treturn native_time.Duration(t-o) * MinimumTick\n}"} {"input": "package core\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\n\n\n\n\nfunc PodKey(namespace, podName string) string {\n\treturn fmt.Sprintf(\"namespace:%s/pod:%s\", namespace, podName)\n}\n\nfunc NamespaceKey(namespace string) string {\n\treturn fmt.Sprintf(\"namespace:%s\", namespace)\n}\n\nfunc NodeKey(node string) string {\n\treturn fmt.Sprintf(\"node:%s\", node)\n}\n\nfunc NodeContainerKey(node, container string) string {\n\treturn fmt.Sprintf(\"node:%s/container:%s\", node, container)\n}\n\nfunc ClusterKey() string {\n\treturn \"cluster\"\n}\n\nfunc PodContainerKey(namespace, podName, containerName string) string ", "output": "{\n\treturn fmt.Sprintf(\"namespace:%s/pod:%s/container:%s\", namespace, podName, containerName)\n}"} {"input": "package flect\n\nimport (\n\t\"strings\"\n\t\"unicode\"\n)\n\nvar spaces = []rune{'_', ' ', ':', '-', '/'}\n\nfunc isSpace(c rune) bool {\n\tfor _, r := range spaces {\n\t\tif r == c {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn unicode.IsSpace(c)\n}\n\nfunc xappend(a []string, ss ...string) []string {\n\tfor _, s := range ss {\n\t\ts = strings.TrimSpace(s)\n\t\tfor _, x := range spaces {\n\t\t\ts = strings.Trim(s, string(x))\n\t\t}\n\t\tif _, ok := baseAcronyms[strings.ToUpper(s)]; ok {\n\t\t\ts = strings.ToUpper(s)\n\t\t}\n\t\tif s != \"\" {\n\t\t\ta = append(a, s)\n\t\t}\n\t}\n\treturn a\n}\n\n\n\nfunc abs(x int) int ", "output": "{\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}"} {"input": "package bridge\n\nimport (\n\t\"github.com/sacloud/libsacloud/v2/helper/service\"\n\t\"github.com/sacloud/libsacloud/v2/helper/validate\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud/types\"\n)\n\ntype UpdateRequest struct {\n\tZone string `request:\"-\" validate:\"required\"`\n\tID types.ID `request:\"-\" validate:\"required\"`\n\n\tName *string `request:\",omitempty\" validate:\"omitempty,min=1\"`\n\tDescription *string `request:\",omitempty\" validate:\"omitempty,min=1,max=512\"`\n}\n\nfunc (req *UpdateRequest) Validate() error {\n\treturn validate.Struct(req)\n}\n\n\n\nfunc (req *UpdateRequest) ToRequestParameter(current *sacloud.Bridge) (*sacloud.BridgeUpdateRequest, error) ", "output": "{\n\tr := &sacloud.BridgeUpdateRequest{}\n\tif err := service.RequestConvertTo(current, r); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := service.RequestConvertTo(req, r); err != nil {\n\t\treturn nil, err\n\t}\n\treturn r, nil\n}"} {"input": "package rpcclientpool\n\nimport (\n\tgonet \"net\"\n\tgorpc \"net/rpc\"\n\n\t\"github.com/Cloud-Foundations/Dominator/lib/connpool\"\n\t\"github.com/Cloud-Foundations/Dominator/lib/net\"\n\t\"github.com/Cloud-Foundations/Dominator/lib/net/rpc\"\n)\n\nvar (\n\tdefaultDialer = &gonet.Dialer{}\n)\n\nfunc newClientResource(network, address string, http bool,\n\tpath string, dialer net.Dialer) *ClientResource {\n\tif path == \"\" {\n\t\tpath = gorpc.DefaultRPCPath\n\t}\n\tclientResource := &ClientResource{\n\t\tnetwork: network,\n\t\taddress: address,\n\t\thttp: http,\n\t\tpath: path,\n\t\tdialer: dialer,\n\t}\n\tclientResource.privateClientResource.clientResource = clientResource\n\trp := connpool.GetResourcePool()\n\tclientResource.resource = rp.Create(&clientResource.privateClientResource)\n\treturn clientResource\n}\n\nfunc (cr *ClientResource) get(cancelChannel <-chan struct{}) (*Client, error) {\n\tif err := cr.resource.Get(cancelChannel); err != nil {\n\t\treturn nil, err\n\t}\n\tcr.client.rpcClient = cr.rpcClient\n\treturn cr.client, nil\n}\n\n\n\nfunc (pcr *privateClientResource) Release() error {\n\tcr := pcr.clientResource\n\terr := cr.client.rpcClient.Close()\n\tcr.client.rpcClient = nil\n\tcr.client = nil\n\treturn err\n}\n\nfunc (client *Client) close() error {\n\treturn client.resource.resource.Release()\n}\n\nfunc (client *Client) put() {\n\tclient.rpcClient = nil\n\tclient.resource.resource.Put()\n}\n\nfunc (pcr *privateClientResource) Allocate() error ", "output": "{\n\tcr := pcr.clientResource\n\tvar rpcClient *gorpc.Client\n\tvar err error\n\tif cr.http {\n\t\trpcClient, err = rpc.DialHTTPPath(\n\t\t\tcr.dialer, cr.network, cr.address, cr.path)\n\t} else {\n\t\trpcClient, err = rpc.Dial(cr.dialer, cr.network, cr.address)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tclient := &Client{resource: cr}\n\tcr.client = client\n\tcr.rpcClient = rpcClient\n\treturn nil\n}"} {"input": "package model\n\ntype Interface interface {\n\tVisitString(name string, resume func())\n\tVisitInt(name string, resume func())\n\tVisitFloat(name string, resume func())\n\tVisitBool(name string, resume func())\n\tVisitPtr(name string, resume func())\n\tVisitBytes(name string, resume func())\n\tVisitSlice(name string, resume func())\n\tVisitStruct(name string, fields []Field, resume func())\n\tVisitStructField(field Field, resume func())\n\tVisitMap(name string, resume func())\n\tVisitCustom(name string, resume func())\n\tVisitReference(name string, resume func())\n}\n\ntype Visitor struct{}\n\n\n\nfunc (self *Visitor) VisitInt(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitFloat(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitBool(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitPtr(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitBytes(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitSlice(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitStruct(name string, fields []Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitStructField(field Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitMap(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitCustom(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitReference(name string, resume func()) {\n\tresume()\n}\n\ntype EmbeddedStructVisitor struct {\n\tInterface\n}\n\nfunc (self *EmbeddedStructVisitor) VisitStruct(name string, fields []Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitString(name string, resume func()) ", "output": "{\n\tresume()\n}"} {"input": "package main\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\t\"html/template\"\n\t\"net/http\"\n)\n\ntype Route struct {\n\tname string\n\tpath string\n\tfuncHandler gin.HandlerFunc\n}\n\ntype Link struct {\n\tpath string\n\tcaption string\n\thtml string\n}\n\ntype Page struct {\n\tCaption string\n\tBody string\n\tTmpl string\n}\n\nvar links = [...]Link{Link{caption: \"Home\", path: \"/\"},\n\tLink{caption: \"Sources\", path: \"/sources\"}}\n\nvar routes []Route\n\nvar webApp *gin.Engine\nvar indexTempl *template.Template\nvar sourceTempl *template.Template\nvar templates map[string]*template.Template\n\nfunc main() {\n\tconfigureServer()\n\tstartServer()\n}\n\nfunc startServer() {\n\twebApp.Run(\":3000\")\n}\n\nfunc initRoutes() {\n\troutes = make([]Route, 2)\n\trouteHome := Route{name: \"home\", path: \"/\", funcHandler: homeHandler}\n\trouteSoures := Route{name: \"source\", path: \"/sources\", funcHandler: sourcesHandler}\n\troutes[0] = routeHome\n\troutes[1] = routeSoures\n}\n\nfunc configureServer() {\n\ttemplates = nil\n\twebApp = gin.Default()\n\twebApp.LoadHTMLGlob(\"templates/*.tmpl\")\n\tinitRoutes()\n\tfor _, curRoute := range routes {\n\t\twebApp.GET(curRoute.path, curRoute.funcHandler)\n\t}\n}\n\n\n\nfunc homeHandler(c *gin.Context) ", "output": "{\n\tc.HTML(http.StatusOK, \"home\", gin.H{})\n}"} {"input": "package cmap\n\nimport \"github.com/OneOfOne/cmap/hashers\"\n\n\n\nfunc hasher(key KT) uint32 ", "output": "{ return hashers.Fnv32(key) }"} {"input": "package relay\n\nimport \"go.uber.org/zap\"\n\n\ntype Option func(options *options) error\n\ntype options struct {\n\tbufferSize int\n\tlog *zap.Logger\n}\n\n\n\n\n\n\n\nfunc WithLogger(log *zap.Logger) Option {\n\treturn func(options *options) error {\n\t\toptions.log = log\n\t\treturn nil\n\t}\n}\n\nfunc newOptions() *options ", "output": "{\n\treturn &options{\n\t\tbufferSize: 32 * 1024,\n\t\tlog: zap.NewNop(),\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com/zenazn/goji/web\"\n)\n\nfunc fileServeHandler(c web.C, w http.ResponseWriter, r *http.Request) {\n\tfileName := c.URLParams[\"name\"]\n\tfilePath := path.Join(Config.filesDir, fileName)\n\n\tif !fileExistsAndNotExpired(fileName) {\n\t\tnotFoundHandler(c, w, r)\n\t\treturn\n\t}\n\n\tif !Config.allowHotlink {\n\t\treferer := r.Header.Get(\"Referer\")\n\t\tif referer != \"\" && !strings.HasPrefix(referer, Config.siteURL) {\n\t\t\tw.WriteHeader(403)\n\t\t\treturn\n\t\t}\n\t}\n\n\tw.Header().Set(\"Content-Security-Policy\", Config.fileContentSecurityPolicy)\n\n\thttp.ServeFile(w, r, filePath)\n}\n\nfunc staticHandler(c web.C, w http.ResponseWriter, r *http.Request) {\n\tpath := r.URL.Path\n\tif path[len(path)-1:] == \"/\" {\n\t\tnotFoundHandler(c, w, r)\n\t\treturn\n\t} else {\n\t\tif path == \"/favicon.ico\" {\n\t\t\tpath = \"/static/images/favicon.gif\"\n\t\t}\n\n\t\tfilePath := strings.TrimPrefix(path, \"/static/\")\n\t\tfile, err := staticBox.Open(filePath)\n\t\tif err != nil {\n\t\t\tnotFoundHandler(c, w, r)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Etag\", timeStartedStr)\n\t\tw.Header().Set(\"Cache-Control\", \"max-age=86400\")\n\t\thttp.ServeContent(w, r, filePath, timeStarted, file)\n\t\treturn\n\t}\n}\n\n\n\nfunc fileExistsAndNotExpired(filename string) bool ", "output": "{\n\tfilePath := path.Join(Config.filesDir, filename)\n\n\t_, err := os.Stat(filePath)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tif isFileExpired(filename) {\n\t\tos.Remove(path.Join(Config.filesDir, filename))\n\t\tos.Remove(path.Join(Config.metaDir, filename))\n\t\treturn false\n\t}\n\n\treturn true\n}"} {"input": "package schedulercache\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/labels\"\n\t\"k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache\"\n)\n\n\ntype FakeCache struct {\n\tAssumeFunc func(*api.Pod)\n}\n\nfunc (f *FakeCache) AssumePod(pod *api.Pod) error {\n\tf.AssumeFunc(pod)\n\treturn nil\n}\n\nfunc (f *FakeCache) AddPod(pod *api.Pod) error { return nil }\n\nfunc (f *FakeCache) UpdatePod(oldPod, newPod *api.Pod) error { return nil }\n\nfunc (f *FakeCache) RemovePod(pod *api.Pod) error { return nil }\n\n\n\nfunc (f *FakeCache) UpdateNode(oldNode, newNode *api.Node) error { return nil }\n\nfunc (f *FakeCache) RemoveNode(node *api.Node) error { return nil }\n\nfunc (f *FakeCache) UpdateNodeNameToInfoMap(infoMap map[string]*schedulercache.NodeInfo) error {\n\treturn nil\n}\n\nfunc (f *FakeCache) List(s labels.Selector) ([]*api.Pod, error) { return nil, nil }\n\nfunc (f *FakeCache) AddNode(node *api.Node) error ", "output": "{ return nil }"} {"input": "package elastic\n\nimport (\n\t\"encoding/json\"\n\t\"testing\"\n)\n\n\n\nfunc TestRangeQueryWithTimeZone(t *testing.T) {\n\tq := NewRangeQuery(\"born\").\n\t\tGte(\"2012-01-01\").\n\t\tLte(\"now\").\n\t\tTimeZone(\"+1:00\")\n\tsrc, err := q.Source()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdata, err := json.Marshal(src)\n\tif err != nil {\n\t\tt.Fatalf(\"marshaling to JSON failed: %v\", err)\n\t}\n\tgot := string(data)\n\texpected := `{\"range\":{\"born\":{\"from\":\"2012-01-01\",\"include_lower\":true,\"include_upper\":true,\"time_zone\":\"+1:00\",\"to\":\"now\"}}}`\n\tif got != expected {\n\t\tt.Errorf(\"expected\\n%s\\n,got:\\n%s\", expected, got)\n\t}\n}\n\nfunc TestRangeQueryWithFormat(t *testing.T) {\n\tq := NewRangeQuery(\"born\").\n\t\tGte(\"2012/01/01\").\n\t\tLte(\"now\").\n\t\tFormat(\"yyyy/MM/dd\")\n\tsrc, err := q.Source()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdata, err := json.Marshal(src)\n\tif err != nil {\n\t\tt.Fatalf(\"marshaling to JSON failed: %v\", err)\n\t}\n\tgot := string(data)\n\texpected := `{\"range\":{\"born\":{\"format\":\"yyyy/MM/dd\",\"from\":\"2012/01/01\",\"include_lower\":true,\"include_upper\":true,\"to\":\"now\"}}}`\n\tif got != expected {\n\t\tt.Errorf(\"expected\\n%s\\n,got:\\n%s\", expected, got)\n\t}\n}\n\nfunc TestRangeQuery(t *testing.T) ", "output": "{\n\tq := NewRangeQuery(\"postDate\").From(\"2010-03-01\").To(\"2010-04-01\").Boost(3)\n\tq = q.QueryName(\"my_query\")\n\tsrc, err := q.Source()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdata, err := json.Marshal(src)\n\tif err != nil {\n\t\tt.Fatalf(\"marshaling to JSON failed: %v\", err)\n\t}\n\tgot := string(data)\n\texpected := `{\"range\":{\"_name\":\"my_query\",\"postDate\":{\"boost\":3,\"from\":\"2010-03-01\",\"include_lower\":true,\"include_upper\":true,\"to\":\"2010-04-01\"}}}`\n\tif got != expected {\n\t\tt.Errorf(\"expected\\n%s\\n,got:\\n%s\", expected, got)\n\t}\n}"} {"input": "package proj\n\nconst (\n\tutmLetters = \"CDEFGHJKLMNPQRSTUVWXX\"\n)\n\nvar (\n\tUTMZones = map[int]*TransverseMercator{}\n)\n\n\n\n\n\nfunc LatLongUTMZone(lat, lon float64) int {\n\tswitch {\n\tcase 56 <= lat && lat < 64 && 3 <= lon && lon < 12:\n\t\treturn 32\n\tcase 72 <= lat && lat < 84 && 0 <= lon && lon < 42:\n\t\tswitch {\n\t\tcase lon < 9:\n\t\t\treturn 31\n\t\tcase lon < 21:\n\t\t\treturn 33\n\t\tcase lon < 33:\n\t\t\treturn 35\n\t\tdefault:\n\t\t\treturn 37\n\t\t}\n\tdefault:\n\t\treturn int(lon+180)/6 + 1\n\t}\n}\n\n\nfunc LatLongUTMLetter(lat, lon float64) byte {\n\tif lat < -80 || 84 <= lat {\n\t\treturn 0\n\t}\n\ti := int((lat + 80) / 8)\n\treturn utmLetters[i]\n}\n\nfunc initUTM() {\n\tfor z := 1; z <= 60; z++ {\n\t\tUTMZones[z] = utmZone(z)\n\t}\n}\n\nfunc utmZone(zone int) *TransverseMercator ", "output": "{\n\treturn &TransverseMercator{\n\t\tcode: 32600 + zone,\n\t\tf0: 0.9996,\n\t\tlat0: rad(0),\n\t\tlon0: rad(6*(30-float64(zone)) + 3),\n\t\te0: 500000,\n\t\tn0: 0,\n\t\te: International1924,\n\t}\n}"} {"input": "package registry\n\nimport \"go.uber.org/zap\"\n\nvar log *zap.Logger\n\nfunc init() {\n\tlog = zap.NewNop()\n}\n\n\n\n\nfunc UseLogger(l *zap.Logger) ", "output": "{\n\tlog = l\n}"} {"input": "package repo\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/url\"\n\t\"os\"\n\t\"os/user\"\n\t\"path/filepath\"\n)\n\nconst netrcFile = `\nmachine %s\nlogin %s\npassword %s\n`\n\n\n\n\n\nfunc WriteNetrc(machine, login, password string) error {\n\tif machine == \"\" {\n\t\treturn nil\n\t}\n\n\tnetrcContent := fmt.Sprintf(\n\t\tnetrcFile,\n\t\tmachine,\n\t\tlogin,\n\t\tpassword,\n\t)\n\n\thome := \"/root\"\n\n\tif currentUser, err := user.Current(); err == nil {\n\t\thome = currentUser.HomeDir\n\t}\n\n\tnetpath := filepath.Join(\n\t\thome,\n\t\t\".netrc\")\n\n\treturn ioutil.WriteFile(\n\t\tnetpath,\n\t\t[]byte(netrcContent),\n\t\t0600)\n}\n\n\nfunc WriteToken(remote string, login, password string) (string, error) {\n\tif remote == \"\" || login == \"\" || password == \"\" {\n\t\treturn remote, nil\n\t}\n\n\tu, err := url.Parse(remote)\n\n\tif err != nil {\n\t\treturn remote, err\n\t}\n\n\tu.User = url.UserPassword(login, password)\n\n\treturn u.String(), nil\n}\n\nfunc WriteKey(privateKey string) error ", "output": "{\n\tif privateKey == \"\" {\n\t\treturn nil\n\t}\n\n\thome := \"/root\"\n\n\tif currentUser, err := user.Current(); err == nil {\n\t\thome = currentUser.HomeDir\n\t}\n\n\tsshpath := filepath.Join(\n\t\thome,\n\t\t\".ssh\")\n\n\tif err := os.MkdirAll(sshpath, 0700); err != nil {\n\t\treturn err\n\t}\n\n\tconfpath := filepath.Join(\n\t\tsshpath,\n\t\t\"config\")\n\n\tprivpath := filepath.Join(\n\t\tsshpath,\n\t\t\"id_rsa\")\n\n\tioutil.WriteFile(\n\t\tconfpath,\n\t\t[]byte(\"StrictHostKeyChecking no\\n\"),\n\t\t0700)\n\n\treturn ioutil.WriteFile(\n\t\tprivpath,\n\t\t[]byte(privateKey),\n\t\t0600)\n}"} {"input": "package service\n\nimport (\n\t\"github.com/golang/glog\"\n\t\"github.com/oikomi/FishChatServer2/http_server/user-api/model\"\n\tauthRpc \"github.com/oikomi/FishChatServer2/http_server/user-api/rpc\"\n\t\"github.com/oikomi/FishChatServer2/protocol/rpc\"\n)\n\ntype Service struct {\n\trpcClient *authRpc.RPCClient\n}\n\nfunc New() (service *Service, err error) {\n\trpcClient, err := authRpc.NewRPCClient()\n\tif err != nil {\n\t\tglog.Error(err)\n\t\treturn\n\t}\n\tservice = &Service{\n\t\trpcClient: rpcClient,\n\t}\n\treturn\n}\n\n\n\nfunc (s *Service) Register(uid int64, userName, pw string) (err error) {\n\trgRegisterReq := &rpc.RGRegisterReq{\n\t\tUID: uid,\n\t\tName: userName,\n\t\tPassword: pw,\n\t}\n\t_, err = s.rpcClient.Register.Register(rgRegisterReq)\n\tif err != nil {\n\t\tglog.Error(err)\n\t\treturn\n\t}\n\treturn\n}\n\nfunc (s *Service) Auth(uid int64, pw string) (loginModel *model.Login, err error) ", "output": "{\n\trgAuthReq := &rpc.RGAuthReq{\n\t\tUID: uid,\n\t}\n\tres, err := s.rpcClient.Register.Auth(rgAuthReq)\n\tif err != nil {\n\t\tglog.Error(err)\n\t\treturn\n\t}\n\tloginModel = &model.Login{\n\t\tToken: res.Token,\n\t}\n\treturn\n}"} {"input": "package main\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/astaxie/beego\"\n\t\"github.com/astaxie/beego/orm\"\n\n\t_ \"github.com/go-sql-driver/mysql\"\n\t. \"weibo.com/opendcp/orion/models\"\n\t_ \"weibo.com/opendcp/orion/routers\"\n\t\"weibo.com/opendcp/orion/sched\"\n)\n\nfunc main() {\n\tbeego.Run()\n}\n\n\n\nfunc initOrm() {\n\tdbUrl := beego.AppConfig.String(\"database_url\")\n\tdbpoolsizestr := beego.AppConfig.String(\"database_poolsize\")\n\tif dbUrl == \"\" {\n\t\tpanic(\"db_url not found in config...\")\n\t}\n\n\torm.Debug = true\n\n\torm.RegisterDriver(\"mysql\", orm.DRMySQL)\n\n\tdbpoolsize, _ := strconv.Atoi(dbpoolsizestr)\n\torm.RegisterDataBase(\"default\", \"mysql\", dbUrl, dbpoolsize)\n\n\torm.RegisterModel(&(Cluster{}), &(Service{}), &(Pool{}), &(Node{}), &(Logs{}))\n\torm.RegisterModel(&(FlowImpl{}), &(Flow{}), &(FlowBatch{}), &(NodeState{}))\n\torm.RegisterModel(&(RemoteStep{}), &(RemoteAction{}), &(RemoteActionImpl{}))\n\torm.RegisterModel(&(CronItem{}), &(DependItem{}), &(ExecTask{}))\n}\n\nfunc init() ", "output": "{\n\terr := beego.LoadAppConfig(\"ini\", \"conf/app.conf\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tinitOrm()\n\n\tif err := sched.Initial(); err != nil {\n\t\tpanic(err)\n\t}\n\tbeego.SetLogger(\"file\", `{\"filename\":\"logs/orion.log\"}`)\n}"} {"input": "package fs\n\nimport (\n\t\"syscall\"\n)\n\nfunc MountRootFS(path string) error {\n\treturn syscall.Mount(path, \"rootfs\", \"\", syscall.MS_BIND, \"\")\n}\n\nfunc MountAdditional(source, dest, t string) error {\n\treturn syscall.Mount(source, dest, t, syscall.MS_BIND, \"\")\n}\n\nfunc MountDevFS() error {\n\treturn syscall.Mount(\"tmpfs\", \"/dev\", \"tmpfs\", syscall.MS_BIND, \"\")\n}\n\n\n\nfunc MountSysFS() error {\n\treturn syscall.Mount(\"sysfs\", \"/sys\", \"sysfs\", syscall.MS_BIND, \"\")\n}\n\nfunc MountProcFS() error ", "output": "{\n\treturn syscall.Mount(\"proc\", \"/proc\", \"proc\", syscall.MS_BIND, \"\")\n}"} {"input": "package cmd\n\nimport \"syscall\"\n\n\n\n\n\n\nfunc Fallocate(fd int, offset int64, len int64) error ", "output": "{\n\tif len == 0 {\n\t\treturn nil\n\t}\n\tfallocFLKeepSize := uint32(1)\n\treturn syscall.Fallocate(fd, fallocFLKeepSize, offset, len)\n}"} {"input": "package dao\n\nimport (\n\t\"github.com/goharbor/harbor/src/common/models\"\n)\n\nconst (\n\tSchemaVersion = \"1.6.0\"\n)\n\n\n\n\nfunc GetSchemaVersion() (*models.SchemaVersion, error) ", "output": "{\n\tversion := &models.SchemaVersion{}\n\tif err := GetOrmer().Raw(\"select version_num from alembic_version\").\n\t\tQueryRow(version); err != nil {\n\t\treturn nil, err\n\t}\n\treturn version, nil\n}"} {"input": "package v1beta1\n\nimport (\n\t\"k8s.io/apimachinery/pkg/conversion\"\n\t\"k8s.io/apimachinery/pkg/util/json\"\n\n\t\"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions\"\n)\n\nfunc Convert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps(in *apiextensions.JSONSchemaProps, out *JSONSchemaProps, s conversion.Scope) error {\n\tif err := autoConvert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif in.Default != nil && *(in.Default) == nil {\n\t\tout.Default = nil\n\t}\n\tif in.Example != nil && *(in.Example) == nil {\n\t\tout.Example = nil\n\t}\n\treturn nil\n}\n\n\n\nfunc Convert_v1beta1_JSON_To_apiextensions_JSON(in *JSON, out *apiextensions.JSON, s conversion.Scope) error {\n\tif in != nil {\n\t\tvar i interface{}\n\t\tif err := json.Unmarshal(in.Raw, &i); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t*out = i\n\t} else {\n\t\tout = nil\n\t}\n\treturn nil\n}\n\nfunc Convert_apiextensions_JSON_To_v1beta1_JSON(in *apiextensions.JSON, out *JSON, s conversion.Scope) error ", "output": "{\n\traw, err := json.Marshal(*in)\n\tif err != nil {\n\t\treturn err\n\t}\n\tout.Raw = raw\n\treturn nil\n}"} {"input": "package controller\n\nimport (\n\t\"fmt\"\n)\n\ntype AdminParams struct {\n\tName *string\n\tInviteId *string\n\tInviteKey *string\n\tConfirmDelete *string\n}\n\nfunc NewAdminParams() *AdminParams {\n\treturn new(AdminParams)\n}\n\n\n\nfunc (params *AdminParams) ValidateInviteId(required bool) error { return nil }\nfunc (params *AdminParams) ValidateInviteKey(required bool) error { return nil }\n\nfunc (params *AdminParams) ValidateName(required bool) error ", "output": "{\n\tif required && *params.Name == \"\" {\n\t\treturn fmt.Errorf(\"name cannot be empty\")\n\t}\n\treturn nil\n}"} {"input": "package summary\n\nimport (\n\tinfo \"github.com/google/cadvisor/info/v2\"\n)\n\n\n\n\n\ntype SamplesBuffer struct {\n\tsamples []info.Usage\n\tmaxSize int\n\tindex int\n}\n\n\nfunc NewSamplesBuffer(size int) *SamplesBuffer {\n\treturn &SamplesBuffer{\n\t\tindex: -1,\n\t\tmaxSize: size,\n\t}\n}\n\n\n\n\n\nfunc (s *SamplesBuffer) Add(stat info.Usage) {\n\tif len(s.samples) < s.maxSize {\n\t\ts.samples = append(s.samples, stat)\n\t\ts.index++\n\t\treturn\n\t}\n\ts.index = (s.index + 1) % s.maxSize\n\ts.samples[s.index] = stat\n}\n\n\nfunc (s *SamplesBuffer) RecentStats(n int) []*info.Usage {\n\tif n > len(s.samples) {\n\t\tn = len(s.samples)\n\t}\n\tstart := s.index - (n - 1)\n\tif start < 0 {\n\t\tstart += len(s.samples)\n\t}\n\n\tout := make([]*info.Usage, n)\n\tfor i := 0; i < n; i++ {\n\t\tindex := (start + i) % len(s.samples)\n\t\tout[i] = &s.samples[index]\n\t}\n\treturn out\n}\n\nfunc (s *SamplesBuffer) Size() int ", "output": "{\n\treturn len(s.samples)\n}"} {"input": "package gtk\n\n\n\nimport \"C\"\nimport (\n\t\"unsafe\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (v *FileChooserButton) GetFocusOnClick() bool {\n\treturn gobool(C.gtk_file_chooser_button_get_focus_on_click(v.native()))\n}\n\n\nfunc (v *FileChooserButton) SetFocusOnClick(grabFocus bool) {\n\tC.gtk_file_chooser_button_set_focus_on_click(v.native(), gbool(grabFocus))\n}\n\n\n\n\nfunc (v *Button) GetFocusOnClick() bool {\n\tc := C.gtk_button_get_focus_on_click(v.native())\n\treturn gobool(c)\n}\n\n\n\n\n\n\n\nfunc (v *TextIter) BeginsTag(v1 *TextTag) bool {\n\treturn gobool(C.gtk_text_iter_begins_tag(v.native(), v1.native()))\n}\n\n\n\n\nfunc (v *Window) ParseGeometry(geometry string) bool {\n\tcstr := C.CString(geometry)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tc := C.gtk_window_parse_geometry(v.native(), (*C.gchar)(cstr))\n\treturn gobool(c)\n}\n\n\nfunc (v *Window) ResizeToGeometry(width, height int) {\n\tC.gtk_window_resize_to_geometry(v.native(), C.gint(width), C.gint(height))\n}\n\n\nfunc (v *Window) SetDefaultGeometry(width, height int) {\n\tC.gtk_window_set_default_geometry(v.native(), C.gint(width),\n\t\tC.gint(height))\n}\n\nfunc (v *Button) SetFocusOnClick(focusOnClick bool) ", "output": "{\n\tC.gtk_button_set_focus_on_click(v.native(), gbool(focusOnClick))\n}"} {"input": "package mlock\n\n\n\nfunc lockMemory() error {\n\treturn nil\n}\n\nfunc init() ", "output": "{\n\tsupported = false\n}"} {"input": "package pprof\n\nimport \"net\"\n\nfunc (d *pprofDialer) pprofDial(proto, addr string) (conn net.Conn, err error) {\n\treturn net.Dial(d.proto, d.addr)\n}\n\n\n\nfunc getPProfDialer(addr string) *pprofDialer ", "output": "{\n\treturn &pprofDialer{\"unix\", addr}\n}"} {"input": "package serial\n\nimport (\n\t\"flag\"\n\n\t\"github.com/juju/govmomi/govc/cli\"\n\t\"github.com/juju/govmomi/govc/flags\"\n\t\"golang.org/x/net/context\"\n)\n\ntype disconnect struct {\n\t*flags.VirtualMachineFlag\n\n\tdevice string\n}\n\nfunc init() {\n\tcli.Register(\"device.serial.disconnect\", &disconnect{})\n}\n\nfunc (cmd *disconnect) Register(f *flag.FlagSet) {\n\tf.StringVar(&cmd.device, \"device\", \"\", \"serial port device name\")\n}\n\n\n\nfunc (cmd *disconnect) Run(f *flag.FlagSet) error {\n\tvm, err := cmd.VirtualMachine()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif vm == nil {\n\t\treturn flag.ErrHelp\n\t}\n\n\tdevices, err := vm.Device(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td, err := devices.FindSerialPort(cmd.device)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn vm.EditDevice(context.TODO(), devices.DisconnectSerialPort(d))\n}\n\nfunc (cmd *disconnect) Process() error ", "output": "{ return nil }"} {"input": "package chart\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/golang/protobuf/jsonpb\"\n)\n\n\nfunc (msg *Config) MarshalJSON() ([]byte, error) {\n\tvar buf bytes.Buffer\n\terr := (&jsonpb.Marshaler{\n\t\tEnumsAsInts: false,\n\t\tEmitDefaults: false,\n\t\tOrigName: false,\n\t}).Marshal(&buf, msg)\n\treturn buf.Bytes(), err\n}\n\n\nfunc (msg *Config) UnmarshalJSON(b []byte) error {\n\treturn (&jsonpb.Unmarshaler{\n\t\tAllowUnknownFields: false,\n\t}).Unmarshal(bytes.NewReader(b), msg)\n}\n\n\nfunc (msg *Value) MarshalJSON() ([]byte, error) {\n\tvar buf bytes.Buffer\n\terr := (&jsonpb.Marshaler{\n\t\tEnumsAsInts: false,\n\t\tEmitDefaults: false,\n\t\tOrigName: false,\n\t}).Marshal(&buf, msg)\n\treturn buf.Bytes(), err\n}\n\n\n\n\nfunc (msg *Value) UnmarshalJSON(b []byte) error ", "output": "{\n\treturn (&jsonpb.Unmarshaler{\n\t\tAllowUnknownFields: false,\n\t}).Unmarshal(bytes.NewReader(b), msg)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"appengine\"\n\t\"appengine/datastore\"\n)\n\nfunc EvalRegex(ctx appengine.Context, input *MatchInput) (*MatchResultResponse, error) {\n\tstartRegex := time.Now()\n\n\tr, err := regexp.Compile(input.Expr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Invalid RegExp: %s -- %v\", input.Expr, err)\n\t}\n\n\tmatches := r.FindAllStringSubmatch(input.Text, input.NumMatches)\n\tresult := &MatchResultResponse{}\n\tif len(matches) > 0 {\n\t\tresult.Matches = matches\n\t\tresult.GroupsName = r.SubexpNames()[1:]\n\t}\n\n\tgo recordStats(ctx, input.Expr, input.Text, time.Since(startRegex))\n\n\treturn result, nil\n}\n\ntype regexStats struct {\n\tExprLength int `datastore:\",noindex\"`\n\tTextLength int `datastore:\",noindex\"`\n\tRanAt time.Time `datastore:\",noindex\"`\n\tDuration time.Duration `datastore:\",noindex\"`\n}\n\n\n\nfunc recordStats(ctx appengine.Context, expr string, text string, duration time.Duration) ", "output": "{\n\tdefer func() {\n\t\tif rec := recover(); rec != nil {\n\t\t\tstack := make([]byte, 32768)\n\t\t\truntime.Stack(stack, false)\n\t\t\tctx.Errorf(\"Recovered from panic: %v -- %s\", rec, stack)\n\t\t}\n\t}()\n\tstats := ®exStats{\n\t\tExprLength: len(expr),\n\t\tTextLength: len(text),\n\t\tRanAt: time.Now(),\n\t\tDuration: duration,\n\t}\n\t_, err := datastore.Put(ctx, datastore.NewIncompleteKey(ctx, \"regex_stats\", nil), stats)\n\tif err != nil {\n\t\tctx.Errorf(\"Error writing stats: %v\", err)\n\t}\n\n}"} {"input": "package storageos\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/storageos/go-api/types\"\n)\n\nvar (\n\tHealthAPIPrefix = \"health\"\n)\n\n\n\n\n\nfunc (c *Client) DPHealth(ctx context.Context, hostname string) (*types.DPHealthStatus, error) {\n\n\turl := fmt.Sprintf(\"http://%s:%s/v1/%s\", hostname, DataplaneHealthPort, HealthAPIPrefix)\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"User-Agent\", userAgent)\n\tif c.username != \"\" && c.secret != \"\" {\n\t\treq.SetBasicAuth(c.username, c.secret)\n\t}\n\n\tresp, err := c.HTTPClient.Do(req.WithContext(ctx))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar status *types.DPHealthStatus\n\tif err := json.NewDecoder(resp.Body).Decode(&status); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn status, nil\n}\n\nfunc (c *Client) CPHealth(ctx context.Context, hostname string) (*types.CPHealthStatus, error) ", "output": "{\n\n\turl := fmt.Sprintf(\"http://%s:%s/v1/%s\", hostname, DefaultPort, HealthAPIPrefix)\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"User-Agent\", userAgent)\n\tif c.username != \"\" && c.secret != \"\" {\n\t\treq.SetBasicAuth(c.username, c.secret)\n\t}\n\n\tresp, err := c.HTTPClient.Do(req.WithContext(ctx))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar status *types.CPHealthStatus\n\tif err := json.NewDecoder(resp.Body).Decode(&status); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn status, nil\n}"} {"input": "package services\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/unrealities/warning-track/models\"\n)\n\n\n\nfunc BaseOuts() []models.BaseOut ", "output": "{\n\tbaseOuts := []models.BaseOut{}\n\n\tbaseOutsFile, err := os.Open(\"base_out.json\")\n\tif err != nil {\n\t\tfmt.Println(\"Error opening baseOutsFile: \" + err.Error())\n\t}\n\n\tjsonParser := json.NewDecoder(baseOutsFile)\n\tif err = jsonParser.Decode(&baseOuts); err != nil {\n\t\tfmt.Println(\"Error parsing file: \" + err.Error())\n\t}\n\n\treturn baseOuts\n}"} {"input": "package v1beta1\n\nimport (\n\tv1beta1 \"k8s.io/api/scheduling/v1beta1\"\n\tserializer \"k8s.io/apimachinery/pkg/runtime/serializer\"\n\t\"k8s.io/client-go/kubernetes/scheme\"\n\trest \"k8s.io/client-go/rest\"\n)\n\ntype SchedulingV1beta1Interface interface {\n\tRESTClient() rest.Interface\n\tPriorityClassesGetter\n}\n\n\ntype SchedulingV1beta1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *SchedulingV1beta1Client) PriorityClasses() PriorityClassInterface {\n\treturn newPriorityClasses(c)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*SchedulingV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &SchedulingV1beta1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *SchedulingV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\n\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *SchedulingV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc New(c rest.Interface) *SchedulingV1beta1Client ", "output": "{\n\treturn &SchedulingV1beta1Client{c}\n}"} {"input": "package test_helpers\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\tdatatypes \"github.com/maximilien/softlayer-go/data_types\"\n)\n\ntype MockProductPackageService struct{}\n\nfunc (mock *MockProductPackageService) GetName() string {\n\treturn \"Mock_Product_Package_Service\"\n}\n\nfunc (mock *MockProductPackageService) GetItemsByType(packageType string) ([]datatypes.SoftLayer_Product_Item, error) {\n\tresponse, _ := ReadJsonTestFixtures(\"services\", \"SoftLayer_Product_Package_getItemsByType_virtual_server.json\")\n\n\tproductItems := []datatypes.SoftLayer_Product_Item{}\n\tjson.Unmarshal(response, &productItems)\n\n\treturn productItems, nil\n}\n\n\n\nfunc (mock *MockProductPackageService) GetItemPricesBySize(packageId int, size int) ([]datatypes.SoftLayer_Product_Item_Price, error) {\n\treturn []datatypes.SoftLayer_Product_Item_Price{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetItems(packageId int) ([]datatypes.SoftLayer_Product_Item, error) {\n\treturn []datatypes.SoftLayer_Product_Item{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetPackagesByType(packageType string) ([]datatypes.Softlayer_Product_Package, error) {\n\treturn []datatypes.Softlayer_Product_Package{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetOnePackageByType(packageType string) (datatypes.Softlayer_Product_Package, error) {\n\treturn datatypes.Softlayer_Product_Package{}, errors.New(\"Not supported\")\n}\n\nfunc (mock *MockProductPackageService) GetItemPrices(packageId int) ([]datatypes.SoftLayer_Product_Item_Price, error) ", "output": "{\n\treturn []datatypes.SoftLayer_Product_Item_Price{}, errors.New(\"Not supported\")\n}"} {"input": "package matchers\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com/onsi/gomega/format\"\n)\n\ntype BeElementOfMatcher struct {\n\tElements []interface{}\n}\n\nfunc (matcher *BeElementOfMatcher) Match(actual interface{}) (success bool, err error) {\n\tif reflect.TypeOf(actual) == nil {\n\t\treturn false, fmt.Errorf(\"BeElement matcher expects actual to be typed\")\n\t}\n\n\tvar lastError error\n\tfor _, m := range flatten(matcher.Elements) {\n\t\tmatcher := &EqualMatcher{Expected: m}\n\t\tsuccess, err := matcher.Match(actual)\n\t\tif err != nil {\n\t\t\tlastError = err\n\t\t\tcontinue\n\t\t}\n\t\tif success {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, lastError\n}\n\n\n\nfunc (matcher *BeElementOfMatcher) NegatedFailureMessage(actual interface{}) (message string) {\n\treturn format.Message(actual, \"not to be an element of\", presentable(matcher.Elements))\n}\n\nfunc (matcher *BeElementOfMatcher) FailureMessage(actual interface{}) (message string) ", "output": "{\n\treturn format.Message(actual, \"to be an element of\", presentable(matcher.Elements))\n}"} {"input": "package osc\n\nimport (\n\t\"net\"\n\t\"testing\"\n)\n\nfunc TestUDPConn(t *testing.T) {\n\tladdr, err := net.ResolveUDPAddr(\"udp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tlc, err := ListenUDP(\"udp\", laddr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvar c Conn = lc\n\t_ = c\n}\n\n\n\nfunc TestValidateAddress(t *testing.T) ", "output": "{\n\tif err := ValidateAddress(\"/foo\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := ValidateAddress(\"/foo@^#&*$^*%)()#($*@\"); err == nil {\n\t\tt.Fatal(\"expected error, got nil\")\n\t}\n}"} {"input": "package gtreap\n\nimport (\n\t\"math/rand\"\n\n\t\"github.com/blevesearch/bleve/index/store\"\n)\n\nfunc (w *Writer) BytesSafeAfterClose() bool {\n\treturn false\n}\n\nfunc (w *Writer) Get(k []byte) (v []byte, err error) {\n\tw.s.m.Lock()\n\tt := w.s.t\n\tw.s.m.Unlock()\n\n\titm := t.Get(&Item{k: k})\n\tif itm != nil {\n\t\treturn itm.(*Item).v, nil\n\t}\n\treturn nil, nil\n}\n\nfunc (w *Writer) Iterator(k []byte) store.KVIterator {\n\tw.s.m.Lock()\n\tt := w.s.t\n\tw.s.m.Unlock()\n\n\treturn newIterator(t).restart(&Item{k: k})\n}\n\n\n\nfunc (w *Writer) Set(k, v []byte) (err error) {\n\tw.s.m.Lock()\n\tw.s.t = w.s.t.Upsert(&Item{k: k, v: v}, rand.Int())\n\tw.s.m.Unlock()\n\n\treturn nil\n}\n\nfunc (w *Writer) Delete(k []byte) (err error) {\n\tw.s.m.Lock()\n\tw.s.t = w.s.t.Delete(&Item{k: k})\n\tw.s.m.Unlock()\n\n\treturn nil\n}\n\nfunc (w *Writer) NewBatch() store.KVBatch {\n\treturn store.NewEmulatedBatch(w, w.s.mo)\n}\n\nfunc (w *Writer) Close() error ", "output": "{\n\tw.s.availableWriters <- true\n\tw.s = nil\n\n\treturn nil\n}"} {"input": "package request\n\nimport (\n\t\"fmt\"\n\n\t\"dchaykin/meetup_api/settings\"\n)\n\ntype SimilarGroupRequest struct {\n\tURLName string \n}\n\nconst urlSimilarGroup string = \"%s/%s/similar_groups?key=%s&sign=true\"\n\n\n\nfunc (request SimilarGroupRequest) Address() string {\n\treturn fmt.Sprintf(urlSimilarGroup, settings.BaseURL, request.URLName, settings.GetApiKey())\n}\n\nfunc (request SimilarGroupRequest) WithOffset() bool ", "output": "{\n\treturn true\n}"} {"input": "package sum\n\nimport (\n\t\"github.com/catorpilor/leetcode/utils\"\n)\n\nfunc SumNumbers(root *utils.TreeNode) int {\n\treturn helper(root, 0)\n}\n\n\n\nfunc helper(node *utils.TreeNode, val int) int ", "output": "{\n\tif node == nil {\n\t\treturn val\n\t}\n\tval = val*10 + node.Val\n\tif node.Left == nil && node.Right == nil {\n\t\treturn val\n\t}\n\tleftSum, rightSum := 0, 0\n\tif node.Left != nil {\n\t\tleftSum = helper(node.Left, val)\n\t}\n\tif node.Right != nil {\n\t\trightSum = helper(node.Right, val)\n\t}\n\treturn leftSum + rightSum\n}"} {"input": "package main\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t_ \"github.com/mattn/go-oci8\"\n)\n\nfunc main() {\n\tdb, err := sql.Open(\"oci8\", getDSN())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t_, err = db.Exec(`\n CREATE OR REPLACE FUNCTION MY_SUM\n (\n P_NUM1 IN NUMBER,\n P_NUM2 IN NUMBER\n )\n RETURN NUMBER\n IS\n R_NUM NUMBER(2) DEFAULT 0;\n BEGIN\n FOR i IN 1..P_NUM2\n LOOP\n R_NUM := R_NUM + P_NUM1;\n END LOOP;\n RETURN R_NUM;\n END;\n `)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\trows, err := db.Query(\"select MY_SUM(5,6) from dual\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor rows.Next() {\n\t\tvar i int\n\t\terr = rows.Scan(&i)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tprintln(i)\n\t}\n}\n\n\n\nfunc getDSN() string ", "output": "{\n\tvar dsn string\n\tif len(os.Args) > 1 {\n\t\tdsn = os.Args[1]\n\t\tif dsn != \"\" {\n\t\t\treturn dsn\n\t\t}\n\t}\n\tdsn = os.Getenv(\"GO_OCI8_CONNECT_STRING\")\n\tif dsn != \"\" {\n\t\treturn dsn\n\t}\n\tfmt.Fprintln(os.Stderr, `Please specifiy connection parameter in GO_OCI8_CONNECT_STRING environment variable,\nor as the first argument! (The format is user/password@host:port/sid)`)\n\treturn \"scott/tiger@XE\"\n}"} {"input": "package encode\n\nimport \"testing\"\n\nfunc TestRunLengthEncode(t *testing.T) {\n\tfor _, test := range encodeTests {\n\t\tif actual := RunLengthEncode(test.input); actual != test.expected {\n\t\t\tt.Errorf(\"FAIL %s - RunLengthEncode(%s) = %q, expected %q.\",\n\t\t\t\ttest.description, test.input, actual, test.expected)\n\t\t}\n\t\tt.Logf(\"PASS RunLengthEncode - %s\", test.description)\n\t}\n}\n\nfunc TestRunLengthEncodeDecode(t *testing.T) {\n\tfor _, test := range encodeDecodeTests {\n\t\tif actual := RunLengthDecode(RunLengthEncode(test.input)); actual != test.expected {\n\t\t\tt.Errorf(\"FAIL %s - RunLengthDecode(RunLengthEncode(%s)) = %q, expected %q.\",\n\t\t\t\ttest.description, test.input, actual, test.expected)\n\t\t}\n\t\tt.Logf(\"PASS %s\", test.description)\n\t}\n}\n\nfunc TestRunLengthDecode(t *testing.T) ", "output": "{\n\tfor _, test := range decodeTests {\n\t\tif actual := RunLengthDecode(test.input); actual != test.expected {\n\t\t\tt.Errorf(\"FAIL %s - RunLengthDecode(%s) = %q, expected %q.\",\n\t\t\t\ttest.description, test.input, actual, test.expected)\n\t\t}\n\t\tt.Logf(\"PASS RunLengthDecode - %s\", test.description)\n\t}\n}"} {"input": "package spi\n\n\nfunc NewGroup(group *GroupInfo) Group {\n\treturn group\n}\n\n\n\n\n\nfunc (g *GroupInfo) GetChildren() ([]Group, error) {\n\treturn nil, nil\n}\n\n\nfunc (g *GroupInfo) GetParent() string {\n\treturn g.ParentID\n}\n\nfunc (g *GroupInfo) GetName() string ", "output": "{\n\treturn g.Name\n}"} {"input": "package main\n\nimport (\n\t\"gopkg.in/redis.v4\"\n)\n\ntype ProphetService interface {\n\tConsult() (string, error)\n}\n\ntype prophetService struct { \n\trclient *redis.Client\n}\n\n\n\nfunc (svc *prophetService) Consult() (string, error) ", "output": "{\n\tv, err := svc.rclient.SRandMember(\"consult\").Result()\n\tif err != nil {\n\t\treturn \"...\", nil\n\t}\n\treturn v, nil\n}"} {"input": "package automation\n\nimport (\n\tautomationpb \"github.com/youtube/vitess/go/vt/proto/automation\"\n\t\"github.com/youtube/vitess/go/vt/topo/topoproto\"\n\t\"golang.org/x/net/context\"\n)\n\n\ntype SplitDiffTask struct {\n}\n\n\nfunc (t *SplitDiffTask) Run(parameters map[string]string) ([]*automationpb.TaskContainer, string, error) {\n\targs := []string{\"SplitDiff\"}\n\tif excludeTables := parameters[\"exclude_tables\"]; excludeTables != \"\" {\n\t\targs = append(args, \"--exclude_tables=\"+excludeTables)\n\t}\n\tif minHealthyRdonlyTablets := parameters[\"min_healthy_rdonly_tablets\"]; minHealthyRdonlyTablets != \"\" {\n\t\targs = append(args, \"--min_healthy_rdonly_tablets=\"+minHealthyRdonlyTablets)\n\t}\n\targs = append(args, topoproto.KeyspaceShardString(parameters[\"keyspace\"], parameters[\"dest_shard\"]))\n\toutput, err := ExecuteVtworker(context.TODO(), parameters[\"vtworker_endpoint\"], args)\n\n\tif err == nil {\n\t\tExecuteVtworker(context.TODO(), parameters[\"vtworker_endpoint\"], []string{\"Reset\"})\n\t}\n\treturn nil, output, err\n}\n\n\n\n\n\nfunc (t *SplitDiffTask) OptionalParameters() []string {\n\treturn []string{\"exclude_tables\", \"min_healthy_rdonly_tablets\"}\n}\n\nfunc (t *SplitDiffTask) RequiredParameters() []string ", "output": "{\n\treturn []string{\"keyspace\", \"dest_shard\", \"vtworker_endpoint\"}\n}"} {"input": "package golang\n\nimport (\n\t\"bldy.build/build/executor\"\n\t\"bldy.build/build/label\"\n)\n\ntype Go struct {\n\tname string `group:\"name\"`\n\tdependencies []label.Label `group:\"deps\"`\n}\n\nfunc (g *Go) Name() string {\n\tpanic(\"not implemented\")\n}\n\nfunc (g *Go) Dependencies() []label.Label {\n\tpanic(\"not implemented\")\n}\n\nfunc (g *Go) Outputs() []string {\n\tpanic(\"not implemented\")\n}\n\n\n\nfunc (g *Go) Build(*executor.Executor) error {\n\tpanic(\"not implemented\")\n}\n\nfunc (g *Go) Hash() []byte ", "output": "{\n\tpanic(\"not implemented\")\n}"} {"input": "package repository\n\nimport (\n\t\"strings\"\n\n\t\"code.gitea.io/gitea/models\"\n\t\"code.gitea.io/gitea/modules/cache\"\n\t\"code.gitea.io/gitea/modules/git\"\n\t\"code.gitea.io/gitea/modules/setting\"\n)\n\nfunc getRefName(fullRefName string) string {\n\tif strings.HasPrefix(fullRefName, git.TagPrefix) {\n\t\treturn fullRefName[len(git.TagPrefix):]\n\t} else if strings.HasPrefix(fullRefName, git.BranchPrefix) {\n\t\treturn fullRefName[len(git.BranchPrefix):]\n\t}\n\treturn \"\"\n}\n\n\n\n\nfunc CacheRef(repo *models.Repository, gitRepo *git.Repository, fullRefName string) error ", "output": "{\n\tif !setting.CacheService.LastCommit.Enabled {\n\t\treturn nil\n\t}\n\n\tcommit, err := gitRepo.GetCommit(fullRefName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcommitsCount, err := cache.GetInt64(repo.GetCommitsCountCacheKey(getRefName(fullRefName), true), commit.CommitsCount)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif commitsCount < setting.CacheService.LastCommit.CommitsCount {\n\t\treturn nil\n\t}\n\n\tcommitCache := git.NewLastCommitCache(repo.FullName(), gitRepo, setting.LastCommitCacheTTLSeconds, cache.GetCache())\n\n\treturn commitCache.CacheCommit(commit)\n}"} {"input": "package state\n\nimport (\n\t\"strconv\"\n\t. \"bugnuts/maps\"\n\t. \"bugnuts/torus\"\n\t. \"bugnuts/util\"\n)\n\n\n\nfunc (s *State) HillLocations(player int) (l []Location) {\n\tfor loc, hill := range s.Hills {\n\t\tif hill.Player == player && hill.Killed == 0 {\n\t\t\tl = append(l, Location(loc))\n\t\t}\n\t}\n\n\treturn l\n}\n\nfunc (s *State) EnemyHillLocations(player int) (l []Location) {\n\tfor loc, hill := range s.Hills {\n\t\tif hill.Player != player && hill.Killed == 0 {\n\t\t\tl = append(l, Location(loc))\n\t\t}\n\t}\n\n\treturn l\n}\n\nfunc (s *State) ValidStep(loc Location) bool {\n\ti := s.Map.Grid[loc]\n\n\treturn i != WATER && i != BLOCK && i != OCCUPIED && i != FOOD && i != MY_ANT && i != MY_HILLANT\n}\n\nfunc (s *State) Stepable(loc Location) bool {\n\ti := s.Map.Grid[loc]\n\n\treturn i != WATER && i != BLOCK && i != FOOD\n}\n\nfunc (m *Metrics) DumpSeen() string {\n\tmax := Max(m.Seen)\n\tstr := \"\"\n\n\tfor r := 0; r < m.Rows; r++ {\n\t\tfor c := 0; c < m.Cols; c++ {\n\t\t\tstr += strconv.Itoa(m.Seen[r*m.Cols+c] * 10 / (max + 1))\n\t\t}\n\t\tstr += \"\\n\"\n\t}\n\n\treturn str\n}\n\nfunc (s *State) FoodLocations() (l []Location) ", "output": "{\n\tfor loc := range s.Food {\n\t\tl = append(l, Location(loc))\n\t}\n\n\treturn l\n}"} {"input": "package sched\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"bosun.org/cmd/bosun/cache\"\n\t\"bosun.org/cmd/bosun/conf\"\n\t\"bosun.org/slog\"\n)\n\n\nfunc (s *Schedule) Run() error {\n\tif s.RuleConf == nil || s.SystemConf == nil {\n\t\treturn fmt.Errorf(\"sched: nil configuration\")\n\t}\n\ts.nc = make(chan interface{}, 1)\n\tif s.SystemConf.GetPing() {\n\t\tgo s.PingHosts()\n\t}\n\tgo s.dispatchNotifications()\n\tgo s.updateCheckContext()\n\tfor _, a := range s.RuleConf.GetAlerts() {\n\t\tgo s.RunAlert(a)\n\t}\n\treturn nil\n}\n\nfunc (s *Schedule) updateCheckContext() {\n\tfor {\n\t\tctx := &checkContext{utcNow(), cache.New(0)}\n\t\ts.ctx = ctx\n\t\ttime.Sleep(s.SystemConf.GetCheckFrequency())\n\t\ts.Lock(\"CollectStates\")\n\t\ts.CollectStates()\n\t\ts.Unlock()\n\t}\n}\n\nfunc (s *Schedule) RunAlert(a *conf.Alert) {\n\ts.checksRunning.Add(1)\n\tdefer s.checksRunning.Done()\n\tfor {\n\t\trunEvery := s.SystemConf.GetDefaultRunEvery()\n\t\tif a.RunEvery != 0 {\n\t\t\trunEvery = a.RunEvery\n\t\t}\n\t\twait := time.After(s.SystemConf.GetCheckFrequency() * time.Duration(runEvery))\n\t\ts.checkAlert(a)\n\t\ts.LastCheck = utcNow()\n\t\tselect {\n\t\tcase <-wait:\n\t\tcase <-s.runnerContext.Done():\n\t\t\tslog.Infof(\"Stopping alert routine for %v\\n\", a.Name)\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n\nfunc (s *Schedule) checkAlert(a *conf.Alert) ", "output": "{\n\tcheckTime := s.ctx.runTime\n\tcheckCache := s.ctx.checkCache\n\trh := s.NewRunHistory(checkTime, checkCache)\n\tcancelled := s.CheckAlert(nil, rh, a)\n\tif cancelled {\n\t\treturn\n\t}\n\tstart := utcNow()\n\ts.RunHistory(rh)\n\tslog.Infof(\"runHistory on %s took %v\\n\", a.Name, time.Since(start))\n}"} {"input": "package mock\n\nimport (\n\t\"time\"\n)\n\ntype Clock struct {\n\tAdded []uint\n\tRemoved []chan time.Time\n\tEta float64\n}\n\nfunc NewClock() *Clock {\n\tm := &Clock{\n\t\tAdded: []uint{},\n\t\tRemoved: []chan time.Time{},\n\t}\n\treturn m\n}\n\nfunc (m *Clock) Add(c chan time.Time, t uint, sync bool) {\n\tm.Added = append(m.Added, t)\n}\n\n\n\nfunc (m *Clock) ETA(c chan time.Time) float64 {\n\treturn m.Eta\n}\n\nfunc (m *Clock) Remove(c chan time.Time) ", "output": "{\n\tm.Removed = append(m.Removed, c)\n}"} {"input": "package toplevel\n\nimport (\n\t\"github.com/astaxie/beego/orm\"\n\t_ \"github.com/go-sql-driver/mysql\"\n\t\"log\"\n\t\"os\"\n)\n\nvar G_ORM orm.Ormer\n\n\n\nfunc InitBeegoOrm() ", "output": "{\n\torm.RegisterDriver(\"mysql\", orm.DRMySQL)\n\torm.RegisterDataBase(\"default\", \"mysql\", G_Config.MallDb.MysqlConn, G_Config.MallDb.MysqlConnectPoolSize/2,\n\t\tG_Config.MallDb.MysqlConnectPoolSize)\n\torm.Debug = true\n\tsql_log_fp, err := os.OpenFile(G_Config.LogDir+\"/\"+G_Config.LogFile+\".mysql\", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)\n\tif err != nil {\n\t\tlog.Fatalf(\"open file[%s.mysql] failed[%s]\", G_Config.LogFile, err)\n\t\treturn\n\t}\n\n\torm.DebugLog = orm.NewLog(sql_log_fp)\n\n\to := orm.NewOrm()\n\to.Using(\"default\")\n\n\tG_ORM = o\n}"} {"input": "package lock\n\nimport (\n\t\"testing\"\n\n\t. \"gopkg.in/check.v1\"\n)\n\n\nfunc Test(t *testing.T) {\n\tTestingT(t)\n}\n\ntype LockSuite struct{}\n\nvar _ = Suite(&LockSuite{})\n\nfunc (s *LockSuite) TestLock(c *C) {\n\tvar lock1 RWMutex\n\tlock1.Lock()\n\tlock1.Unlock()\n\n\tlock1.RLock()\n\tlock1.RLock()\n\tlock1.RUnlock()\n\tlock1.RUnlock()\n\n\tvar lock2 Mutex\n\tlock2.Lock()\n\tlock2.Unlock()\n}\n\n\n\nfunc (s *LockSuite) TestDebugLock(c *C) ", "output": "{\n\tvar lock1 RWMutexDebug\n\tlock1.Lock()\n\tlock1.Unlock()\n\n\tlock1.RLock()\n\tlock1.RLock()\n\tlock1.RUnlock()\n\tlock1.RUnlock()\n\n\tvar lock2 MutexDebug\n\tlock2.Lock()\n\tlock2.Unlock()\n}"} {"input": "package logger\n\nimport (\n\t\"os\"\n\t\"syscall\"\n)\n\n\n\nfunc tryRedirectStderrTo(f *os.File) error ", "output": "{\n\treturn syscall.Dup2(int(f.Fd()), 2)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\n\ntype Player struct {\n\tID string\n\tName string\n\tHealth int\n\tHunger int\n\tCriticalHunger bool\n\tNextAction int\n\tDead bool\n}\n\n\n\n\nfunc (p *Player) String() string {\n\treturn fmt.Sprintf(\"[%-12s](HP: %3d)\", p.Name, p.Health, p.Hunger)\n}\n\n\nfunc (p *Player) AddHealth(amount int) bool {\n\tp.Health += amount\n\tif p.Health > 100 {\n\t\tp.Health = 100\n\t}\n\tif p.Health <= 0 {\n\t\tp.Health = 0\n\t\tp.Dead = true\n\t\treturn true\n\t}\n\treturn false\n}\n\n\nfunc (p *Player) AddHunger(amount int) int {\n\tp.Hunger += amount\n\tif p.Hunger >= 100 {\n\t\tp.Hunger = 100\n\t\tif p.CriticalHunger {\n\t\t\treturn 2\n\t\t}\n\t\tp.CriticalHunger = true\n\t\treturn 1\n\t}\n\tif p.Hunger <= 0 {\n\t\tp.Hunger = 0\n\t}\n\treturn 0\n}\n\nfunc NewPlayer(ID, name string) *Player ", "output": "{\n\treturn &Player{ID, name, 100, 0, false, 0, false}\n}"} {"input": "package rabbitgo\n\nimport (\n \"testing\"\n . \"github.com/smartystreets/goconvey/convey\"\n \n \"github.com/golang/protobuf/proto\"\n \"github.com/entropyx/rabbitgo/pb\"\n)\n\n\n\nfunc TestDelivery(t *testing.T) ", "output": "{\n Convey(\"Given a new delivery\", t, func() {\n delivery := &Delivery{}\n\n Convey(\"When a proto is sent as the response\", func() {\n test := &pb.Test{Text: \"some text\"}\n delivery.Proto(test)\n\n Convey(\"The unmarshaled body should be the same as the proto\", func() {\n newTest := &pb.Test{}\n proto.Unmarshal(delivery.Response.Body, newTest)\n So(newTest.Text, ShouldEqual, test.Text)\n })\n })\n })\n}"} {"input": "package client\n\nimport (\n\t\"context\"\n\t\"strconv\"\n\n\t\"github.com/containerd/containerd/containers\"\n\t\"github.com/containerd/containerd/oci\"\n\tspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n)\n\nconst newLine = \"\\r\\n\"\n\nfunc withExitStatus(es int) oci.SpecOpts {\n\treturn func(_ context.Context, _ oci.Client, _ *containers.Container, s *specs.Spec) error {\n\t\ts.Process.Args = []string{\"cmd\", \"/c\", \"exit\", strconv.Itoa(es)}\n\t\treturn nil\n\t}\n}\n\nfunc withProcessArgs(args ...string) oci.SpecOpts {\n\treturn oci.WithProcessArgs(append([]string{\"cmd\", \"/c\"}, args...)...)\n}\n\nfunc withCat() oci.SpecOpts {\n\treturn oci.WithProcessArgs(\"cmd\", \"/c\", \"more\")\n}\n\nfunc withTrue() oci.SpecOpts {\n\treturn oci.WithProcessArgs(\"cmd\", \"/c\")\n}\n\nfunc withExecExitStatus(s *specs.Process, es int) {\n\ts.Args = []string{\"cmd\", \"/c\", \"exit\", strconv.Itoa(es)}\n}\n\n\n\nfunc withExecArgs(s *specs.Process, args ...string) ", "output": "{\n\ts.Args = append([]string{\"cmd\", \"/c\"}, args...)\n}"} {"input": "package ignition\n\nimport (\n\t\"github.com/coreos/ignition/config/types\"\n\t\"github.com/hashicorp/terraform/helper/schema\"\n)\n\nfunc resourceGroup() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceGroupCreate,\n\t\tDelete: resourceGroupDelete,\n\t\tExists: resourceGroupExists,\n\t\tRead: resourceGroupRead,\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"name\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"gid\": &schema.Schema{\n\t\t\t\tType: schema.TypeInt,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"password_hash\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceGroupCreate(d *schema.ResourceData, meta interface{}) error {\n\tid, err := buildGroup(d, meta.(*cache))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.SetId(id)\n\treturn nil\n}\n\nfunc resourceGroupDelete(d *schema.ResourceData, meta interface{}) error {\n\td.SetId(\"\")\n\treturn nil\n}\n\nfunc resourceGroupExists(d *schema.ResourceData, meta interface{}) (bool, error) {\n\tid, err := buildGroup(d, meta.(*cache))\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn id == d.Id(), nil\n}\n\nfunc resourceGroupRead(d *schema.ResourceData, meta interface{}) error {\n\treturn nil\n}\n\n\n\nfunc buildGroup(d *schema.ResourceData, c *cache) (string, error) ", "output": "{\n\treturn c.addGroup(&types.Group{\n\t\tName: d.Get(\"name\").(string),\n\t\tPasswordHash: d.Get(\"password_hash\").(string),\n\t\tGid: getUInt(d, \"gid\"),\n\t}), nil\n}"} {"input": "package dao\n\nimport (\n\t\"context\"\n\n\t\"go-common/app/job/live/push-search/conf\"\n\t\"go-common/library/queue/databus\"\n\t\"go-common/library/database/hbase.v2\"\n)\n\n\ntype Dao struct {\n\tc *conf.Config\n\tRoomInfoDataBus *databus.Databus\n\tAttentionDataBus *databus.Databus\n\tUserNameDataBus *databus.Databus\n\tPushSearchDataBus *databus.Databus\n\tSearchHBase *hbase.Client\n}\n\n\n\n\n\nfunc (d *Dao) Close() {\n\td.RoomInfoDataBus.Close()\n\td.AttentionDataBus.Close()\n\td.UserNameDataBus.Close()\n\treturn\n}\n\n\nfunc (d *Dao) Ping(c context.Context) error {\n\treturn nil\n}\n\nfunc New(c *conf.Config) (dao *Dao) ", "output": "{\n\tdao = &Dao{\n\t\tc: c,\n\t\tRoomInfoDataBus: databus.New(c.DataBus.RoomInfo),\n\t\tAttentionDataBus: databus.New(c.DataBus.Attention),\n\t\tUserNameDataBus: databus.New(c.DataBus.UserName),\n\t\tPushSearchDataBus: databus.New(c.DataBus.PushSearch),\n\t\tSearchHBase: hbase.NewClient(&c.SearchHBase.Config),\n\t}\n\treturn\n}"} {"input": "package certstore\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n)\n\n\n\nfunc TestMain(m *testing.M) ", "output": "{\n\tfmt.Println(\"CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG\")\n\twinAPIFlag = 0x00010000\n\tif status := m.Run(); status != 0 {\n\t\tos.Exit(status)\n\t}\n\n\tfmt.Println(\"CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG\")\n\twinAPIFlag = 0x00020000\n\tif status := m.Run(); status != 0 {\n\t\tos.Exit(status)\n\t}\n\n\tos.Exit(0)\n}"} {"input": "package pmgo\n\nimport mgo \"gopkg.in/mgo.v2\"\n\ntype IterManager interface {\n\tAll(result interface{}) error\n\tClose() error\n\tDone() bool\n\tErr() error\n\tFor(result interface{}, f func() error) (err error)\n\tNext(result interface{}) bool\n\tTimeout() bool\n}\n\ntype Iter struct {\n\titer *mgo.Iter\n}\n\nfunc NewIter(iter *mgo.Iter) IterManager {\n\treturn &Iter{iter}\n}\n\n\n\nfunc (i *Iter) Close() error {\n\treturn i.iter.Close()\n}\n\nfunc (i *Iter) Done() bool {\n\treturn i.iter.Done()\n}\n\nfunc (i *Iter) Err() error {\n\treturn i.iter.Err()\n}\n\nfunc (i *Iter) For(result interface{}, f func() error) (err error) {\n\treturn i.iter.For(result, f)\n}\n\nfunc (i *Iter) Next(result interface{}) bool {\n\treturn i.iter.Next(result)\n}\n\nfunc (i *Iter) Timeout() bool {\n\treturn i.iter.Timeout()\n}\n\nfunc (i *Iter) All(result interface{}) error ", "output": "{\n\treturn i.iter.All(result)\n}"} {"input": "package main\n\n\n\nimport (\n\t\"github.com/faceless-saint/go-socketcmd\"\n\n\t\"errors\"\n\t\"os\"\n)\n\nconst EnvSocketPath = \"SOCKET_PATH\"\n\nvar ExampleSocketPath = \"@example.sock\"\n\n\n\nfunc main() {\n\tif len(os.Args) < 2 {\n\t\tpanic(errors.New(\"not enough arguments - you must specify a command\"))\n\t}\n\tvar args []string\n\tif len(os.Args) > 2 {\n\t\targs = os.Args[2:]\n\t}\n\tcmd := socketcmd.Cmd(os.Args[1], args...)\n\n\ts, err := socketcmd.NewUnix(ExampleSocketPath, cmd)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := s.Run(); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc init() ", "output": "{\n\tenvPath := os.Getenv(EnvSocketPath)\n\tif envPath != \"\" {\n\t\tExampleSocketPath = envPath\n\t}\n}"} {"input": "package subject\n\nimport (\n\t\"testing\"\n\t\"reflect\"\n)\n\nfunc TestLoadSubject(t *testing.T) {\n\tpath := \"../../example/subject.csv\"\n\texpect := [][]string{{\"A01\", \"Shibuya Rin\", \"100\"}, {\"A02\", \"\", \"200\"}}\n\n\tres, err := LoadSubject(path)\n\n\tif !(reflect.DeepEqual(res, expect) && err == nil) {\n\t\tt.Errorf(\"Failed to load and parse csv. result: %s, error: %s\", res, err)\n\t}\n}\n\nfunc TestLoadSubject_LoadError(t *testing.T) {\n\tpath := \"/path/to/nowhere.csv\"\n\n\tres, err := LoadSubject(path)\n\n\tif !(res == nil && err != nil) {\n\t\tt.Errorf(\"Failed to raise error properly. result: %s, error: %s\", res, err)\n\t}\n}\n\n\n\nfunc TestLoadSubject_ParseError(t *testing.T) ", "output": "{\n\tpath := \"/tmp/\"\n\n\tres, err := LoadSubject(path)\n\n\tif !(res == nil && err != nil) {\n\t\tt.Errorf(\"Failed to raise error properly. result: %s, error: %s\", res, err)\n\t}\n}"} {"input": "package kiiroo\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"runtime\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/funjack/launchcontrol/protocol\"\n)\n\n\nvar scenario = \"{1.00:1,1.50:4,1.51:4,1.51:3,1.52:4,1.66:1,1.84:2,1.85:3,1.90:4,1.95:1,2.00:2,2.20:4,2.45:2}\"\n\nfunc playerwithscenario(scenario string) (protocol.Player, error) {\n\tb := bytes.NewBufferString(scenario)\n\treturn Load(b)\n}\n\ntype actionValidator struct {\n\tLastPostion int\n\tLastTime time.Duration\n}\n\n\n\n\n\nfunc TestPlay(t *testing.T) {\n\tif runtime.GOOS == \"darwin\" {\n\t\tt.Skip(\"don't run timing tests on darwin #17610\")\n\t}\n\n\tk, err := playerwithscenario(scenario)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tav := actionValidator{}\n\tstarttime := time.Now()\n\tfor a := range k.Play() {\n\t\teventtime := time.Now().Sub(starttime)\n\t\tt.Logf(\"Action: %s: %d,%d\", eventtime, a.Position, a.Speed)\n\t\tif err := av.Validate(a.Position, eventtime); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}\n}\n\nfunc (a *actionValidator) Validate(p int, t time.Duration) error ", "output": "{\n\tdefer func() {\n\t\ta.LastPostion = p\n\t\ta.LastTime = t\n\t}()\n\n\tif p == a.LastPostion {\n\t\treturn fmt.Errorf(\"received the same position in a row\")\n\t}\n\tif a.LastTime > 0 && (t-a.LastTime) < (time.Millisecond*150) {\n\t\treturn fmt.Errorf(\"time between events not big enough: %s\", t-a.LastTime)\n\t}\n\treturn nil\n}"} {"input": "package windows\n\nimport (\n\t\"github.com/docker/docker/daemon/execdriver\"\n\t\"github.com/docker/engine-api/types/container\"\n)\n\ntype info struct {\n\tID string\n\tdriver *Driver\n\tisolation container.IsolationLevel\n}\n\n\n\n\nfunc (i *info) IsRunning() bool {\n\tvar running bool\n\trunning = true \n\treturn running\n}\n\nfunc (d *Driver) Info(id string) execdriver.Info ", "output": "{\n\treturn &info{\n\t\tID: id,\n\t\tdriver: d,\n\t\tisolation: DefaultIsolation,\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"sort\"\n)\n\n\ntype RankedCoordFinder struct {\n\tboard Board\n\tremaining []*Coord\n}\n\nfunc (f *RankedCoordFinder) NextOpenCoordinate(board Board, coord XY) (*Coord, bool) {\n\tf.board = board\n\tf.RefreshCoordinates()\n\n\tif len(f.remaining) == 0 {\n\t\treturn nil, false\n\t}\n\n\tc := f.remaining[0]\n\tf.remaining = f.remaining[0:]\n\n\treturn c, true\n}\n\n\n\nfunc (f *RankedCoordFinder) Len() int {\n\treturn len(f.remaining)\n}\nfunc (f *RankedCoordFinder) Less(i, j int) bool {\n\treturn len(f.board.AvailableValuesAtCoordinate(f.remaining[i])) <\n\t\tlen(f.board.AvailableValuesAtCoordinate(f.remaining[j]))\n}\nfunc (f *RankedCoordFinder) Swap(i, j int) {\n\tf.remaining[i], f.remaining[j] = f.remaining[j], f.remaining[i]\n}\n\nfunc (f *RankedCoordFinder) RefreshCoordinates() ", "output": "{\n\tf.remaining = []*Coord{}\n\tfor x := 0; x < len(f.board); x++ {\n\t\tfor y := 0; y < len(f.board); y++ {\n\t\t\tif f.board[x][y] == 0 {\n\t\t\t\tf.remaining = append(f.remaining, &Coord{x, y})\n\t\t\t}\n\t\t}\n\t}\n\tsort.Sort(f)\n}"} {"input": "package label\n\n\n\n\nfunc InitLabels(mcsdir string, options []string) (string, string, error) {\n\treturn \"\", \"\", nil\n}\n\n\n\nfunc SetProcessLabel(processLabel string) error {\n\treturn nil\n}\n\nfunc SetFileLabel(path string, fileLabel string) error {\n\treturn nil\n}\n\nfunc SetFileCreateLabel(fileLabel string) error {\n\treturn nil\n}\n\nfunc Relabel(path string, fileLabel string, relabel string) error {\n\treturn nil\n}\n\nfunc GetPidLabel(pid int) (string, error) {\n\treturn \"\", nil\n}\n\nfunc Init() {\n}\n\nfunc ReserveLabel(label string) error {\n\treturn nil\n}\n\nfunc UnreserveLabel(label string) error {\n\treturn nil\n}\n\n\n\nfunc DupSecOpt(src string) []string {\n\treturn nil\n}\n\n\n\nfunc DisableSecOpt() []string {\n\treturn nil\n}\n\nfunc FormatMountLabel(src string, mountLabel string) string ", "output": "{\n\treturn src\n}"} {"input": "package depsync\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\n\t\"github.com/go-kit/kit/endpoint\"\n)\n\nfunc (s *DEPSyncService) SyncNow(_ context.Context) error {\n\ts.syncer.SyncNow()\n\treturn nil\n}\n\ntype syncNowResponse struct{}\ntype syncNowRequest struct{}\n\nfunc MakeSyncNowEndpoint(s Service) endpoint.Endpoint {\n\treturn func(ctx context.Context, _ interface{}) (interface{}, error) {\n\t\ts.SyncNow(ctx)\n\t\treturn syncNowResponse{}, nil\n\t}\n}\n\nfunc decodeEmptyRequest(ctx context.Context, r *http.Request) (interface{}, error) {\n\treturn nil, nil\n}\n\n\n\nfunc decodeEmptyResponse(ctx context.Context, r *http.Response) (interface{}, error) {\n\treturn nil, nil\n}\n\nfunc (e Endpoints) SyncNow(ctx context.Context) error {\n\t_, err := e.SyncNowEndpoint(ctx, nil)\n\treturn err\n}\n\nfunc encodeEmptyResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error ", "output": "{\n\treturn nil\n}"} {"input": "package containerregistry\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\nfunc UserAgent() string {\n\treturn \"Azure-SDK-For-Go/\" + Version() + \" containerregistry/2018-09-01\"\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn version.Number\n}"} {"input": "package result\n\ntype Classic struct {\n\tid int\n\tfitness float64\n\terr error\n\tstop bool\n}\n\nfunc New(id int, fitness float64, err error, stop bool) Classic {\n\treturn Classic{id, fitness, err, stop}\n}\n\n\nfunc (r Classic) ID() int { return r.id }\n\n\nfunc (r Classic) Fitness() float64 { return r.fitness }\n\n\nfunc (r Classic) Err() error { return r.err }\n\n\n\n\nfunc (r Classic) Stop() bool ", "output": "{ return r.stop }"} {"input": "package trace\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\n\ntype Tracer interface {\n\tTrace(...interface{})\n}\n\ntype tracer struct {\n\tout io.Writer\n}\n\nfunc (t *tracer) Trace(a ...interface{}) {\n\tt.out.Write([]byte(fmt.Sprint(a...)))\n\tt.out.Write([]byte(\"\\n\"))\n}\n\ntype nilTracer struct{}\n\nfunc (t *nilTracer) Trace(a ...interface{}) {}\n\n\n\n\nfunc New(w io.Writer) Tracer {\n\treturn &tracer{out: w}\n}\n\nfunc Off() Tracer ", "output": "{\n\treturn &nilTracer{}\n}"} {"input": "package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\n\t\"github.com/Shopify/toxiproxy/stream\"\n\t\"github.com/Shopify/toxiproxy/toxics\"\n)\n\ntype HttpResponseToxic struct {\n\tHttpBody string `json:\"body\"`\n\tHttpStatusCode int `json:\"code\"`\n\tHttpStatusText string `json:\"status\"`\n}\n\nfunc (t *HttpResponseToxic) ModifyResponse(resp *http.Response) {\n\tif t.HttpBody != \"\" {\n\t\tresp.Body = ioutil.NopCloser(bytes.NewBufferString(t.HttpBody))\n\t\tresp.ContentLength = int64(len(t.HttpBody))\n\t}\n\tif t.HttpStatusCode > 0 {\n\t\tresp.StatusCode = t.HttpStatusCode\n\t}\n\tif t.HttpStatusText != \"\" {\n\t\tresp.Status = t.HttpStatusText\n\t}\n}\n\nfunc (t *HttpResponseToxic) Pipe(stub *toxics.ToxicStub) {\n\tbuffer := bytes.NewBuffer(make([]byte, 0, 32*1024))\n\twriter := stream.NewChanWriter(stub.Output)\n\treader := stream.NewChanReader(stub.Input)\n\treader.SetInterrupt(stub.Interrupt)\n\tfor {\n\t\ttee := io.TeeReader(reader, buffer)\n\t\tresp, err := http.ReadResponse(bufio.NewReader(tee), nil)\n\t\tif err == stream.ErrInterrupted {\n\t\t\tbuffer.WriteTo(writer)\n\t\t\treturn\n\t\t} else if err == io.EOF {\n\t\t\tstub.Close()\n\t\t\treturn\n\t\t}\n\t\tif err != nil {\n\t\t\tbuffer.WriteTo(writer)\n\t\t} else {\n\t\t\tt.ModifyResponse(resp)\n\t\t\tresp.Write(writer)\n\t\t}\n\t\tbuffer.Reset()\n\t}\n}\n\n\n\nfunc init() ", "output": "{\n\ttoxics.Register(\"response\", new(HttpResponseToxic))\n}"} {"input": "package api_xhr\n\nimport (\n\t\"compress/gzip\"\n\t\"encoding/json\"\n\t\"io\"\n\t\"net/http\"\n\n\t\"github.com/deze333/vroom/reqres\"\n)\n\n\n\n\n\n\nfunc ParseReq(w http.ResponseWriter, r *http.Request) (req *reqres.Req, err error) {\n\n\tparams := map[string]interface{}{}\n\n\tswitch r.Header.Get(\"Content-Encoding\") {\n\tcase \"gzip\":\n\t\tparams, err = decodeAsGzipReq(r)\n\n\tdefault:\n\t\tparams, err = decodeAsUnencodedReq(r)\n\t}\n\n\treq = &reqres.Req{\n\t\tParams: params,\n\t\tHttpReq: r,\n\t\tHttpResWriter: w,\n\t}\n\treturn\n}\n\n\n\n\nfunc decodeAsGzipReq(r *http.Request) (params map[string]interface{}, err error) {\n\n\tvar reader *gzip.Reader\n\treader, err = gzip.NewReader(r.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdecoder := json.NewDecoder(reader)\n\terr = decoder.Decode(¶ms)\n\n\tif err == io.EOF {\n\t\terr = nil\n\t}\n\n\treturn\n}\n\nfunc decodeAsUnencodedReq(r *http.Request) (params map[string]interface{}, err error) ", "output": "{\n\n\tdecoder := json.NewDecoder(r.Body)\n\terr = decoder.Decode(¶ms)\n\n\tif err == io.EOF {\n\t\terr = nil\n\t}\n\n\treturn\n}"} {"input": "package tempconv\n\nimport \"testing\"\n\nfunc TestCToF(t *testing.T) {\n\tvar c Celsius = 37\n\tf := CToF(c)\n\tif f != Fahrenheit(98.6) {\n\t\tt.Errorf(`CToF(%g) == %g failed`, c, f)\n\t}\n}\n\n\n\nfunc TestCToK(t *testing.T) {\n\tvar c Celsius = 37\n\tk := CToK(c)\n\tif k != Kelvin(310.15) {\n\t\tt.Errorf(`CToK(%g) == %g failed`, c, k)\n\t}\n}\n\nfunc TestKToC(t *testing.T) {\n\tvar k Kelvin = 1000\n\tc := KToC(k)\n\tif c != Celsius(726.85) {\n\t\tt.Errorf(`KToC(%g) == %g failed`, k, c)\n\t}\n}\n\nfunc TestFToC(t *testing.T) ", "output": "{\n\tvar f Fahrenheit = 95\n\tc := FToC(f)\n\tif c != Celsius(35) {\n\t\tt.Errorf(`FToC(%g) == %g failed`, f, c)\n\t}\n}"} {"input": "package analytics\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n\t\"testing\"\n\t\"time\"\n\n\tadaptertest \"istio.io/istio/mixer/pkg/adapter/test\"\n)\n\n\n\nfunc TestStandardSelect(t *testing.T) {\n\n\tenv := adaptertest.NewEnv(t)\n\n\topts := Options{\n\t\tBufferPath: \"/tmp/apigee-ax/buffer/\",\n\t\tStagingFileLimit: 10,\n\t\tBaseURL: &url.URL{},\n\t\tKey: \"key\",\n\t\tSecret: \"secret\",\n\t\tClient: http.DefaultClient,\n\t\tnow: time.Now,\n\t\tCollectionInterval: time.Minute,\n\t}\n\n\tm, err := NewManager(env, opts)\n\tif err != nil {\n\t\tt.Fatalf(\"newManager: %s\", err)\n\t}\n\tm.Close()\n\n\tif _, ok := m.(*manager); !ok {\n\t\tt.Errorf(\"want an *manager type, got: %#v\", m)\n\t}\n}\n\nfunc TestStandardBadOptions(t *testing.T) {\n\n\tenv := adaptertest.NewEnv(t)\n\n\topts := Options{\n\t\tBufferPath: \"/tmp/apigee-ax/buffer/\",\n\t\tStagingFileLimit: 0,\n\t\tBaseURL: &url.URL{},\n\t\tKey: \"\",\n\t\tSecret: \"\",\n\t\tClient: http.DefaultClient,\n\t\tnow: time.Now,\n\t}\n\n\twant := \"all analytics options are required\"\n\tm, err := NewManager(env, opts)\n\tif err == nil || err.Error() != want {\n\t\tt.Errorf(\"want: %s, got: %s\", want, err)\n\t}\n\tif m != nil {\n\t\tt.Errorf(\"should not get manager\")\n\t\tm.Close()\n\t}\n}\n\nfunc TestLegacySelect(t *testing.T) ", "output": "{\n\n\tenv := adaptertest.NewEnv(t)\n\n\topts := Options{\n\t\tLegacyEndpoint: true,\n\t\tBufferPath: \"\",\n\t\tStagingFileLimit: 10,\n\t\tBaseURL: &url.URL{},\n\t\tKey: \"key\",\n\t\tSecret: \"secret\",\n\t\tClient: http.DefaultClient,\n\t\tnow: time.Now,\n\t}\n\n\tm, err := NewManager(env, opts)\n\tm.Close()\n\tif err != nil {\n\t\tt.Fatalf(\"newManager: %s\", err)\n\t}\n\n\tif _, ok := m.(*legacyAnalytics); !ok {\n\t\tt.Errorf(\"want an *legacyAnalytics type, got: %#v\", m)\n\t}\n}"} {"input": "package main\nimport (\n\"time\"\n\"fmt\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar deposits = make (chan int)\nvar balances = make (chan int)\nfunc Deposit(amount int){\n\tdeposits<-amount\n}\n\nfunc teller(){\n\tvar balance int\n\tfor{\n\t\tselect{\n\t\t\tcase amount:=<-deposits:\n\t\t\t\tbalance+=amount\n\t\t\tcase balances<-balance:\n\t\t}\n\t}\n}\n\nfunc init(){\n\tgo teller()\n}\nfunc main() {\n\tgo func(){\n\t\tDeposit(200)\n\t\tfmt.Println(\"=\",Balance()) \n\t}()\n\n\tgo func(){\n\t\tDeposit(100)\n\t}()\n\ttime.Sleep(time.Second*1)\n}\n\nfunc Balance() int", "output": "{\n\treturn <-balances\n}"} {"input": "package gtimer\n\n\n\n\n\n\nfunc (h *priorityQueueHeap) Less(i, j int) bool {\n\treturn h.array[i].priority < h.array[j].priority\n}\n\n\nfunc (h *priorityQueueHeap) Swap(i, j int) {\n\tif len(h.array) == 0 {\n\t\treturn\n\t}\n\th.array[i], h.array[j] = h.array[j], h.array[i]\n}\n\n\nfunc (h *priorityQueueHeap) Push(x interface{}) {\n\th.array = append(h.array, x.(priorityQueueItem))\n}\n\n\nfunc (h *priorityQueueHeap) Pop() interface{} {\n\tlength := len(h.array)\n\tif length == 0 {\n\t\treturn nil\n\t}\n\titem := h.array[length-1]\n\th.array = h.array[0 : length-1]\n\treturn item\n}\n\nfunc (h *priorityQueueHeap) Len() int ", "output": "{\n\treturn len(h.array)\n}"} {"input": "package rules\n\nimport (\n\t\"regexp\"\n\t\"strings\"\n)\n\n\ntype Checker interface {\n\tCheck(path string) bool\n}\n\n\ntype Rule struct {\n\tRegex bool `json:\"regex\"`\n\tAllow bool `json:\"allow\"`\n\tPath string `json:\"path\"`\n\tRegexp *Regexp `json:\"regexp\"`\n}\n\n\nfunc (r *Rule) Matches(path string) bool {\n\tif r.Regex {\n\t\treturn r.Regexp.MatchString(path)\n\t}\n\n\treturn strings.HasPrefix(path, r.Path)\n}\n\n\n\ntype Regexp struct {\n\tRaw string `json:\"raw\"`\n\tregexp *regexp.Regexp\n}\n\n\n\n\nfunc (r *Regexp) MatchString(s string) bool ", "output": "{\n\tif r.regexp == nil {\n\t\tr.regexp = regexp.MustCompile(r.Raw)\n\t}\n\n\treturn r.regexp.MatchString(s)\n}"} {"input": "package elasticsearch_test\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"testing\"\n)\n\n\n\n\ntype Test struct{}\n\n\nfunc (t *Test) Assert(tb testing.TB, condition bool, msg string, v ...interface{}) {\n\tif !condition {\n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfmt.Printf(\"\\033[31m%s:%d: \"+msg+\"\\033[39m\\n\\n\", append([]interface{}{filepath.Base(file), line}, v...)...)\n\t\ttb.FailNow()\n\t}\n}\n\n\nfunc (t *Test) OK(tb testing.TB, err error) {\n\tif err != nil {\n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfmt.Printf(\"\\033[31m%s:%d: unexpected error: %s\\033[39m\\n\\n\", filepath.Base(file), line, err.Error())\n\t\ttb.FailNow()\n\t}\n}\n\n\n\n\nfunc (t *Test) Equals(tb testing.TB, exp, act interface{}) ", "output": "{\n\tif !reflect.DeepEqual(exp, act) {\n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfmt.Printf(\"\\033[31m%s:%d:\\n\\n\\texp: %#v\\n\\n\\tgot: %#v\\033[39m\\n\\n\", filepath.Base(file), line, exp, act)\n\t\ttb.FailNow()\n\t}\n}"} {"input": "package wraps\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-on/wrap\"\n)\n\n\n\ntype Catcher interface {\n\tCatch(recovered interface{}, w http.ResponseWriter, r *http.Request)\n}\n\n\ntype CatchFunc func(recovered interface{}, w http.ResponseWriter, r *http.Request)\n\n\n\n\n\n\n\nfunc (c CatchFunc) ServeHTTPNext(next http.Handler, wr http.ResponseWriter, req *http.Request) {\n\tchecked := wrap.NewPeek(wr, func(ck *wrap.Peek) bool {\n\t\tck.FlushHeaders()\n\t\tck.FlushCode()\n\t\treturn true\n\t})\n\n\tdefer func() {\n\t\tif p := recover(); p != nil {\n\t\t\tc(p, wr, req)\n\t\t} else {\n\t\t\tchecked.FlushMissing()\n\t\t}\n\t}()\n\n\tnext.ServeHTTP(checked, req)\n}\n\n\nfunc (c CatchFunc) Wrap(next http.Handler) http.Handler {\n\treturn wrap.NextHandler(c).Wrap(next)\n}\n\n\nfunc Catch(c Catcher) wrap.Wrapper {\n\treturn CatchFunc(c.Catch)\n}\n\nfunc (c CatchFunc) Catch(recovered interface{}, w http.ResponseWriter, r *http.Request) ", "output": "{\n\tc(recovered, w, r)\n}"} {"input": "package pagerduty\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/GoogleCloudPlatform/terraformer/terraformutils\"\n\tpagerduty \"github.com/heimweh/go-pagerduty/pagerduty\"\n)\n\ntype ScheduleGenerator struct {\n\tPagerDutyService\n}\n\nfunc (g *ScheduleGenerator) createScheduleResources(client *pagerduty.Client) error {\n\tvar offset = 0\n\toptions := pagerduty.ListSchedulesOptions{}\n\tfor {\n\t\toptions.Offset = offset\n\t\tresp, _, err := client.Schedules.List(&options)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, schedule := range resp.Schedules {\n\t\t\tg.Resources = append(g.Resources, terraformutils.NewSimpleResource(\n\t\t\t\tschedule.ID,\n\t\t\t\tfmt.Sprintf(\"schedule_%s\", schedule.Name),\n\t\t\t\t\"pagerduty_schedule\",\n\t\t\t\tg.ProviderName,\n\t\t\t\t[]string{},\n\t\t\t))\n\t\t}\n\t\tif !resp.More {\n\t\t\tbreak\n\t\t}\n\n\t\toffset += resp.Limit\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (g *ScheduleGenerator) InitResources() error ", "output": "{\n\tclient, err := g.Client()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfuncs := []func(*pagerduty.Client) error{\n\t\tg.createScheduleResources,\n\t}\n\n\tfor _, f := range funcs {\n\t\terr := f(client)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package container\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/martin-helmich/distcrond/domain\"\n)\n\ntype JobContainer struct {\n\tjobs []domain.Job\n\tjobsByName map[string]*domain.Job\n}\n\nfunc NewJobContainer(initialCapacity int) *JobContainer {\n\tcontainer := new(JobContainer)\n\tcontainer.jobs = make([]domain.Job, 0, initialCapacity)\n\tcontainer.jobsByName = make(map[string]*domain.Job)\n\treturn container\n}\n\n\n\nfunc (c *JobContainer) Count() int {\n\treturn len(c.jobs)\n}\n\nfunc (c *JobContainer) All() []domain.Job {\n\treturn c.jobs\n}\n\nfunc (c *JobContainer) Get(i int) *domain.Job {\n\treturn &c.jobs[i]\n}\n\nfunc (c *JobContainer) JobByName(n string) (*domain.Job, error) {\n\tif job, ok := c.jobsByName[n]; !ok {\n\t\treturn nil, errors.New(fmt.Sprintf(\"No job with name '%s' is known\", n))\n\t} else {\n\t\treturn job, nil\n\t}\n}\n\nfunc (c *JobContainer) AddJob(job domain.Job) ", "output": "{\n\tc.jobs = append(c.jobs, job)\n\tc.jobsByName[job.Name] = &c.jobs[len(c.jobs)-1]\n}"} {"input": "package v1\n\nimport (\n\t\"testing\"\n\n\t\"github.com/rackspace/gophercloud\"\n\t\"github.com/rackspace/gophercloud/rackspace/lb/v1/lbs\"\n\t\"github.com/rackspace/gophercloud/rackspace/lb/v1/monitors\"\n\tth \"github.com/rackspace/gophercloud/testhelper\"\n)\n\nfunc TestMonitors(t *testing.T) {\n\tclient := setup(t)\n\n\tids := createLB(t, client, 1)\n\tlbID := ids[0]\n\n\tgetMonitor(t, client, lbID)\n\n\tupdateMonitor(t, client, lbID)\n\n\tdeleteMonitor(t, client, lbID)\n\n\tdeleteLB(t, client, lbID)\n}\n\nfunc getMonitor(t *testing.T, client *gophercloud.ServiceClient, lbID int) {\n\thm, err := monitors.Get(client, lbID).Extract()\n\tth.AssertNoErr(t, err)\n\tt.Logf(\"Health monitor for LB %d: Type [%s] Delay [%d] Timeout [%d] AttemptLimit [%d]\",\n\t\tlbID, hm.Type, hm.Delay, hm.Timeout, hm.AttemptLimit)\n}\n\n\n\nfunc deleteMonitor(t *testing.T, client *gophercloud.ServiceClient, lbID int) {\n\terr := monitors.Delete(client, lbID).ExtractErr()\n\tth.AssertNoErr(t, err)\n\n\twaitForLB(client, lbID, lbs.ACTIVE)\n\tt.Logf(\"Deleted monitor for LB %d\", lbID)\n}\n\nfunc updateMonitor(t *testing.T, client *gophercloud.ServiceClient, lbID int) ", "output": "{\n\topts := monitors.UpdateHTTPMonitorOpts{\n\t\tAttemptLimit: 3,\n\t\tDelay: 10,\n\t\tTimeout: 10,\n\t\tBodyRegex: \"hello is it me you're looking for\",\n\t\tPath: \"/foo\",\n\t\tStatusRegex: \"200\",\n\t\tType: monitors.HTTP,\n\t}\n\n\terr := monitors.Update(client, lbID, opts).ExtractErr()\n\tth.AssertNoErr(t, err)\n\n\twaitForLB(client, lbID, lbs.ACTIVE)\n\tt.Logf(\"Updated monitor for LB %d\", lbID)\n}"} {"input": "package policylist\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/hashicorp/consul/command/acl\"\n\t\"github.com/hashicorp/consul/command/flags\"\n\t\"github.com/mitchellh/cli\"\n)\n\nfunc New(ui cli.Ui) *cmd {\n\tc := &cmd{UI: ui}\n\tc.init()\n\treturn c\n}\n\ntype cmd struct {\n\tUI cli.Ui\n\tflags *flag.FlagSet\n\thttp *flags.HTTPFlags\n\thelp string\n\n\tshowMeta bool\n}\n\n\n\nfunc (c *cmd) Run(args []string) int {\n\tif err := c.flags.Parse(args); err != nil {\n\t\treturn 1\n\t}\n\n\tclient, err := c.http.APIClient()\n\tif err != nil {\n\t\tc.UI.Error(fmt.Sprintf(\"Error connecting to Consul agent: %s\", err))\n\t\treturn 1\n\t}\n\n\tpolicies, _, err := client.ACL().PolicyList(nil)\n\tif err != nil {\n\t\tc.UI.Error(fmt.Sprintf(\"Failed to retrieve the policy list: %v\", err))\n\t\treturn 1\n\t}\n\n\tfor _, policy := range policies {\n\t\tacl.PrintPolicyListEntry(policy, c.UI, c.showMeta)\n\t}\n\n\treturn 0\n}\n\nfunc (c *cmd) Synopsis() string {\n\treturn synopsis\n}\n\nfunc (c *cmd) Help() string {\n\treturn flags.Usage(c.help, nil)\n}\n\nconst synopsis = \"Lists ACL Policies\"\nconst help = `\nUsage: consul acl policy list [options]\n\n Lists all the ACL policies\n\n Example:\n\n $ consul acl policy list\n`\n\nfunc (c *cmd) init() ", "output": "{\n\tc.flags = flag.NewFlagSet(\"\", flag.ContinueOnError)\n\tc.flags.BoolVar(&c.showMeta, \"meta\", false, \"Indicates that policy metadata such \"+\n\t\t\"as the content hash and raft indices should be shown for each entry\")\n\n\tc.http = &flags.HTTPFlags{}\n\tflags.Merge(c.flags, c.http.ClientFlags())\n\tflags.Merge(c.flags, c.http.ServerFlags())\n\tc.help = flags.Usage(help, c.flags)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype geometry interface {\n\tarea() float64\n\tperim() float64\n}\n\ntype square struct {\n\twidth, heigth float64\n}\n\ntype circle struct {\n\tradius float64\n}\n\nfunc (s square) area() float64 {\n\treturn s.width * s.heigth\n}\n\nfunc (s square) perim() float64 {\n\treturn 2*s.width + 2*s.heigth\n}\n\nfunc (c circle) area() float64 {\n\treturn math.Pi * c.radius * c.radius\n}\n\n\n\nfunc measure(g geometry) {\n\tfmt.Println(g)\n\tfmt.Println(g.area())\n\tfmt.Println(g.perim())\n}\n\nfunc main() {\n\ts := square{width: 3, heigth: 4}\n\tc := circle{radius: 5}\n\n\tmeasure(s)\n\tmeasure(c)\n}\n\nfunc (c circle) perim() float64 ", "output": "{\n\treturn 2 * math.Pi * c.radius\n}"} {"input": "package client_test\n\nimport (\n\t\"github.com/jdextraze/go-gesclient/client\"\n\t\"testing\"\n)\n\nfunc TestWrongExpectedVersion_Error(t *testing.T) {\n\tif client.WrongExpectedVersion.Error() != \"Wrong expected version\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestStreamDeleted_Error(t *testing.T) {\n\tif client.StreamDeleted.Error() != \"Stream deleted\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestInvalidTransaction_Error(t *testing.T) {\n\tif client.InvalidTransaction.Error() != \"Invalid transaction\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestAccessDenied_Error(t *testing.T) {\n\tif client.AccessDenied.Error() != \"Access denied\" {\n\t\tt.FailNow()\n\t}\n}\n\n\n\nfunc TestBadRequest_Error(t *testing.T) {\n\tif client.BadRequest.Error() != \"Bad request\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestServerError_Error(t *testing.T) {\n\terr := client.NewServerError(\"\")\n\tif err.Error() != \"Unexpected error on server: \" {\n\t\tt.FailNow()\n\t}\n\n\terr = client.NewServerError(\"test\")\n\tif err.Error() != \"Unexpected error on server: test\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestNotModified_Error(t *testing.T) {\n\terr := client.NewNotModified(\"test\")\n\tif err.Error() != \"Stream not modified: test\" {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestAuthenticationError_Error(t *testing.T) ", "output": "{\n\tif client.AuthenticationError.Error() != \"Authentication error\" {\n\t\tt.FailNow()\n\t}\n}"} {"input": "package react\n\n\ntype ImgProps struct {\n\tClassName string\n\tDangerouslySetInnerHTML *DangerousInnerHTML\n\tID string\n\tKey string\n\n\tOnChange\n\tOnClick\n\n\tRole string\n\tSrc string\n\tStyle *CSS\n}\n\n\n\nfunc (i *ImgProps) assign(v *_ImgProps) ", "output": "{\n\n\tv.ClassName = i.ClassName\n\n\tv.DangerouslySetInnerHTML = i.DangerouslySetInnerHTML\n\n\tif i.ID != \"\" {\n\t\tv.ID = i.ID\n\t}\n\n\tif i.Key != \"\" {\n\t\tv.Key = i.Key\n\t}\n\n\tif i.OnChange != nil {\n\t\tv.o.Set(\"onChange\", i.OnChange.OnChange)\n\t}\n\n\tif i.OnClick != nil {\n\t\tv.o.Set(\"onClick\", i.OnClick.OnClick)\n\t}\n\n\tv.Role = i.Role\n\n\tv.Src = i.Src\n\n\tv.Style = i.Style.hack()\n\n}"} {"input": "package web\n\nimport (\n\t\"strings\"\n\n\t\"github.com/gopherjs/gopherjs/js\"\n)\n\nfunc IsNodeJS() bool {\n\treturn js.Global.Get(\"require\") != js.Undefined\n}\n\nfunc IsBrowser() bool {\n\treturn !IsNodeJS()\n}\n\nfunc IsIOSSafari() bool {\n\tua := js.Global.Get(\"navigator\").Get(\"userAgent\").String()\n\tif !strings.Contains(ua, \"iPhone\") {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc IsAndroidChrome() bool {\n\tua := js.Global.Get(\"navigator\").Get(\"userAgent\").String()\n\tif !strings.Contains(ua, \"Android\") {\n\t\treturn false\n\t}\n\tif !strings.Contains(ua, \"Chrome\") {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\n\nfunc IsMobileBrowser() bool ", "output": "{\n\treturn IsIOSSafari() || IsAndroidChrome()\n}"} {"input": "package graph\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestLinksTo(t *testing.T) ", "output": "{\n\tts := new(TestTripleStore)\n\ttsFixed := newFixedIterator()\n\ttsFixed.AddValue(2)\n\tts.On(\"GetIdFor\", \"cool\").Return(1)\n\tts.On(\"GetTripleIterator\", Object, 1).Return(tsFixed)\n\tfixed := newFixedIterator()\n\tfixed.AddValue(ts.GetIdFor(\"cool\"))\n\tlto := NewLinksToIterator(ts, fixed, Object)\n\tval, ok := lto.Next()\n\tif !ok {\n\t\tt.Error(\"At least one triple matches the fixed object\")\n\t}\n\tif val != 2 {\n\t\tt.Errorf(\"Triple index 2, such as %s, should match %s\", ts.GetTriple(2), ts.GetTriple(val))\n\t}\n}"} {"input": "package hll\n\nimport \"testing\"\n\n\n\nfunc TestExtractShift(t *testing.T) {\n\ttestCases := []struct {\n\t\tinput uint64\n\t\tstartPos, endPos uint\n\t\texpectResult uint64\n\t}{\n\t\t{0, 0, 63, 0},\n\t\t{0xAABBCCDD00, 8, 47, 0xAABBCCDD},\n\t\t{0xFF00000000000000, 56, 63, 0xFF},\n\t\t{0xFF, 0, 7, 0xFF},\n\t}\n\n\tfor i, testCase := range testCases {\n\t\tactualResult := extractShift(testCase.input, testCase.startPos, testCase.endPos)\n\t\tif testCase.expectResult != actualResult {\n\t\t\tt.Errorf(\"Case %d actual result was %v\", i, actualResult)\n\t\t}\n\t}\n}\n\nfunc TestConcat(t *testing.T) {\n\ttestCases := []struct {\n\t\tinputs []concatInput\n\t\texpectResult uint64\n\t}{\n\t\t{[]concatInput{{0xABCD, 0, 15}, {0x1234, 0, 15}}, 0xABCD1234},\n\t\t{[]concatInput{{0x0000ABCD0000, 16, 31}, {0x1234000000000000, 48, 63}}, 0xABCD1234},\n\t\t{[]concatInput{{0x1234, 0, 15}, {0x12, 0, 7}}, 0x123412},\n\t}\n\n\tfor i, testCase := range testCases {\n\t\tactualResult := concat(testCase.inputs)\n\t\tif testCase.expectResult != actualResult {\n\t\t\tt.Errorf(\"Case %d actual result was %x\", i, actualResult)\n\t\t}\n\t}\n}\n\nfunc TestOnesTo(t *testing.T) ", "output": "{\n\ttestCases := []struct {\n\t\tstartPos, endPos uint\n\t\texpectResult uint64\n\t}{\n\t\t{0, 0, 1},\n\t\t{63, 63, 1 << 63},\n\t\t{2, 4, 4 + 8 + 16},\n\t\t{56, 63, 0xFF00000000000000},\n\t}\n\n\tfor i, testCase := range testCases {\n\t\tactualResult := onesFromTo(testCase.startPos, testCase.endPos)\n\t\tif testCase.expectResult != actualResult {\n\t\t\tt.Errorf(\"Case %d actual result was %v\", i, actualResult)\n\t\t}\n\t}\n}"} {"input": "package chipmunk\n\nimport \"github.com/dataarts/chipmunk/vect\"\n\nconst (\n\terrorBias = 0.00179701029991443 \n)\n\ntype ConstraintCallback interface {\n\tCollisionPreSolve(constraint Constraint)\n\tCollisionPostSolve(constraint Constraint)\n}\n\ntype Constraint interface {\n\tConstraint() *BasicConstraint\n\tPreSolve()\n\tPostSolve()\n\tPreStep(dt vect.Float)\n\tApplyCachedImpulse(dt_coef vect.Float)\n\tApplyImpulse()\n\tImpulse() vect.Float\n}\n\ntype BasicConstraint struct {\n\tBodyA, BodyB *Body\n\tspace *Space\n\tMaxForce vect.Float\n\tErrorBias vect.Float\n\tMaxBias vect.Float\n\tCallbackHandler ConstraintCallback\n\tUserData Data\n}\n\nfunc NewConstraint(a, b *Body) BasicConstraint {\n\treturn BasicConstraint{BodyA: a, BodyB: b, MaxForce: Inf, MaxBias: Inf, ErrorBias: errorBias}\n}\n\nfunc (this *BasicConstraint) Constraint() *BasicConstraint {\n\treturn this\n}\n\nfunc (this *BasicConstraint) PreStep(dt vect.Float) {\n\tpanic(\"empty constraint\")\n}\n\n\n\nfunc (this *BasicConstraint) ApplyImpulse() {\n\tpanic(\"empty constraint\")\n}\n\nfunc (this *BasicConstraint) Impulse() vect.Float {\n\tpanic(\"empty constraint\")\n}\n\nfunc (this *BasicConstraint) PreSolve() {\n\tif this.CallbackHandler != nil {\n\t\tthis.CallbackHandler.CollisionPreSolve(this)\n\t}\n}\n\nfunc (this *BasicConstraint) PostSolve() {\n\tif this.CallbackHandler != nil {\n\t\tthis.CallbackHandler.CollisionPostSolve(this)\n\t}\n}\n\nfunc (this *BasicConstraint) ApplyCachedImpulse(dt_coef vect.Float) ", "output": "{\n\tpanic(\"empty constraint\")\n}"} {"input": "package thriftclient\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"git.apache.org/thrift.git/lib/go/thrift\"\n)\n\ntype transportFactory struct {\n\tserviceIP string\n\tservicePort int\n\ttimeOut int64\n}\n\nfunc NewTransportFactory(serviceIP string, servicePort int, timeOut int64) *transportFactory {\n\treturn &transportFactory{serviceIP: serviceIP, servicePort: servicePort, timeOut: timeOut}\n}\n\n\nfunc (tf *transportFactory) CreateObj() (interface{}, error) {\n\ttransportFactory := thrift.NewTTransportFactory()\n\tvar err error\n\tvar transport thrift.TTransport\n\taddr := fmt.Sprintf(\"%s:%d\", tf.serviceIP, tf.servicePort)\n\ttransport, err = thrift.NewTSocketTimeout(addr, time.Duration(tf.timeOut)*time.Millisecond)\n\tif err != nil {\n\t\tfmt.Println(\"Error opening socket:\", err)\n\t\treturn nil, err\n\t}\n\ttransport = transportFactory.GetTransport(transport)\n\tif err := transport.Open(); err != nil {\n\t\tfmt.Println(\"Error transport opening:\", err)\n\t\treturn nil, err\n\t}\n\treturn transport, nil\n}\n\n\n\n\n\nfunc (tf *transportFactory) ValidateObj(t interface{}) error {\n\tvalue, ok := t.(thrift.TTransport)\n\tif ok {\n\t\tif value.IsOpen() {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn errors.New(\"transport is not validate\")\n}\n\nfunc (tf *transportFactory) DestroyObj(t interface{}) error ", "output": "{\n\tvalue, ok := t.(thrift.TTransport)\n\tif ok {\n\t\tif value.IsOpen() {\n\t\t\tvalue.Close()\n\t\t}\n\t}\n\treturn nil\n\n}"} {"input": "package sync\n\nimport (\n \"ghighlighter/models\"\n \"ghighlighter/readmill/readmillreadings\"\n \"ghighlighter/readmill/readmillhighlights\"\n)\n\nfunc Sync() {\n config := models.Config()\n\n syncHighlights(config.AccessToken)\n syncReadings(config.UserId, config.AccessToken)\n}\n\nfunc syncHighlights(accessToken string) {\n highlights := models.Highlights()\n\n tmpItems := make([]models.GhHighlight, len(highlights.Items))\n copy(tmpItems, highlights.Items)\n\n for _, highlight := range tmpItems {\n var highlightComment *readmillhighlights.HighlightComment\n if highlight.Comment != \"\" {\n highlightComment = &readmillhighlights.HighlightComment{highlight.Comment}\n }\n\n readmillHighlight := readmillhighlights.Highlight{highlight.Content,\n highlight.Position, highlight.Timestamp, readmillhighlights.HighlightLocators{}}\n\n success := readmillhighlights.PostHighlight(readmillHighlight, highlightComment, highlight.ReadingReadmillId, accessToken)\n\n if success {\n highlights.Delete(highlight)\n }\n }\n}\n\n\n\nfunc syncReadings(userId int, accessToken string) ", "output": "{\n readings := models.Readings()\n readmillReadings := readmillreadings.GetReadings(userId, accessToken)\n\n for _, readmillReading := range readmillReadings {\n title := readmillReading.Book.Title + \" - \" + readmillReading.Book.Author\n reading := models.GhReading{title, readmillReading.Id, 1}\n readings.Add(reading)\n }\n}"} {"input": "package gorfxtrx\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n)\n\n\ntype Wind struct {\n\tdata []byte\n\ttypeId byte\n\tSequenceNumber byte\n\tid uint16\n\tDirection uint16\n\tAverageSpeed float64\n\tGust float64\n\tBattery byte\n\tRssi byte\n}\n\nvar windTypes = map[byte]string{\n\t0x01: \"WTGR800\",\n\t0x02: \"WGR800\",\n\t0x03: \"STR918, WGR918\",\n\t0x04: \"TFA\",\n}\n\n\n\n\nfunc (self *Wind) Id() string {\n\treturn fmt.Sprintf(\"%02x:%02x\", self.id>>8, self.id&0xff)\n}\n\n\nfunc (self *Wind) Type() string {\n\treturn windTypes[self.typeId]\n}\n\nfunc (self *Wind) Receive(data []byte) ", "output": "{\n\tself.data = data\n\tself.typeId = data[2]\n\tself.SequenceNumber = data[3]\n\tself.id = binary.BigEndian.Uint16(data[4:6])\n\tself.Direction = binary.BigEndian.Uint16(data[6:8])\n\tself.AverageSpeed = float64(binary.BigEndian.Uint16(data[8:10])) / 10\n\tself.Gust = float64(binary.BigEndian.Uint16(data[10:12])) / 10\n\tif self.typeId == 0x03 {\n\t\tself.Battery = (data[16] + 1) * 10\n\t} else {\n\t\tself.Battery = (data[16] & 0x0f) * 10\n\t\tself.Rssi = data[16] >> 4\n\t}\n}"} {"input": "package spec\n\nimport (\n\t\"encoding/json\"\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\nvar paths = Paths{\n\tVendorExtensible: VendorExtensible{Extensions: map[string]interface{}{\"x-framework\": \"go-swagger\"}},\n\tPaths: map[string]PathItem{\n\t\t\"/\": PathItem{\n\t\t\tRefable: Refable{Ref: MustCreateRef(\"cats\")},\n\t\t},\n\t},\n}\n\nvar pathsJSON = `{\"x-framework\":\"go-swagger\",\"/\":{\"$ref\":\"cats\"}}`\n\n\n\nfunc TestIntegrationPaths(t *testing.T) ", "output": "{\n\tConvey(\"all fields of paths should\", t, func() {\n\n\t\tConvey(\"serialize\", func() {\n\t\t\texpected := map[string]interface{}{}\n\t\t\tjson.Unmarshal([]byte(pathsJSON), &expected)\n\t\t\tb, err := json.Marshal(paths)\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tvar actual map[string]interface{}\n\t\t\terr = json.Unmarshal(b, &actual)\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(actual, ShouldResemble, expected)\n\t\t})\n\n\t\tConvey(\"deserialize\", func() {\n\n\t\t\tactual := Paths{}\n\t\t\terr := json.Unmarshal([]byte(pathsJSON), &actual)\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(actual, ShouldResemble, paths)\n\t\t})\n\n\t})\n}"} {"input": "package api\n\ntype Memstore map[string]*Collection\n\nfunc (m Memstore) Init(dbName string) error {\n\treturn nil\n}\n\nfunc (m Memstore) CreateCollection(slug, name string) (Collection, error) {\n\tm[slug] = &Collection{Name: name,\n\t\tSlug: slug,\n\t\tItems: map[string]Item{},\n\t}\n\treturn *m[slug], nil\n}\n\nfunc (m Memstore) UpdateCollection(slug, name string) error {\n\tif c, ok := m[slug]; !ok {\n\t\treturn CollectionNotFoundError\n\t} else {\n\t\tc.Name = name\n\t}\n\treturn nil\n}\n\nfunc (m Memstore) GetCollectionData(slug string) (Collection, error) {\n\tif c, ok := m[slug]; ok {\n\t\t(*c).Items = nil\n\t\treturn *c, nil\n\t}\n\treturn Collection{}, CollectionNotFoundError\n}\n\nfunc (m Memstore) GetCollectionItems(slug string) (map[string]Item, error) {\n\tif c, ok := m[slug]; ok {\n\t\treturn c.Items, nil\n\t}\n\treturn map[string]Item{}, CollectionNotFoundError\n}\n\n\n\nfunc (m Memstore) GetItemFromCollection(slug, tag string) (Item, error) {\n\tif _, ok := m[slug]; !ok {\n\t\treturn Item{}, CollectionNotFoundError\n\t}\n\tif _, ok := m[slug].Items[tag]; !ok {\n\t\treturn Item{}, BlobNotFoundError\n\t}\n\treturn m[slug].Items[tag], nil\n}\n\nfunc (m Memstore) AddItemToCollection(slug string, item Item) error ", "output": "{\n\tif c, ok := m[slug]; ok {\n\t\tc.Items[item.Tag] = item\n\t\treturn nil\n\t}\n\treturn CollectionNotFoundError\n}"} {"input": "package block\n\nimport (\n\t\"github.com/juju/cmd/v3\"\n\t\"github.com/juju/juju/jujuclient\"\n\n\t\"github.com/juju/juju/apiserver/params\"\n\t\"github.com/juju/juju/cmd/modelcmd\"\n)\n\n\n\nfunc NewDisableCommandForTest(store jujuclient.ClientStore, api blockClientAPI, err error) cmd.Command {\n\tcmd := &disableCommand{\n\t\tapiFunc: func(_ newAPIRoot) (blockClientAPI, error) {\n\t\t\treturn api, err\n\t\t},\n\t}\n\tcmd.SetClientStore(store)\n\treturn modelcmd.Wrap(cmd)\n}\n\n\n\n\n\ntype listMockAPI interface {\n\tblockListAPI\n\tListBlockedModels() ([]params.ModelBlockInfo, error)\n}\n\n\n\nfunc NewListCommandForTest(store jujuclient.ClientStore, api listMockAPI, err error) cmd.Command {\n\tcmd := &listCommand{\n\t\tapiFunc: func(_ newAPIRoot) (blockListAPI, error) {\n\t\t\treturn api, err\n\t\t},\n\t\tcontrollerAPIFunc: func(_ newControllerAPIRoot) (controllerListAPI, error) {\n\t\t\treturn api, err\n\t\t},\n\t}\n\tcmd.SetClientStore(store)\n\treturn modelcmd.Wrap(cmd)\n}\n\nfunc NewEnableCommandForTest(store jujuclient.ClientStore, api unblockClientAPI, err error) cmd.Command ", "output": "{\n\tcmd := &enableCommand{\n\t\tapiFunc: func(_ newAPIRoot) (unblockClientAPI, error) {\n\t\t\treturn api, err\n\t\t},\n\t}\n\tcmd.SetClientStore(store)\n\treturn modelcmd.Wrap(cmd)\n}"} {"input": "package netutil\n\nimport \"net\"\n\n\n\n\nfunc AddrIP(addr net.Addr) net.IP ", "output": "{\n\tswitch a := addr.(type) {\n\tcase *net.IPAddr:\n\t\treturn a.IP\n\tcase *net.TCPAddr:\n\t\treturn a.IP\n\tcase *net.UDPAddr:\n\t\treturn a.IP\n\tdefault:\n\t\treturn nil\n\t}\n}"} {"input": "package conekta\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nconst (\n\tkey = \"\"\n\tsecret = \"key_KjXFWbopqyujnagRLy4dtw\"\n)\n\n\n\nfunc TestCustomerCreate(t *testing.T) {\n\n\tc, err := NewClient(key, secret, false)\n\tc.debug = true\n\tassert.Nil(t, err)\n\tassert.NotNil(t, c)\n\n\tcr := &CustomerRequest{\n\t\tName: \"Mario Perez\",\n\t\tPhone: \"+5215555555555\",\n\t\tEmail: \"usuario@example.com\",\n\t\tPaymentSources: []PaymentSource{\n\t\t\tPaymentSource{\n\t\t\t\tTokenID: \"tok_test_visa_4242\",\n\t\t\t\tType: \"card\",\n\t\t\t},\n\t\t},\n\t\tCorporate: true,\n\t}\n\tcus, err := c.CreateCustomer(cr)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, cus)\n}\n\nfunc TestOrderCreate(t *testing.T) ", "output": "{\n\n\tc, err := NewClient(key, secret, false)\n\tc.debug = true\n\tassert.Nil(t, err)\n\tassert.NotNil(t, c)\n\n\tor := &OrderRequest{\n\t\tCurrency: MXN,\n\t\tCustomerInfo: &Customer{\n\t\t\tCustomerID: \"cus_2h3syNSMiZwfFM5XC\",\n\t\t},\n\t\tLineItems: []Product{\n\t\t\tProduct{\n\t\t\t\tName: \"Box of sls\",\n\t\t\t\tUnitPrice: 150 * 100,\n\t\t\t\tQuantity: 1,\n\t\t\t},\n\t\t},\n\t\tCharges: []Charge{\n\t\t\tCharge{\n\t\t\t\tPaymentMethod: PaymentMethod{\n\t\t\t\t\tType: \"default\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\torder, err := c.CreateOrder(or)\n\tassert.Nil(t, err)\n\tassert.NotNil(t, order)\n}"} {"input": "package unit\n\nimport (\n\t\"github.com/juju/cmd\"\n\t\"github.com/juju/names/v4\"\n\t\"github.com/juju/utils/v2/voyeur\"\n\n\t\"github.com/juju/juju/agent\"\n\t\"github.com/juju/juju/cmd/containeragent/utils\"\n\t\"github.com/juju/juju/cmd/jujud/agent/agentconf\"\n\t\"github.com/juju/juju/worker/logsender\"\n)\n\ntype (\n\tManifoldsConfig = manifoldsConfig\n\tContainerUnitAgent = containerUnitAgent\n)\n\ntype ContainerUnitAgentTest interface {\n\tcmd.Command\n\tDataDir() string\n\tSetAgentConf(cfg agentconf.AgentConf)\n\tChangeConfig(change agent.ConfigMutator) error\n\tCurrentConfig() agent.Config\n\tTag() names.UnitTag\n\tCharmModifiedVersion() int\n\tGetContainerNames() []string\n}\n\nfunc NewForTest(\n\tctx *cmd.Context,\n\tbufferedLogger *logsender.BufferedLogWriter,\n\tconfigChangedVal *voyeur.Value,\n\tfileReaderWriter utils.FileReaderWriter,\n\tenvironment utils.Environment,\n) ContainerUnitAgentTest {\n\treturn &containerUnitAgent{\n\t\tctx: ctx,\n\t\tAgentConf: agentconf.NewAgentConf(\"\"),\n\t\tbufferedLogger: bufferedLogger,\n\t\tconfigChangedVal: configChangedVal,\n\t\tfileReaderWriter: fileReaderWriter,\n\t\tenvironment: environment,\n\t}\n}\n\nfunc (c *containerUnitAgent) SetAgentConf(cfg agentconf.AgentConf) {\n\tc.AgentConf = cfg\n}\n\n\n\nfunc (c *containerUnitAgent) DataDir() string {\n\treturn c.AgentConf.DataDir()\n}\n\nfunc (c *containerUnitAgent) GetContainerNames() []string ", "output": "{\n\treturn c.containerNames\n}"} {"input": "package structs\n\nimport \"fmt\"\n\n\ntype Bitmap []byte\n\n\nfunc NewBitmap(size uint) (Bitmap, error) {\n\tif size == 0 {\n\t\treturn nil, fmt.Errorf(\"bitmap must be positive size\")\n\t}\n\tif size&7 != 0 {\n\t\treturn nil, fmt.Errorf(\"bitmap must be byte aligned\")\n\t}\n\tb := make([]byte, size>>3)\n\treturn Bitmap(b), nil\n}\n\n\nfunc (b Bitmap) Copy() (Bitmap, error) {\n\tif b == nil {\n\t\treturn nil, fmt.Errorf(\"can't copy nil Bitmap\")\n\t}\n\n\traw := make([]byte, len(b))\n\tcopy(raw, b)\n\treturn Bitmap(raw), nil\n}\n\n\nfunc (b Bitmap) Size() uint {\n\treturn uint(len(b) << 3)\n}\n\n\nfunc (b Bitmap) Set(idx uint) {\n\tbucket := idx >> 3\n\tmask := byte(1 << (idx & 7))\n\tb[bucket] |= mask\n}\n\n\nfunc (b Bitmap) Check(idx uint) bool {\n\tbucket := idx >> 3\n\tmask := byte(1 << (idx & 7))\n\treturn (b[bucket] & mask) != 0\n}\n\n\n\n\n\n\nfunc (b Bitmap) IndexesInRange(set bool, from, to uint) []int {\n\tvar indexes []int\n\tfor i := from; i < to; i++ {\n\t\tc := b.Check(i)\n\t\tif c && set || !c && !set {\n\t\t\tindexes = append(indexes, int(i))\n\t\t}\n\t}\n\n\treturn indexes\n}\n\nfunc (b Bitmap) Clear() ", "output": "{\n\tfor i := range b {\n\t\tb[i] = 0\n\t}\n}"} {"input": "package distribution\n\nimport (\n\t\"testing\"\n\n\t\"github.com/ready-steady/assert\"\n)\n\n\n\nfunc TestParse(t *testing.T) ", "output": "{\n\tcases := []struct {\n\t\tline string\n\t\tsuccess bool\n\t}{\n\t\t{\"Beta(1, 1)\", true},\n\t\t{\"beta(0.5, 1.5)\", true},\n\t\t{\" Beta \\t (1, 1)\", true},\n\t\t{\"Gamma(1, 1)\", false},\n\t\t{\"Beta(1, 1, 1)\", false},\n\t\t{\"beta(-1, 1)\", false},\n\t\t{\"beta(0, 1)\", false},\n\t\t{\"beta(1, -1)\", false},\n\t\t{\"beta(1, 0)\", false},\n\t\t{\"beta(1, 0)\", false},\n\t\t{\"uniform()\", true},\n\t\t{\"uniform( )\", true},\n\t}\n\n\tfor _, c := range cases {\n\t\tif _, err := Parse(c.line); c.success {\n\t\t\tassert.Success(err, t)\n\t\t} else {\n\t\t\tassert.Failure(err, t)\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com/kataras/iris/v12/httptest\"\n)\n\n\n\nfunc TestDependencyInjectionBasic_Middleware(t *testing.T) ", "output": "{\n\tapp := newApp()\n\n\te := httptest.New(t, app)\n\te.POST(\"/42\").WithJSON(testInput{Email: \"my_email\"}).Expect().\n\t\tStatus(httptest.StatusOK).\n\t\tJSON().Equal(testOutput{ID: 42, Name: \"my_email\"})\n\n\te.POST(\"/42\").WithJSON(testInput{Email: \"invalid\"}).Expect().\n\t\tStatus(httptest.StatusAccepted).Body().Empty()\n\n\te.POST(\"/42\").WithJSON(testInput{Email: \"error\"}).Expect().\n\t\tStatus(httptest.StatusConflict).Body().Equal(\"my_error\")\n}"} {"input": "package customresourcedefinition\n\nimport (\n\tcontext \"context\"\n\n\tv1 \"k8s.io/api/core/v1\"\n\tv1beta1 \"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1\"\n\tcustomresourcedefinition \"knative.dev/pkg/client/injection/apiextensions/reconciler/apiextensions/v1beta1/customresourcedefinition\"\n\treconciler \"knative.dev/pkg/reconciler\"\n)\n\n\n\n\n\n\n\n\ntype Reconciler struct {\n}\n\n\nvar _ customresourcedefinition.Interface = (*Reconciler)(nil)\n\n\n\n\n\nfunc (r *Reconciler) ReconcileKind(ctx context.Context, o *v1beta1.CustomResourceDefinition) reconciler.Event {\n\n\n\treturn newReconciledNormal(o.Namespace, o.Name)\n}\n\nfunc newReconciledNormal(namespace, name string) reconciler.Event ", "output": "{\n\treturn reconciler.NewEvent(v1.EventTypeNormal, \"CustomResourceDefinitionReconciled\", \"CustomResourceDefinition reconciled: \\\"%s/%s\\\"\", namespace, name)\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/mexisme/go-config/settings\"\n)\n\n\nfunc AddConfigItems(configKeys []string) {\n\tsettings.AddConfigItems(configKeys)\n}\n\n\nfunc AddConfigItemsWithPFlags(configKeys []string) error {\n\treturn settings.AddConfigItemsWithPFlags(configKeys)\n}\n\n\nfunc ApplyWith(key string, f func(interface{})) {\n\tsettings.ApplyWith(key, f)\n}\n\n\nfunc Get(key string) interface{} {\n\treturn settings.Get(key)\n}\n\n\nfunc GetBool(key string) bool {\n\treturn settings.GetBool(key)\n}\n\n\nfunc GetFloat64(key string) float64 {\n\treturn settings.GetFloat64(key)\n}\n\n\nfunc GetInt(key string) int {\n\treturn settings.GetInt(key)\n}\n\n\nfunc GetString(key string) string {\n\treturn settings.GetString(key)\n}\n\n\nfunc GetStringMap(key string) map[string]interface{} {\n\treturn settings.GetStringMap(key)\n}\n\n\nfunc GetStringMapString(key string) map[string]string {\n\treturn settings.GetStringMapString(key)\n}\n\n\nfunc GetStringSlice(key string) []string {\n\treturn settings.GetStringSlice(key)\n}\n\n\nfunc GetTime(key string) time.Time {\n\treturn settings.GetTime(key)\n}\n\n\nfunc GetDuration(key string) time.Duration {\n\treturn settings.GetDuration(key)\n}\n\n\nfunc IsSet(key string) bool {\n\treturn settings.IsSet(key)\n}\n\n\n\n\nfunc AllSettings() map[string]interface{} ", "output": "{\n\treturn settings.AllSettings()\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/russmack/statemachiner\"\n)\n\n\nfunc main() {\n\ts := statemachiner.NewStateMachine()\n\ts.StartState = dispenseDogBiscuits\n\tc := NewHome()\n\ts.Start(c)\n}\n\n\ntype Home struct {\n\tDispenseDogBiscuits int `json:\"dispense_dog_biscuits\"`\n\tTotalDogBiscuits int `json:\"dog_biscuits\"`\n\tLights bool `json:\"lights\"`\n\tKettle bool `json:\"kettle\"`\n\tVacuumRoom string `json:\"vacuum_room\"`\n}\n\n\nfunc NewHome() *Home {\n\treturn &Home{}\n}\n\n\n\nfunc dispenseDogBiscuits(cargo interface{}) statemachiner.StateFn {\n\tcargo.(*Home).DispenseDogBiscuits = 10\n\tcargo.(*Home).TotalDogBiscuits += cargo.(*Home).DispenseDogBiscuits\n\tfmt.Printf(\"%+v\\n\", cargo)\n\treturn lights\n}\n\n\nfunc lights(cargo interface{}) statemachiner.StateFn {\n\tcargo.(*Home).Lights = true\n\tfmt.Printf(\"%+v\\n\", cargo)\n\treturn kettle\n}\n\n\nfunc kettle(cargo interface{}) statemachiner.StateFn {\n\tcargo.(*Home).Kettle = true\n\tfmt.Printf(\"%+v\\n\", cargo)\n\treturn vacuumRoom\n}\n\n\n\n\nfunc vacuumRoom(cargo interface{}) statemachiner.StateFn ", "output": "{\n\tif cargo.(*Home).TotalDogBiscuits < 20 {\n\t\treturn dispenseDogBiscuits\n\t} else {\n\t\tcargo.(*Home).VacuumRoom = \"kitchen\"\n\t}\n\tfmt.Printf(\"%+v\\n\", cargo)\n\treturn nil\n}"} {"input": "package execution\n\nimport (\n\t\"github.com/hyperledger/burrow/acm\"\n\t\"github.com/hyperledger/burrow/acm/acmstate\"\n\t\"github.com/hyperledger/burrow/bcm\"\n\t\"github.com/hyperledger/burrow/crypto\"\n\t\"github.com/hyperledger/burrow/execution/contexts\"\n\t\"github.com/hyperledger/burrow/execution/engine\"\n\t\"github.com/hyperledger/burrow/execution/exec\"\n\t\"github.com/hyperledger/burrow/execution/vms\"\n\t\"github.com/hyperledger/burrow/logging\"\n\t\"github.com/hyperledger/burrow/txs\"\n\t\"github.com/hyperledger/burrow/txs/payload\"\n)\n\n\n\n\n\n\n\nfunc CallCodeSim(reader acmstate.Reader, blockchain bcm.BlockchainInfo, fromAddress, address crypto.Address, code, data []byte,\n\tlogger *logging.Logger) (*exec.TxExecution, error) {\n\n\tcache := acmstate.NewCache(reader)\n\terr := cache.UpdateAccount(&acm.Account{\n\t\tAddress: address,\n\t\tEVMCode: code,\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn CallSim(cache, blockchain, fromAddress, address, data, logger)\n}\n\nfunc CallSim(reader acmstate.Reader, blockchain bcm.BlockchainInfo, fromAddress, address crypto.Address, data []byte,\n\tlogger *logging.Logger) (*exec.TxExecution, error) ", "output": "{\n\tcache := acmstate.NewCache(reader)\n\texe := contexts.CallContext{\n\t\tVMS: vms.NewConnectedVirtualMachines(engine.Options{}),\n\t\tRunCall: true,\n\t\tState: cache,\n\t\tMetadataState: acmstate.NewMemoryState(),\n\t\tBlockchain: blockchain,\n\t\tLogger: logger,\n\t}\n\n\ttxe := exec.NewTxExecution(txs.Enclose(blockchain.ChainID(),\n\t\t&payload.CallTx{\n\t\t\tInput: &payload.TxInput{\n\t\t\t\tAddress: fromAddress,\n\t\t\t},\n\t\t\tAddress: &address,\n\t\t\tData: data,\n\t\t\tGasLimit: contexts.GasLimit,\n\t\t}))\n\n\ttxe.Height = blockchain.LastBlockHeight()\n\terr := exe.Execute(txe, txe.Envelope.Tx.Payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn txe, nil\n}"} {"input": "package lfs\n\nimport (\n\t\"testing\"\n\n\t\"github.com/git-lfs/git-lfs/config\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestFetchPruneConfigCustom(t *testing.T) {\n\tcfg := config.NewFrom(config.Values{\n\t\tGit: map[string][]string{\n\t\t\t\"lfs.fetchrecentrefsdays\": []string{\"12\"},\n\t\t\t\"lfs.fetchrecentremoterefs\": []string{\"false\"},\n\t\t\t\"lfs.fetchrecentcommitsdays\": []string{\"9\"},\n\t\t\t\"lfs.pruneoffsetdays\": []string{\"30\"},\n\t\t\t\"lfs.pruneverifyremotealways\": []string{\"true\"},\n\t\t\t\"lfs.pruneremotetocheck\": []string{\"upstream\"},\n\t\t},\n\t})\n\tfp := NewFetchPruneConfig(cfg.Git)\n\n\tassert.Equal(t, 12, fp.FetchRecentRefsDays)\n\tassert.Equal(t, 9, fp.FetchRecentCommitsDays)\n\tassert.False(t, fp.FetchRecentRefsIncludeRemotes)\n\tassert.Equal(t, 30, fp.PruneOffsetDays)\n\tassert.Equal(t, \"upstream\", fp.PruneRemoteName)\n\tassert.True(t, fp.PruneVerifyRemoteAlways)\n}\n\nfunc TestFetchPruneConfigDefault(t *testing.T) ", "output": "{\n\tcfg := config.NewFrom(config.Values{})\n\tfp := NewFetchPruneConfig(cfg.Git)\n\n\tassert.Equal(t, 7, fp.FetchRecentRefsDays)\n\tassert.Equal(t, 0, fp.FetchRecentCommitsDays)\n\tassert.Equal(t, 3, fp.PruneOffsetDays)\n\tassert.True(t, fp.FetchRecentRefsIncludeRemotes)\n\tassert.Equal(t, 3, fp.PruneOffsetDays)\n\tassert.Equal(t, \"origin\", fp.PruneRemoteName)\n\tassert.False(t, fp.PruneVerifyRemoteAlways)\n}"} {"input": "package eventgrid\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc UserAgent() string {\n\treturn \"Azure-SDK-For-Go/v10.3.1-beta arm-eventgrid/2017-06-15-preview\"\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn \"v10.3.1-beta\"\n}"} {"input": "package context\n\nimport (\n\t\"github.com/gorilla/context\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype RequestParam struct {\n\tRequest *http.Request\n}\n\nfunc Params(req *http.Request) *RequestParam {\n\tif rp, ok := context.Get(req, params).(*RequestParam); ok {\n\t\treturn rp\n\t}\n\n\treturn nil\n}\n\nfunc InitParams(req *http.Request) error {\n\terr := req.ParseForm()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trp := RequestParam{req}\n\n\tcontext.Set(req, params, &rp)\n\n\treturn nil\n}\n\n\n\nfunc (rp *RequestParam) GetInt(param string) (int, error) {\n\treturn strconv.Atoi(rp.Get(param))\n}\n\nfunc (rp *RequestParam) Get(param string) string ", "output": "{\n\tif strings.HasPrefix(param, \":\") {\n\t\treturn rp.Request.URL.Query().Get(param)\n\t}\n\n\treturn rp.Request.Form.Get(param)\n}"} {"input": "package models\n\nimport \"encoding/binary\"\n\n\n\ntype Page struct {\n\tPrev bool\n\tPrevVal int\n\n\tNext bool\n\tNextVal int\n\n\tNextURL string\n\n\tpages int\n\tPages []string\n\tTotal int\n\tCount int\n\tSkip int\n}\n\n\n\n\n\n\nfunc SearchPagination(count int, page int, perPage int) Page {\n\tvar pg Page\n\tvar total int\n\n\tif count%perPage != 0 {\n\t\ttotal = count/perPage + 1\n\t} else {\n\t\ttotal = count / perPage\n\t}\n\n\tif total < page {\n\t\tpage = total\n\t}\n\n\tif page == 1 {\n\t\tpg.Prev = false\n\t\tpg.Next = true\n\t}\n\n\tif page != 1 {\n\t\tpg.Prev = true\n\t}\n\n\tif total > page {\n\t\tpg.Next = true\n\t}\n\n\tif total == page {\n\t\tpg.Next = false\n\t}\n\n\tvar pgs = make([]string, total)\n\n\tskip := perPage * (page - 1)\n\n\tpg.Total = total\n\tpg.Skip = skip\n\tpg.Count = count\n\tpg.NextVal = page + 1\n\tpg.PrevVal = page - 1\n\tpg.Pages = pgs\n\n\treturn pg\n}\n\nfunc itob(v int) []byte ", "output": "{\n\tb := make([]byte, 8)\n\tbinary.BigEndian.PutUint64(b, uint64(v))\n\treturn b\n}"} {"input": "package controllers\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\n\t\"github.com/astaxie/beego\"\n\t\"github.com/gorilla/websocket\"\n\t\"github.com/beego/samples/WebIM/models\"\n)\n\n\ntype WebSocketController struct {\n\tbaseController\n}\n\n\nfunc (this *WebSocketController) Get() {\n\tuname := this.GetString(\"uname\")\n\tif len(uname) == 0 {\n\t\tthis.Redirect(\"/\", 302)\n\t\treturn\n\t}\n\n\tthis.TplName = \"websocket.html\"\n\tthis.Data[\"IsWebSocket\"] = true\n\tthis.Data[\"UserName\"] = uname\n}\n\n\n\n\n\nfunc broadcastWebSocket(event models.Event) {\n\tdata, err := json.Marshal(event)\n\tif err != nil {\n\t\tbeego.Error(\"Fail to marshal event:\", err)\n\t\treturn\n\t}\n\n\tfor sub := subscribers.Front(); sub != nil; sub = sub.Next() {\n\t\tws := sub.Value.(Subscriber).Conn\n\t\tif ws != nil {\n\t\t\tif ws.WriteMessage(websocket.TextMessage, data) != nil {\n\t\t\t\tunsubscribe <- sub.Value.(Subscriber).Name\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (this *WebSocketController) Join() ", "output": "{\n\tuname := this.GetString(\"uname\")\n\tif len(uname) == 0 {\n\t\tthis.Redirect(\"/\", 302)\n\t\treturn\n\t}\n\n\tws, err := websocket.Upgrade(this.Ctx.ResponseWriter, this.Ctx.Request, nil, 1024, 1024)\n\tif _, ok := err.(websocket.HandshakeError); ok {\n\t\thttp.Error(this.Ctx.ResponseWriter, \"Not a websocket handshake\", 400)\n\t\treturn\n\t} else if err != nil {\n\t\tbeego.Error(\"Cannot setup WebSocket connection:\", err)\n\t\treturn\n\t}\n\n\tJoin(uname, ws)\n\tdefer Leave(uname)\n\n\tfor {\n\t\t_, p, err := ws.ReadMessage()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tpublish <- newEvent(models.EVENT_MESSAGE, uname, string(p))\n\t}\n}"} {"input": "package global\n\nimport (\n\t\"context\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/otel/propagation\"\n)\n\n\n\n\ntype textMapPropagator struct {\n\tmtx sync.Mutex\n\tonce sync.Once\n\tdelegate propagation.TextMapPropagator\n\tnoop propagation.TextMapPropagator\n}\n\n\n\nvar _ propagation.TextMapPropagator = (*textMapPropagator)(nil)\n\nfunc newTextMapPropagator() *textMapPropagator {\n\treturn &textMapPropagator{\n\t\tnoop: propagation.NewCompositeTextMapPropagator(),\n\t}\n}\n\n\n\n\nfunc (p *textMapPropagator) SetDelegate(delegate propagation.TextMapPropagator) {\n\tif delegate == nil {\n\t\treturn\n\t}\n\n\tp.mtx.Lock()\n\tp.once.Do(func() { p.delegate = delegate })\n\tp.mtx.Unlock()\n}\n\n\n\n\nfunc (p *textMapPropagator) effectiveDelegate() propagation.TextMapPropagator {\n\tp.mtx.Lock()\n\tdefer p.mtx.Unlock()\n\tif p.delegate != nil {\n\t\treturn p.delegate\n\t}\n\treturn p.noop\n}\n\n\nfunc (p *textMapPropagator) Inject(ctx context.Context, carrier propagation.TextMapCarrier) {\n\tp.effectiveDelegate().Inject(ctx, carrier)\n}\n\n\nfunc (p *textMapPropagator) Extract(ctx context.Context, carrier propagation.TextMapCarrier) context.Context {\n\treturn p.effectiveDelegate().Extract(ctx, carrier)\n}\n\n\n\n\nfunc (p *textMapPropagator) Fields() []string ", "output": "{\n\treturn p.effectiveDelegate().Fields()\n}"} {"input": "package services\n\nimport (\n \"encoding/json\"\n \"strconv\"\n)\n\ntype FBPayloadApp struct {\n Name string\n Bundle_identifier string\n Platform string\n}\n\ntype FBPayload struct {\n Display_id int\n Title string\n Method string\n Crashes_count int\n Impacted_devices_count int\n Impact_level int\n Url string\n App FBPayloadApp\n}\n\ntype FBMessage struct {\n Event string\n Payload_type string\n Payload FBPayload\n}\n\n\n\nfunc getFabricData(decoder *json.Decoder) (string, string) ", "output": "{\n var fbEvent FBMessage\n decoder.Decode(&fbEvent)\n event := \"`Crashlytics: \" + fbEvent.Payload_type + \", \" +\n fbEvent.Payload.Title + \" for \" + fbEvent.Payload.App.Bundle_identifier + \"`\"\n payload := fbEvent.Payload\n desc := fbEvent.Event +\n \"\\nCrashes Count: \" + strconv.Itoa(payload.Crashes_count) +\n \"\\nPlatform: \" + payload.App.Platform +\n \"\\nName: \" + payload.App.Name +\n \"\\nMethod: \" + payload.Method +\n \"\\nURL: \" + payload.Url +\n \"\\nMethod: \" + payload.Method +\n \"\\nImpacted Devices Count: \" + strconv.Itoa(payload.Impacted_devices_count) +\n \"\\nImpacted Level: \" + strconv.Itoa(payload.Impact_level)\n return event, desc\n}"} {"input": "package libvirt_kvm\n\nimport (\n\tenvdriver \"github.com/dorzheh/deployer/drivers/env_driver/libvirt/libvirt_kvm\"\n\t\"github.com/dorzheh/deployer/utils\"\n\t\"github.com/dorzheh/deployer/utils/sysinfo\"\n\tssh \"github.com/dorzheh/infra/comm/common\"\n)\n\nconst (\n\tmultiQueueLibvirtVersion = \"1.0.6\"\n\tmultiQueueKernelVersion = \"3.8\"\n)\n\nfunc MultiQueueSupported(sshconfig *ssh.Config) (bool, error) {\n\tc := sysinfo.NewCollector(sshconfig)\n\tif c.KernelMajorMinorEqualOrGreaterThan(multiQueueKernelVersion) {\n\t\td := envdriver.NewDriver(sshconfig)\n\t\tcurVersion, err := d.Version()\n\t\tif err != nil {\n\t\t\treturn false, utils.FormatError(err)\n\t\t}\n\t\tif curVersion >= multiQueueLibvirtVersion {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}\n\n\n\n\nfunc MultiQueueSupportedMock(kernelVersion, libvirtVersion string, sshconfig *ssh.Config) (bool, error) ", "output": "{\n\tc := sysinfo.NewCollector(sshconfig)\n\tif c.KernelMajorMinorEqualOrGreaterThan(kernelVersion) {\n\t\td := envdriver.NewDriver(sshconfig)\n\t\tcurVersion, err := d.Version()\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif curVersion >= libvirtVersion {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/shezadkhan137/go-qrcode/qrcode\"\n)\n\nvar image *string\n\n\n\n\nfunc main() {\n\n\tflag.Parse()\n\n\tresults, err := qrcode.GetDataFromPNG(*image)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfor _, result := range results {\n\t\tfmt.Printf(\"Symbol Type: %s, Data %s\", result.SymbolType, result.Data)\n\t}\n}\n\nfunc init() ", "output": "{\n\timage = flag.String(\"i\", \"\", \"image path\")\n}"} {"input": "package main\n\nimport (\n\t\"github.com/jjyr/ringo\"\n\t\"github.com/jjyr/ringo/middleware\"\n)\n\n\n\ntype user struct {\n\tName string `json:\"name\" validate:\"required\"`\n}\n\nvar users []user\n\n\ntype Users struct {\n\tringo.Controller\n}\n\nfunc (_ *Users) Get(c ringo.Context) {\n\tc.JSON(200, ringo.H{\"users\": users})\n}\n\nfunc (ctl *Users) Post(c ringo.Context) {\n\tu := user{}\n\tif err := c.BindJSON(&u); err == nil {\n\t\tusers = append(users, u)\n\t\tc.JSON(200, u)\n\t} else {\n\t\tc.JSON(400, ringo.H{\"message\": \"format error\"})\n\t}\n}\n\nfunc DisplayList(c ringo.Context) {\n\tc.HTML(200, \"list.html\", users)\n}\n\ntype User struct {\n\tringo.Controller\n}\n\n\n\nfunc main() {\n\tapp := ringo.NewApp()\n\n\tapp.Add(\"/users\", &Users{})\n\tapp.GET(\"/users-list\", DisplayList)\n\tapp.Add(\"/user/:id\", &User{})\n\tapp.Use(middleware.Recover())\n\tapp.SetTemplatePath(\"templates\")\n\tapp.Run(\"localhost:8000\")\n}\n\nfunc (ctl *User) Delete(c ringo.Context) ", "output": "{\n\tidx := -1\n\tname := c.Params().ByName(\"id\")\n\tfor i, u := range users {\n\t\tif name == u.Name {\n\t\t\tidx = i\n\t\t\tbreak\n\t\t}\n\t}\n\tif idx >= 0 {\n\t\tusers = append(users[:idx], users[idx+1:]...)\n\t\tc.JSON(200, ringo.H{\"message\": \"ok\"})\n\t} else {\n\t\tc.JSON(404, ringo.H{\"message\": \"not found\"})\n\t}\n}"} {"input": "package permissions\n\nimport (\n\t\"path/filepath\"\n\t\"util\"\n)\n\n\nvar globalPermissions *PermissionsLoader\n\n\nfunc Get() *Permissions {\n\tif globalPermissions == nil {\n\t\treturn &Default\n\t}\n\treturn globalPermissions.Get()\n}\n\n\nfunc SetPath(permissions string) error {\n\tif permissions != \"default\" {\n\t\tpl, err := NewPermissionsLoader(permissions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif globalPermissions != nil {\n\t\t\tglobalPermissions.Close()\n\t\t}\n\t\tglobalPermissions = pl\n\t\tif !pl.Get().Watch {\n\t\t\tglobalPermissions.Close() \n\t\t}\n\n\t} else {\n\t\tif globalPermissions != nil {\n\t\t\tglobalPermissions.Close()\n\t\t}\n\t\tglobalPermissions = nil\n\t}\n\treturn nil\n}\n\n\ntype PermissionsLoader struct {\n\tPermissions *Permissions \n\tWatcher *util.FileWatcher \n}\n\n\nfunc (pl *PermissionsLoader) Get() *Permissions {\n\tif pl == nil {\n\t\treturn &Default\n\t}\n\n\tpl.Watcher.RLock()\n\tdefer pl.Watcher.RUnlock()\n\treturn pl.Permissions\n}\n\n\n\n\n\n\nfunc (pl *PermissionsLoader) Reload() error {\n\tp, err := Load(pl.Watcher.FileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpl.Watcher.Lock()\n\tpl.Permissions = p\n\tpl.Watcher.Unlock()\n\n\tif !p.Watch {\n\t\tpl.Close() \n\t}\n\n\treturn nil\n}\n\n\nfunc (pl *PermissionsLoader) Close() {\n\tpl.Watcher.Close()\n}\n\nfunc NewPermissionsLoader(filename string) (*PermissionsLoader, error) ", "output": "{\n\tfilename, err := filepath.Abs(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp, err := Load(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpl := &PermissionsLoader{\n\t\tPermissions: p,\n\t}\n\tpl.Watcher, err = util.NewFileWatcher(filename, pl)\n\treturn pl, err\n}"} {"input": "package main\n\nimport (\"os\";\"runtime\")\n\n\n\nfunc UserHomeDir() string ", "output": "{\n if runtime.GOOS == \"windows\" {\n home := os.Getenv(\"HOMEDRIVE\") + os.Getenv(\"HOMEPATH\")\n if home == \"\" {\n home = os.Getenv(\"USERPROFILE\")\n }\n return home\n }\n return os.Getenv(\"HOME\")\n}"} {"input": "package boottest\n\nimport (\n\t\"strings\"\n\n\t\"github.com/snapcore/snapd/asserts\"\n\t\"github.com/snapcore/snapd/snap\"\n)\n\ntype mockDevice struct {\n\tbootSnap string\n\tmode string\n\tuc20 bool\n\n\tmodel *asserts.Model\n}\n\n\n\n\n\n\n\nfunc MockDevice(s string) snap.Device {\n\tbootsnap, mode, uc20 := snapAndMode(s)\n\tif uc20 && bootsnap == \"\" {\n\t\tpanic(\"MockDevice with no snap name and @mode is unsupported\")\n\t}\n\treturn &mockDevice{\n\t\tbootSnap: bootsnap,\n\t\tmode: mode,\n\t\tuc20: uc20,\n\t}\n}\n\n\n\n\nfunc MockUC20Device(mode string, model *asserts.Model) snap.Device {\n\tif mode == \"\" {\n\t\tmode = \"run\"\n\t}\n\tif model == nil {\n\t\tmodel = MakeMockUC20Model()\n\t}\n\treturn &mockDevice{\n\t\tbootSnap: model.Kernel(),\n\t\tmode: mode,\n\t\tuc20: true,\n\t\tmodel: model,\n\t}\n}\n\n\n\nfunc (d *mockDevice) Kernel() string { return d.bootSnap }\nfunc (d *mockDevice) Classic() bool { return d.bootSnap == \"\" }\nfunc (d *mockDevice) RunMode() bool { return d.mode == \"run\" }\nfunc (d *mockDevice) HasModeenv() bool { return d.uc20 }\nfunc (d *mockDevice) Base() string {\n\tif d.model != nil {\n\t\treturn d.model.Base()\n\t}\n\treturn d.bootSnap\n}\nfunc (d *mockDevice) Model() *asserts.Model {\n\tif d.model == nil {\n\t\tpanic(\"Device.Model called but MockUC20Device not used\")\n\t}\n\treturn d.model\n}\n\nfunc snapAndMode(str string) (snap, mode string, uc20 bool) ", "output": "{\n\tparts := strings.SplitN(string(str), \"@\", 2)\n\tif len(parts) == 1 || parts[1] == \"\" {\n\t\treturn parts[0], \"run\", false\n\t}\n\treturn parts[0], parts[1], true\n}"} {"input": "package helpers\n\nfunc getWhitelistedDrivers(resourceData *ResourceData) []string {\n\ttempMap := make(map[string]string)\n\tfor _, driver := range resourceData.Blacklist {\n\t\ttempMap[driver] = \"\"\n\t}\n\twhitelist := []string{}\n\tfor _, driver := range resourceData.Drivers {\n\t\tif _, ok := tempMap[driver]; !ok {\n\t\t\twhitelist = append(whitelist, driver)\n\t\t}\n\t}\n\treturn whitelist\n}\n\n\n\nfunc isBlacklisted(resourceData *ResourceData, driver string) bool ", "output": "{\n\tfor _, disallowedDriver := range resourceData.Blacklist {\n\t\tif disallowedDriver == driver {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package graphql\n\n\n\n\nimport (\n\t\"net/http\"\n\n\tmiddleware \"github.com/go-openapi/runtime/middleware\"\n\n\tmodels \"github.com/semi-technologies/weaviate/entities/models\"\n)\n\n\ntype GraphqlBatchHandlerFunc func(GraphqlBatchParams, *models.Principal) middleware.Responder\n\n\nfunc (fn GraphqlBatchHandlerFunc) Handle(params GraphqlBatchParams, principal *models.Principal) middleware.Responder {\n\treturn fn(params, principal)\n}\n\n\ntype GraphqlBatchHandler interface {\n\tHandle(GraphqlBatchParams, *models.Principal) middleware.Responder\n}\n\n\n\n\n\ntype GraphqlBatch struct {\n\tContext *middleware.Context\n\tHandler GraphqlBatchHandler\n}\n\nfunc (o *GraphqlBatch) ServeHTTP(rw http.ResponseWriter, r *http.Request) {\n\troute, rCtx, _ := o.Context.RouteInfo(r)\n\tif rCtx != nil {\n\t\tr = rCtx\n\t}\n\tvar Params = NewGraphqlBatchParams()\n\n\tuprinc, aCtx, err := o.Context.Authorize(r, route)\n\tif err != nil {\n\t\to.Context.Respond(rw, r, route.Produces, route, err)\n\t\treturn\n\t}\n\tif aCtx != nil {\n\t\tr = aCtx\n\t}\n\tvar principal *models.Principal\n\tif uprinc != nil {\n\t\tprincipal = uprinc.(*models.Principal) \n\t}\n\n\tif err := o.Context.BindValidRequest(r, route, &Params); err != nil { \n\t\to.Context.Respond(rw, r, route.Produces, route, err)\n\t\treturn\n\t}\n\n\tres := o.Handler.Handle(Params, principal) \n\n\to.Context.Respond(rw, r, route.Produces, route, res)\n\n}\n\nfunc NewGraphqlBatch(ctx *middleware.Context, handler GraphqlBatchHandler) *GraphqlBatch ", "output": "{\n\treturn &GraphqlBatch{Context: ctx, Handler: handler}\n}"} {"input": "package sacloud\n\n\ntype Icon struct {\n\t*Resource \n\tpropAvailability \n\tpropName \n\tpropScope \n\tpropTags \n\tpropCreatedAt \n\tpropModifiedAt \n\n\tURL string `json:\",omitempty\"` \n\tImage string `json:\",omitempty\"` \n}\n\n\ntype Image string\n\n\nfunc (icon *Icon) GetURL() string {\n\treturn icon.URL\n}\n\n\nfunc (icon *Icon) GetImage() string {\n\treturn icon.Image\n}\n\n\n\n\nfunc (icon *Icon) SetImage(image string) ", "output": "{\n\ticon.Image = image\n}"} {"input": "package commons\n\nimport \"net/http\"\n\nfunc HttpNoContent(w http.ResponseWriter) {\n\tHttpError(w, http.StatusNoContent)\n}\n\nfunc HttpUnauthorized(w http.ResponseWriter) {\n\tHttpError(w, http.StatusUnauthorized)\n}\n\n\n\nfunc HttpError(w http.ResponseWriter, code int) {\n\thttp.Error(w, http.StatusText(code), code)\n}\n\nfunc HttpCheckError(err error, status int, w http.ResponseWriter) {\n\tif err != nil {\n\t\tHttpError(w, status)\n\t}\n}\n\nfunc HttpBadRequest(w http.ResponseWriter) ", "output": "{\n\tHttpError(w, http.StatusBadRequest)\n}"} {"input": "package customer\n\nimport (\n\t\"github.com/corestoreio/csfw/eav\"\n\t\"github.com/corestoreio/csfw/storage/csdb\"\n)\n\ntype (\n\tAddressModel struct {\n\t}\n)\n\nvar (\n\t_ eav.EntityTypeModeller = (*AddressModel)(nil)\n\t_ eav.EntityTypeTabler = (*AddressModel)(nil)\n\t_ eav.EntityTypeAdditionalAttributeTabler = (*AddressModel)(nil)\n\t_ eav.EntityTypeIncrementModeller = (*AddressModel)(nil)\n)\n\nfunc (c *AddressModel) TBD() {\n\n}\n\nfunc (c *AddressModel) TableNameBase() string {\n\treturn TableCollection.Name(TableIndexAddressEntity)\n}\n\nfunc (c *AddressModel) TableNameValue(i eav.ValueIndex) string {\n\ts, err := GetAddressValueStructure(i)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn s.Name\n}\n\n\nfunc (c *AddressModel) TableAdditionalAttribute() (*csdb.Table, error) {\n\treturn TableCollection.Structure(TableIndexEAVAttribute)\n}\n\n\nfunc (c *AddressModel) TableEavWebsite() (*csdb.Table, error) {\n\treturn TableCollection.Structure(TableIndexEAVAttributeWebsite)\n}\n\n\n\nfunc Address() *AddressModel ", "output": "{\n\treturn &AddressModel{}\n}"} {"input": "package main\nimport (\n\t\"fmt\"\n)\nvar a = \"G\"\n\nfunc main(){\n\tn()\n\tm()\n\tn()\n\n}\n\nfunc n(){\n\tfmt.Println(a)\n}\n\n\n\nfunc m()", "output": "{\n\ta := \"O\"\n\tfmt.Println(a)\n}"} {"input": "package cmd\n\nimport (\n\t\"github.com/autoabs/autoabs/signing\"\n\t\"os\"\n)\n\n\n\nfunc GenKey() ", "output": "{\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tgenkey := &signing.GenKey{\n\t\tRoot: wd,\n\t\tName: \"AutoABS\",\n\t\tEmail: \"build@autoabs.com\",\n\t}\n\n\terr = genkey.Generate()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = genkey.Export()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}"} {"input": "package project\n\nimport (\n\t\"javaPlugin/pkg/db\"\n\t\"testing\"\n\t\"encoding/json\"\n)\n\ntype parseNameCase struct {\n\tstr string\n\texp []string\n}\n\n\n\nfunc Test_parseName(t *testing.T) {\n\tdb.InitVar(\"10.6.82.199:3306\", \"yzadmin\", \"fxm\", \"fxm@YiZhen\", \"mysql\")\n\terr := db.Init()\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t\treturn\n\t}\n\ttt, err := db.DbClient.Engine().DBMetas()\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t\treturn\n\t}\n\tfor _,value:=range tt{\n\t\tb,err:=json.Marshal(value.Columns())\n\t\tif err!=nil{\n\t\t\tt.Error(err.Error())\n\t\t}else{\n\t\t\tt.Log(string(b))\n\t\t}\n\t}\n\n\n}\n\nfunc (testcase parseNameCase) CheckResult(result []string) bool ", "output": "{\n\tif len(result) != len(testcase.exp) {\n\t\treturn false\n\t}\n\tfor index, str := range result {\n\t\tif str != testcase.exp[index] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}"} {"input": "package file\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/cosiner/gohper/testing2\"\n)\n\n\n\nfunc TestWriteFlag(t *testing.T) {\n\ttt := testing2.Wrap(t)\n\ttt.Eq(os.O_APPEND, WriteFlag(false))\n\ttt.Eq(os.O_TRUNC, WriteFlag(true))\n}\n\nfunc TestCopyFile(t *testing.T) ", "output": "{\n\ttt := testing2.Wrap(t)\n\tsrc, dst := \"/tmp/copytest\", \"/tmp/copytest.copy\"\n\tif Create(src, nil) == nil {\n\t\ttt.True(Create(src, nil) != nil)\n\t\ttt.True(Copy(dst, src) == nil)\n\t\ttt.True(IsFile(dst))\n\t\tos.Remove(dst)\n\t\tos.Remove(src)\n\t}\n}"} {"input": "package runtime\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestHandleCrash(t *testing.T) {\n\tcount := 0\n\texpect := 10\n\tfor i := 0; i < expect; i = i + 1 {\n\t\tdefer HandleCrash()\n\t\tif i%2 == 0 {\n\t\t\tpanic(\"Test Panic\")\n\t\t}\n\t\tcount = count + 1\n\t}\n\tif count != expect {\n\t\tt.Errorf(\"Expected %d iterations, found %d\", expect, count)\n\t}\n}\nfunc TestCustomHandleCrash(t *testing.T) {\n\told := PanicHandlers\n\tdefer func() { PanicHandlers = old }()\n\tvar result interface{}\n\tPanicHandlers = []func(interface{}){\n\t\tfunc(r interface{}) {\n\t\t\tresult = r\n\t\t},\n\t}\n\tfunc() {\n\t\tdefer HandleCrash()\n\t\tpanic(\"test\")\n\t}()\n\tif result != \"test\" {\n\t\tt.Errorf(\"did not receive custom handler\")\n\t}\n}\n\n\nfunc TestCustomHandleError(t *testing.T) ", "output": "{\n\told := ErrorHandlers\n\tdefer func() { ErrorHandlers = old }()\n\tvar result error\n\tErrorHandlers = []func(error){\n\t\tfunc(err error) {\n\t\t\tresult = err\n\t\t},\n\t}\n\terr := fmt.Errorf(\"test\")\n\tHandleError(err)\n\tif result != err {\n\t\tt.Errorf(\"did not receive custom handler\")\n\t}\n}"} {"input": "package guest_get_time\n\nimport (\n\t\"time\"\n\n\t\"github.com/vtolstov/cloudagent/qga\"\n)\n\n\n\nfunc fnGuestGetTime(req *qga.Request) *qga.Response {\n\tres := &qga.Response{ID: req.ID}\n\n\tres.Return = struct {\n\t\tTime int64\n\t}{Time: time.Now().UnixNano()}\n\n\treturn res\n}\n\nfunc init() ", "output": "{\n\tqga.RegisterCommand(&qga.Command{\n\t\tName: \"guest-get-time\",\n\t\tFunc: fnGuestGetTime,\n\t\tEnabled: true,\n\t\tReturns: true,\n\t})\n}"} {"input": "package helpers\n\nimport (\n \"fmt\"\n\n \"kekocity/data/entities\"\n \"kekocity/data/models\"\n \"kekocity/interfaces\"\n)\n\nvar AuthHelper *authHelper\n\ntype authHelper struct{}\n\nfunc init() {\n\tAuthHelper = &authHelper{}\n}\n\n\n\nfunc (a *authHelper) AuthenticateUsingCredentials(_token string) (interfaces.IPlayer, error) {\n var players *entities.Player\n var query string = fmt.Sprintf(\"SELECT * FROM user WHERE token = '%v' LIMIT 1\", _token)\n db.Query(query).Rows(&players)\n\n if players == nil {\n\t\treturn nil, fmt.Errorf(\"Player '%s' not found\", _token)\n\t}\n\n\tplayerModel, err := a.playerEntityToModel(players)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn playerModel, nil\n}\n\nfunc (a *authHelper) playerEntityToModel(_entity *entities.Player) (*models.Player, error) ", "output": "{\n u := models.NewPlayer(_entity)\n\n return u, nil\n}"} {"input": "package gitlab\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/nlamirault/guzuta/utils\"\n)\n\nvar (\n\tnamespace = \"nicolas-lamirault\"\n\tname = \"scame\"\n\tdescription = \"An Emacs configuration\"\n)\n\nfunc getGitlabClient() *Client {\n\treturn NewClient(utils.Getenv(\"GUZUTA_GITLAB_TOKEN\"))\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc TestRetrieveGitlabUnknownProject(t *testing.T) {\n\tclient := getGitlabClient()\n\t_, err := client.GetProject(namespace, \"aaaaaaaaaa\")\n\tif err == nil {\n\t\tt.Fatalf(\"No error with unknown username\")\n\t}\n}\n\nfunc TestRetrieveGitLabProjects(t *testing.T) ", "output": "{\n\tclient := getGitlabClient()\n\tprojects, _ := client.GetProjects()\n\tfor _, project := range *projects {\n\t\tpath := fmt.Sprintf(\"%s/%s\", namespace, project.Path)\n\t\tif !strings.HasPrefix(project.PathWithNamespace, path) {\n\t\t\tt.Fatalf(\"Invalid project name : %s %s\",\n\t\t\t\tproject.PathWithNamespace, path)\n\t\t}\n\t}\n}"} {"input": "package cabf_br\n\n\n\nimport (\n\t\"github.com/zmap/zcrypto/x509\"\n\t\"github.com/zmap/zlint/v3/lint\"\n\t\"github.com/zmap/zlint/v3/util\"\n)\n\ntype CertPolicyOVRequiresProvinceOrLocal struct{}\n\n\n\nfunc init() {\n\tlint.RegisterLint(&lint.Lint{\n\t\tName: \"e_cert_policy_ov_requires_province_or_locality\",\n\t\tDescription: \"If certificate policy 2.23.140.1.2.2 is included, localityName or stateOrProvinceName MUST be included in subject\",\n\t\tCitation: \"BRs: 7.1.6.4\",\n\t\tSource: lint.CABFBaselineRequirements,\n\t\tEffectiveDate: util.CABEffectiveDate,\n\t\tLint: &CertPolicyOVRequiresProvinceOrLocal{},\n\t})\n}\n\nfunc (l *CertPolicyOVRequiresProvinceOrLocal) Initialize() error {\n\treturn nil\n}\n\n\n\nfunc (l *CertPolicyOVRequiresProvinceOrLocal) Execute(cert *x509.Certificate) *lint.LintResult {\n\tvar out lint.LintResult\n\tif util.TypeInName(&cert.Subject, util.LocalityNameOID) || util.TypeInName(&cert.Subject, util.StateOrProvinceNameOID) {\n\t\tout.Status = lint.Pass\n\t} else {\n\t\tout.Status = lint.Error\n\t}\n\treturn &out\n}\n\nfunc (l *CertPolicyOVRequiresProvinceOrLocal) CheckApplies(cert *x509.Certificate) bool ", "output": "{\n\treturn util.IsSubscriberCert(cert) && util.SliceContainsOID(cert.PolicyIdentifiers, util.BROrganizationValidatedOID)\n}"} {"input": "package util\n\nimport (\n\t\"testing\"\n\n\tkubeadmapi \"k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm\"\n)\n\n\n\nfunc TestGenerateToken(t *testing.T) {\n\tvar cfg kubeadmapi.TokenDiscovery\n\n\tGenerateToken(&cfg)\n\tif len(cfg.ID) != 6 {\n\t\tt.Errorf(\"failed GenerateToken first part length:\\n\\texpected: 6\\n\\t actual: %d\", len(cfg.ID))\n\t}\n\tif len(cfg.Secret) != 16 {\n\t\tt.Errorf(\"failed GenerateToken first part length:\\n\\texpected: 16\\n\\t actual: %d\", len(cfg.Secret))\n\t}\n}\n\nfunc TestRandBytes(t *testing.T) {\n\tvar randTest = []int{\n\t\t0,\n\t\t1,\n\t\t2,\n\t\t3,\n\t\t100,\n\t}\n\n\tfor _, rt := range randTest {\n\t\tactual, err := RandBytes(rt)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"failed RandBytes: %v\", err)\n\t\t}\n\t\tif len(actual) != rt*2 {\n\t\t\tt.Errorf(\"failed RandBytes:\\n\\texpected: %d\\n\\t actual: %d\\n\", rt*2, len(actual))\n\t\t}\n\t}\n}\n\nfunc TestTokenParseErrors(t *testing.T) ", "output": "{\n\tinvalidTokens := []string{\n\t\t\"1234567890123456789012\",\n\t\t\"12345.1234567890123456\",\n\t\t\".1234567890123456\",\n\t\t\"123456.1234567890.123456\",\n\t}\n\n\tfor _, token := range invalidTokens {\n\t\tif _, _, err := ParseToken(token); err == nil {\n\t\t\tt.Errorf(\"generateTokenIfNeeded did not return an error for this invalid token: [%s]\", token)\n\t\t}\n\t}\n}"} {"input": "package soong_compat\n\nimport (\n\t\"android/soong/android\"\n)\n\n\n\n\n\nfunc SoongSupportsMkInstallTargets() bool {\n\treturn true\n}\n\nfunc ConvertAndroidMkExtraEntriesFunc(f AndroidMkExtraEntriesFunc) []android.AndroidMkExtraEntriesFunc ", "output": "{\n\treturn []android.AndroidMkExtraEntriesFunc{\n\t\tfunc(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {\n\t\t\tf(entries)\n\t\t},\n\t}\n}"} {"input": "package rpn\n\nimport (\n\t\"strconv\"\n\t\"unicode/utf8\"\n)\n\ntype operator func(int, int) int\n\nvar operations = map[rune]operator{\n\t'+': func(left, right int) int {\n\t\treturn left + right\n\t},\n\t'-': func(left, right int) int {\n\t\treturn left - right\n\t},\n\t'*': func(left, right int) int {\n\t\treturn left * right\n\t},\n\t'/': func(left, right int) int {\n\t\treturn left / right\n\t},\n}\n\nvar operators = func() (result string) {\n\tfor operator := range operations {\n\t\tresult += string(operator)\n\t}\n\treturn\n}()\n\n\n\n\nfunc Calculate(expression string) int ", "output": "{\n\tvar expressionStack intStack\n\texpressionArray := splitExpression(expression)\n\n\tif expressionArray != nil {\n\t\tfor _, oper := range expressionArray {\n\t\t\toperator, _ := utf8.DecodeRuneInString(oper)\n\t\t\tif operation, ok := operations[operator]; ok {\n\t\t\t\tif expressionStack.size() >= 2 {\n\t\t\t\t\texpressionStack.push(operation(expressionStack.pop(), expressionStack.pop()))\n\t\t\t\t} else {\n\t\t\t\t\tpanic(\"Operator requires two arguments\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif value, err := strconv.Atoi(oper); err == nil {\n\t\t\t\t\texpressionStack.push(value)\n\t\t\t\t} else {\n\t\t\t\t\tpanic(\"Operand is not a number\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn expressionStack.pop()\n\t}\n\treturn 0\n}"} {"input": "package hcn\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestMissingNetworkById(t *testing.T) {\n\t_, err := GetNetworkByID(\"5f0b1190-63be-4e0c-b974-bd0f55675a42\")\n\tif err == nil {\n\t\tt.Fatal(\"Unrelated error was thrown.\")\n\t}\n\tif !IsNotFoundError(err) {\n\t\tt.Fatal(\"Unrelated error was thrown.\")\n\t}\n\tif _, ok := err.(NetworkNotFoundError); !ok {\n\t\tt.Fatal(\"Wrong error type was thrown.\")\n\t}\n}\n\nfunc TestMissingNetworkByName(t *testing.T) ", "output": "{\n\t_, err := GetNetworkByName(\"Not found name\")\n\tif err == nil {\n\t\tt.Fatal(\"Error was not thrown.\")\n\t}\n\tif !IsNotFoundError(err) {\n\t\tt.Fatal(\"Unrelated error was thrown.\")\n\t}\n\tif _, ok := err.(NetworkNotFoundError); !ok {\n\t\tt.Fatal(\"Wrong error type was thrown.\")\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/ginuerzh/gosocks5\"\n\t\"github.com/gorilla/websocket\"\n\t\"log\"\n\t\"net/http\"\n\t\"time\"\n)\n\ntype WSConn struct {\n\t*websocket.Conn\n\trb []byte\n}\n\nfunc NewWSConn(conn *websocket.Conn) *WSConn {\n\tc := &WSConn{\n\t\tConn: conn,\n\t}\n\n\treturn c\n}\n\nfunc (conn *WSConn) Read(b []byte) (n int, err error) {\n\tif len(conn.rb) == 0 {\n\t\t_, conn.rb, err = conn.ReadMessage()\n\t}\n\tn = copy(b, conn.rb)\n\tconn.rb = conn.rb[n:]\n\n\n\treturn\n}\n\n\n\nfunc (conn *WSConn) SetDeadline(t time.Time) error {\n\tif err := conn.SetReadDeadline(t); err != nil {\n\t\treturn err\n\t}\n\treturn conn.SetWriteDeadline(t)\n}\n\ntype WSServer struct {\n\tAddr string\n}\n\nvar upgrader = websocket.Upgrader{\n\tReadBufferSize: 8192,\n\tWriteBufferSize: 8192,\n\tCheckOrigin: func(r *http.Request) bool { return true },\n}\n\nfunc (s *WSServer) handle(w http.ResponseWriter, r *http.Request) {\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\tc := gosocks5.ServerConn(NewWSConn(conn), serverConfig)\n\tsocks5Handle(c)\n}\n\nfunc (s *WSServer) ListenAndServe() error {\n\thttp.HandleFunc(\"/\", s.handle)\n\treturn http.ListenAndServe(s.Addr, nil)\n}\n\nfunc (conn *WSConn) Write(b []byte) (n int, err error) ", "output": "{\n\terr = conn.WriteMessage(websocket.BinaryMessage, b)\n\tn = len(b)\n\n\treturn\n}"} {"input": "package model\n\ntype Interface interface {\n\tVisitString(name string, resume func())\n\tVisitInt(name string, resume func())\n\tVisitFloat(name string, resume func())\n\tVisitBool(name string, resume func())\n\tVisitPtr(name string, resume func())\n\tVisitBytes(name string, resume func())\n\tVisitSlice(name string, resume func())\n\tVisitStruct(name string, fields []Field, resume func())\n\tVisitStructField(field Field, resume func())\n\tVisitMap(name string, resume func())\n\tVisitCustom(name string, resume func())\n\tVisitReference(name string, resume func())\n}\n\ntype Visitor struct{}\n\nfunc (self *Visitor) VisitString(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitInt(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitFloat(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitBool(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitPtr(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitBytes(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitSlice(name string, resume func()) {\n\tresume()\n}\n\n\n\nfunc (self *Visitor) VisitStructField(field Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitMap(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitCustom(name string, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitReference(name string, resume func()) {\n\tresume()\n}\n\ntype EmbeddedStructVisitor struct {\n\tInterface\n}\n\nfunc (self *EmbeddedStructVisitor) VisitStruct(name string, fields []Field, resume func()) {\n\tresume()\n}\n\nfunc (self *Visitor) VisitStruct(name string, fields []Field, resume func()) ", "output": "{\n\tresume()\n}"} {"input": "package state\n\nimport (\n\t\"context\"\n)\n\ntype envKey struct{}\n\n\n\nfunc ContextWith(ctx context.Context, s Store) context.Context {\n\treturn context.WithValue(ctx, envKey{}, s)\n}\n\n\n\n\nfunc FromContext(ctx context.Context) Store {\n\tif e, ok := ctx.Value(envKey{}).(Store); ok {\n\t\treturn e\n\t}\n\tpanic(\"no Store found in context\")\n}\n\n\ntype fail interface {\n\tError(args ...interface{})\n}\n\n\nfunc GetStringOrFail(ctx context.Context, t fail, key string) string {\n\tvalue := \"\"\n\tstate := FromContext(ctx)\n\tif err := state.Get(ctx, key, &value); err != nil {\n\t\tt.Error(err)\n\t}\n\treturn value\n}\n\n\n\n\n\nfunc SetOrFail(ctx context.Context, t fail, key string, value interface{}) {\n\tstate := FromContext(ctx)\n\tif err := state.Set(ctx, key, value); err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc GetOrFail(ctx context.Context, t fail, key string, value interface{}) ", "output": "{\n\tstate := FromContext(ctx)\n\tif err := state.Get(ctx, key, value); err != nil {\n\t\tt.Error(err)\n\t}\n}"} {"input": "package lib\n\nimport (\n\t\"github.com/hyperledger/fabric-ca/lib/common\"\n\t\"github.com/hyperledger/fabric-ca/lib/metadata\"\n)\n\n\ntype ServerInfoResponseNet struct {\n\tCAName string\n\tCAChain string\n\tIssuerPublicKey string\n\tVersion string\n}\n\nfunc newCAInfoEndpoint(s *Server) *serverEndpoint {\n\treturn &serverEndpoint{\n\t\tMethods: []string{\"GET\", \"POST\", \"HEAD\"},\n\t\tHandler: cainfoHandler,\n\t\tServer: s,\n\t}\n}\n\n\n\n\nfunc cainfoHandler(ctx *serverRequestContextImpl) (interface{}, error) ", "output": "{\n\tca, err := ctx.GetCA()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp := &common.CAInfoResponseNet{}\n\terr = ca.fillCAInfo(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp.Version = metadata.GetVersion()\n\treturn resp, nil\n}"} {"input": "package api\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api/resource\"\n)\n\n\n\n\n\nfunc (self *ResourceList) Cpu() *resource.Quantity {\n\tif val, ok := (*self)[ResourceCPU]; ok {\n\t\treturn &val\n\t}\n\treturn &resource.Quantity{}\n}\n\n\nfunc (self *ResourceList) Memory() *resource.Quantity {\n\tif val, ok := (*self)[ResourceMemory]; ok {\n\t\treturn &val\n\t}\n\treturn &resource.Quantity{}\n}\n\nfunc (self *ResourceList) Pods() *resource.Quantity {\n\tif val, ok := (*self)[ResourcePods]; ok {\n\t\treturn &val\n\t}\n\treturn &resource.Quantity{}\n}\n\nfunc GetContainerStatus(statuses []ContainerStatus, name string) (ContainerStatus, bool) {\n\tfor i := range statuses {\n\t\tif statuses[i].Name == name {\n\t\t\treturn statuses[i], true\n\t\t}\n\t}\n\treturn ContainerStatus{}, false\n}\n\nfunc GetExistingContainerStatus(statuses []ContainerStatus, name string) ContainerStatus {\n\tfor i := range statuses {\n\t\tif statuses[i].Name == name {\n\t\t\treturn statuses[i]\n\t\t}\n\t}\n\treturn ContainerStatus{}\n}\n\n\nfunc IsPodReady(pod *Pod) bool {\n\tfor _, c := range pod.Status.Conditions {\n\t\tif c.Type == PodReady && c.Status == ConditionTrue {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (self ResourceName) String() string ", "output": "{\n\treturn string(self)\n}"} {"input": "package common\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"runtime/debug\"\n\t\"strings\"\n)\n\n\n\n\n\nfunc PrintDepricationWarning(str string) {\n\tline := strings.Repeat(\"#\", len(str)+4)\n\temptyLine := strings.Repeat(\" \", len(str))\n\tfmt.Printf(`\n%s\n# %s #\n# %s #\n# %s #\n%s\n\n`, line, emptyLine, str, emptyLine, line)\n}\n\nfunc Report(extra ...interface{}) ", "output": "{\n\tfmt.Fprintln(os.Stderr, \"You've encountered a sought after, hard to reproduce bug. Please report this to the developers <3 https:github.com/WhaleCoinOrg/WhaleCoin/issues\")\n\tfmt.Fprintln(os.Stderr, extra...)\n\n\t_, file, line, _ := runtime.Caller(1)\n\tfmt.Fprintf(os.Stderr, \"%v:%v\\n\", file, line)\n\n\tdebug.PrintStack()\n\n\tfmt.Fprintln(os.Stderr, \"#### BUG! PLEASE REPORT ####\")\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\ntype OpenpitrixRoleResource struct {\n\n\tCPU int64 `json:\"cpu,omitempty\"`\n\n\tGpu int64 `json:\"gpu,omitempty\"`\n\n\tInstanceSize int64 `json:\"instance_size,omitempty\"`\n\n\tMemory int64 `json:\"memory,omitempty\"`\n\n\tRole string `json:\"role,omitempty\"`\n\n\tStorageSize int64 `json:\"storage_size,omitempty\"`\n}\n\n\n\n\n\nfunc (m *OpenpitrixRoleResource) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\nfunc (m *OpenpitrixRoleResource) UnmarshalBinary(b []byte) error {\n\tvar res OpenpitrixRoleResource\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}\n\nfunc (m *OpenpitrixRoleResource) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package iso20022\n\n\ntype CardPaymentBatchTransferResponse1 struct {\n\n\tTransactionTotals *TransactionTotals2 `xml:\"TxTtls\"`\n\n\tDataSet []*CardPaymentDataSet5 `xml:\"DataSet,omitempty\"`\n}\n\nfunc (c *CardPaymentBatchTransferResponse1) AddTransactionTotals() *TransactionTotals2 {\n\tc.TransactionTotals = new(TransactionTotals2)\n\treturn c.TransactionTotals\n}\n\n\n\nfunc (c *CardPaymentBatchTransferResponse1) AddDataSet() *CardPaymentDataSet5 ", "output": "{\n\tnewValue := new(CardPaymentDataSet5)\n\tc.DataSet = append(c.DataSet, newValue)\n\treturn newValue\n}"} {"input": "package screepsws\n\nimport \"fmt\"\n\nfunc (ws *webSocket) SubscribeRoom(shard, room string) (<-chan RoomResponse, error) {\n\tchannel := fmt.Sprintf(roomFormat, shard, room)\n\tdataChan, err := ws.Subscribe(channel)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to subscribe to '%s'\", channel)\n\t}\n\n\trespChan := make(chan RoomResponse)\n\tgo func() {\n\t\tdefer close(respChan)\n\t\tfor data := range dataChan {\n\t\t\tresp := RoomResponse{}\n\t\t\tclosed := UnmarshalResponse(data, &resp)\n\t\t\tif closed {\n\t\t\t\treturn\n\t\t\t}\n\t\t\trespChan <- resp\n\t\t}\n\t}()\n\n\treturn respChan, nil\n}\n\nfunc (ws *webSocket) UnsubscribeRoom(shard, room string) error {\n\treturn ws.Unsubscribe(fmt.Sprintf(roomFormat, shard, room))\n}\n\n\n\nfunc (ws *webSocket) UnsubscribeRoomMap(shard, room string) error {\n\treturn ws.Unsubscribe(fmt.Sprintf(roomMapFormat, shard, room))\n}\n\nfunc (ws *webSocket) SubscribeRoomMap(shard, room string) (<-chan RoomMapResponse, error) ", "output": "{\n\tchannel := fmt.Sprintf(roomMapFormat, shard, room)\n\tdataChan, err := ws.Subscribe(channel)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to subscribe to '%s'\", channel)\n\t}\n\n\trespChan := make(chan RoomMapResponse)\n\tgo func() {\n\t\tdefer close(respChan)\n\t\tfor data := range dataChan {\n\t\t\tresp := RoomMapResponse{}\n\t\t\tclosed := UnmarshalResponse(data, &resp)\n\t\t\tif closed {\n\t\t\t\treturn\n\t\t\t}\n\t\t\trespChan <- resp\n\t\t}\n\t}()\n\n\treturn respChan, nil\n}"} {"input": "package errors\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n)\n\n\ntype HTTPError struct {\n\tStatusCode int\n\terror\n}\n\n\n\n\n\n\n\nfunc NewMethodNotAllowed(method string) *HTTPError {\n\treturn &HTTPError{http.StatusMethodNotAllowed, errors.New(`Method is not allowed:\"` + method + `\"`)}\n}\n\n\nfunc NewBadRequest(err error) *HTTPError {\n\treturn &HTTPError{http.StatusBadRequest, err}\n}\n\n\n\nfunc NewBadRequestString(s string) *HTTPError {\n\treturn NewBadRequest(errors.New(s))\n}\n\n\n\nfunc NewBadRequestMissingParameter(s string) *HTTPError {\n\treturn NewBadRequestString(`Missing parameter \"` + s + `\"`)\n}\n\n\n\nfunc NewBadRequestUnwantedParameter(s string) *HTTPError {\n\treturn NewBadRequestString(`Unwanted parameter \"` + s + `\"`)\n}\n\nfunc (e *HTTPError) Error() string ", "output": "{\n\treturn e.error.Error()\n}"} {"input": "package main\n\nimport ()\n\ntype channel struct {\n\tpath string\n\tqueue queue\n\tconnections connections\n\th *hub\n}\n\ntype connections map[*connection]interface {\n}\n\nfunc (c *channel) run() {\n\tincr(\"channels\", 1)\n\tdefer c.stop()\n\tfor cmd := range c.queue {\n\t\tswitch cmd.cmd {\n\t\tcase SUBSCRIBE:\n\t\t\tc.subscribe(cmd.conn)\n\t\tcase UNSUBSCRIBE:\n\t\t\tc.unsubscribe(cmd.conn)\n\t\t\tif len(c.connections) == 0 {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase PUBLISH:\n\t\t\tc.publish(cmd.text)\n\t\tcase BROADCAST:\n\t\t\tc.broadcast(cmd.text)\n\t\tdefault:\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (c *channel) stop() {\n\tclose(c.queue)\n\tc.h.queue <- command{cmd: REMOVE, path: c.path}\n\tdecr(\"channels\", 1)\n}\n\nfunc (c *channel) subscribe(conn *connection) {\n\tc.connections[conn] = nil\n}\n\nfunc (c *channel) unsubscribe(conn *connection) {\n\tif _, ok := c.connections[conn]; ok {\n\t\tclose(conn.send)\n\t\tdelete(c.connections, conn)\n\t}\n}\n\nfunc (c *channel) publish(text []byte) {\n\tif len(text) == 0 {\n\t\treturn\n\t}\n\tc.h.queue <- command{cmd: PUBLISH, path: c.path, text: text}\n}\n\n\n\nfunc (c *channel) broadcast(text []byte) ", "output": "{\n\tif len(text) == 0 {\n\t\treturn\n\t}\n\tfor conn := range c.connections {\n\t\tselect {\n\t\tcase conn.send <- text:\n\t\tdefault:\n\t\t\tc.unsubscribe(conn)\n\t\t}\n\t}\n}"} {"input": "package testclient\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n\tclientgotesting \"k8s.io/client-go/testing\"\n\n\tuserapi \"github.com/openshift/origin/pkg/user/apis/user\"\n)\n\n\n\ntype FakeIdentities struct {\n\tFake *Fake\n}\n\nvar identitiesResource = schema.GroupVersionResource{Group: \"\", Version: \"\", Resource: \"identities\"}\n\nfunc (c *FakeIdentities) Get(name string, options metav1.GetOptions) (*userapi.Identity, error) {\n\tobj, err := c.Fake.Invokes(clientgotesting.NewRootGetAction(identitiesResource, name), &userapi.Identity{})\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*userapi.Identity), err\n}\n\nfunc (c *FakeIdentities) List(opts metav1.ListOptions) (*userapi.IdentityList, error) {\n\tobj, err := c.Fake.Invokes(clientgotesting.NewRootListAction(identitiesResource, opts), &userapi.IdentityList{})\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*userapi.IdentityList), err\n}\n\n\n\nfunc (c *FakeIdentities) Update(inObj *userapi.Identity) (*userapi.Identity, error) {\n\tobj, err := c.Fake.Invokes(clientgotesting.NewRootUpdateAction(identitiesResource, inObj), inObj)\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*userapi.Identity), err\n}\n\nfunc (c *FakeIdentities) Delete(name string) error {\n\t_, err := c.Fake.Invokes(clientgotesting.NewRootDeleteAction(identitiesResource, name), nil)\n\treturn err\n}\n\nfunc (c *FakeIdentities) Create(inObj *userapi.Identity) (*userapi.Identity, error) ", "output": "{\n\tobj, err := c.Fake.Invokes(clientgotesting.NewRootCreateAction(identitiesResource, inObj), inObj)\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*userapi.Identity), err\n}"} {"input": "package goDB\n\nimport (\n \"encoding/json\"\n \"os\"\n)\n\n\ntype BlockMetadata struct {\n Timestamp int64 `json:\"timestamp\"`\n PcapPacketsReceived int `json:\"pcap_packets_received\"`\n PcapPacketsDropped int `json:\"pcap_packets_dropped\"`\n PcapPacketsIfDropped int `json:\"pcap_packets_if_dropped\"`\n PacketsLogged int `json:\"packets_logged\"`\n\n \n FlowCount uint64 `json:\"flowcount\"`\n Traffic uint64 `json:\"traffic\"`\n}\n\n\n\ntype Metadata struct {\n Blocks []BlockMetadata `json:\"blocks\"`\n}\n\n\n\n\nfunc ReadMetadata(path string) (*Metadata, error) {\n var result Metadata\n\n f, err := os.Open(path)\n if err != nil {\n return nil, err\n }\n defer f.Close()\n\n if err := json.NewDecoder(f).Decode(&result); err != nil {\n return nil, err\n }\n\n return &result, nil\n}\n\n\n\nfunc TryReadMetadata(path string) *Metadata {\n meta, err := ReadMetadata(path)\n if err != nil {\n return NewMetadata()\n }\n return meta\n}\n\nfunc WriteMetadata(path string, meta *Metadata) error {\n f, err := os.Create(path)\n if err != nil {\n return err\n }\n defer f.Close()\n\n return json.NewEncoder(f).Encode(meta)\n}\n\nfunc NewMetadata() *Metadata ", "output": "{\n return &Metadata{}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/astaxie/beego\"\n\t\"test/models\"\n\t_ \"test/routers\"\n\t\"os\"\n)\n\n\n\nfunc main() {\n\tbeego.Run()\n}\n\nfunc initArgs() {\n\targs := os.Args\n\tfor _, v := range args {\n\t\tif v == \"-syncdb\" {\n\t\t\tmodels.Syncbd(false)\n\t\t\tos.Exit(0)\n\t\t}\n\t\tif v == \"-syncdb-force\" {\n\t\t\tmodels.Syncbd(true)\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n}\n\nfunc init() ", "output": "{\n\tmodels.Connect()\n\tinitArgs()\n}"} {"input": "package wire\n\nimport (\n\t\"bytes\"\n\t\"io\"\n)\n\n\n\ntype fixedWriter struct {\n\tb []byte\n\tpos int\n}\n\n\n\n\n\n\nfunc (w *fixedWriter) Write(p []byte) (n int, err error) {\n\tlenp := len(p)\n\tif w.pos+lenp > cap(w.b) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\tn = lenp\n\tw.pos += copy(w.b[w.pos:], p)\n\treturn\n}\n\n\nfunc (w *fixedWriter) Bytes() []byte {\n\treturn w.b\n}\n\n\n\nfunc newFixedWriter(max int) io.Writer {\n\tb := make([]byte, max)\n\tfw := fixedWriter{b, 0}\n\treturn &fw\n}\n\n\n\ntype fixedReader struct {\n\tbuf []byte\n\tpos int\n\tiobuf *bytes.Buffer\n}\n\n\n\n\n\n\nfunc (fr *fixedReader) Read(p []byte) (n int, err error) {\n\tn, err = fr.iobuf.Read(p)\n\tfr.pos += n\n\treturn\n}\n\n\n\n\n\nfunc newFixedReader(max int, buf []byte) io.Reader ", "output": "{\n\tb := make([]byte, max)\n\tif buf != nil {\n\t\tcopy(b[:], buf)\n\t}\n\n\tiobuf := bytes.NewBuffer(b)\n\tfr := fixedReader{b, 0, iobuf}\n\treturn &fr\n}"} {"input": "package elements\n\nimport \"github.com/fileformats/graphics/jt/model\"\n\n\n\n\ntype InfiniteLightAttribute struct {\n\tBaseLight\n\tVersionNumber uint8\n\tDirection model.Vector3D\n}\n\nfunc (n InfiniteLightAttribute) GUID() model.GUID {\n\treturn model.InfiniteLightAttributeElement\n}\n\nfunc (n *InfiniteLightAttribute) Read(c *model.Context) error {\n\tc.LogGroup(\"InfiniteLightAttribute\")\n\tdefer c.LogGroupEnd()\n\n\tif err := (&n.BaseLight).Read(c); err != nil {\n\t\treturn err\n\t}\n\n\tif c.Version.Equal(model.V8) {\n\t\tc.Data.Unpack(&n.Direction)\n\t\tn.VersionNumber = uint8(c.Data.Int16())\n\n\t\tif n.VersionNumber == 1 {\n\t\t\tn.CoordSystem = c.Data.Int32()\n\t\t\tc.Log(\"CoordSystem: %d\", n.CoordSystem)\n\t\t}\n\t}\n\n\tif c.Version.Equal(model.V9) {\n\t\tn.VersionNumber = uint8(c.Data.Int16())\n\t\tc.Data.Unpack(&n.Direction)\n\n\t\tif n.VersionNumber == 2 {\n\t\t\tn.ShadowOpacity = c.Data.Float32()\n\t\t\tc.Log(\"ShadowOpacity: %f\", n.ShadowOpacity)\n\t\t}\n\t}\n\n\tif c.Version.GreaterEqThan(model.V10) {\n\t\tn.VersionNumber = c.Data.UInt8()\n\t\tc.Data.Unpack(&n.Direction)\n\t}\n\tc.Log(\"VersionNumber: %d\", n.VersionNumber)\n\tc.Log(\"Direction: %s\", n.Direction)\n\n\n\treturn c.Data.GetError()\n}\n\nfunc (n *InfiniteLightAttribute) GetBaseAttribute() *BaseAttribute {\n\treturn &n.BaseAttribute\n}\n\n\n\nfunc (n *InfiniteLightAttribute) BaseElement() *JTElement ", "output": "{\n\treturn &n.JTElement\n}"} {"input": "package console\n\nimport \"github.com/cgrates/cgrates/utils\"\n\nfunc init() {\n\tc := &CmdGetCacheAge{\n\t\tname: \"cache_age\",\n\t\trpcMethod: \"ApierV1.GetCachedItemAge\",\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdGetCacheAge struct {\n\tname string\n\trpcMethod string\n\trpcParams *StringWrapper\n\t*CommandExecuter\n}\n\nfunc (self *CmdGetCacheAge) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdGetCacheAge) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdGetCacheAge) RpcParams() interface{} {\n\tif self.rpcParams == nil {\n\t\tself.rpcParams = &StringWrapper{}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdGetCacheAge) PostprocessRpcParams() error {\n\treturn nil\n}\n\n\n\nfunc (self *CmdGetCacheAge) RpcResult() interface{} ", "output": "{\n\treturn &utils.CachedItemAge{}\n}"} {"input": "package cmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/viper\"\n\t\"github.com/willf/bloom\"\n)\n\nvar checkCmd = &cobra.Command{\n\tUse: \"check\",\n\tShort: \"Check domain presence in the bloom filter\",\n}\n\n\n\nfunc check(cmd *cobra.Command, args []string) error {\n\tif err := InitializeConfig(checkCmd); err != nil {\n\t\treturn err\n\t}\n\n\tbf := bloom.New(1000000, 5)\n\n\tfileName := viper.GetString(\"DatabasePath\")\n\tif _, err := os.Stat(fileName); err == nil {\n\t\tbff, err2 := os.Open(fileName)\n\t\tif err2 != nil {\n\t\t\tpanic(err2)\n\t\t}\n\t\tdefer bff.Close()\n\n\t\tif _, err3 := bf.ReadFrom(bff); err != nil {\n\t\t\tpanic(err3)\n\t\t}\n\t} else {\n\t\tfmt.Println(\"You must build a filter first, use 'build' command.\")\n\t\treturn err\n\t}\n\n\tif len(args) > 0 {\n\t\tfor _, domain := range args {\n\t\t\tfmt.Printf(\"%s,%v\\n\", domain, bf.TestString(domain))\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc init() ", "output": "{\n\tinitCommonFlags(checkCmd)\n\n\tcheckCmd.RunE = check\n}"} {"input": "package iris2\n\nimport (\n\t\"fmt\"\n)\n\ntype Mux struct {\n\trunning bool\n\tsources []<-chan interface{}\n\tselector chan Word\n\tdestination chan interface{}\n\terr chan error\n\n\tControl <-chan Word\n\tSelect chan<- Word\n\tDestination <-chan interface{}\n\tError <-chan error\n}\n\nfunc NewMux(control chan<- Word) *Mux {\n\tvar mux Mux\n\tmux.err = make(chan error)\n\tmux.destination = make(chan interface{})\n\tmux.selector = make(chan Word)\n\tmux.Error = mux.err\n\tmux.Destination = mux.destination\n\tmux.Control = control\n\tmux.Select = mux.selector\n\treturn &mux\n}\nfunc (this *Mux) AddSource(src <-chan interface{}) {\n\tthis.sources = append(this.sources, src)\n}\n\n\nfunc (this *Mux) queryControl() {\n\t<-this.Control\n\tif err := this.shutdown(); err != nil {\n\t\tthis.err <- err\n\t}\n}\n\nfunc (this *Mux) shutdown() error {\n\tif !this.running {\n\t\treturn fmt.Errorf(\"Attempted to shutdown a multiplexer which isn't running\")\n\t} else {\n\t\tthis.running = false\n\t\tclose(this.selector)\n\t\treturn nil\n\t}\n}\n\nfunc (this *Mux) Startup() error {\n\tif this.running {\n\t\treturn fmt.Errorf(\"Given multiplexer is already running!\")\n\t} else {\n\t\tthis.running = true\n\t\tgo this.body()\n\t\tgo this.queryControl()\n\t\treturn nil\n\t}\n}\n\nfunc (this *Mux) body() ", "output": "{\n\tfor this.running {\n\t\tselect {\n\t\tcase index, more := <-this.selector:\n\t\t\tif more {\n\t\t\t\tif index >= Word(len(this.sources)) {\n\t\t\t\t\tthis.err <- fmt.Errorf(\"Selected non existent source: %d\", index)\n\t\t\t\t} else if index < 0 {\n\t\t\t\t\tthis.err <- fmt.Errorf(\"Select source %d is less than zero!\", index)\n\t\t\t\t} else {\n\t\t\t\t\tthis.destination <- <-this.sources[index]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package mock\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"github.com/Matir/webborer/client\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\ntype MockClientFactory struct {\n\tForeverClient *MockClient\n\tNextClient *MockClient\n}\n\ntype MockClient struct {\n\tForeverResponse *http.Response\n\tNextResponse *http.Response\n\tRequests []*url.URL\n\tRedir *url.URL\n\tCheckRedirect func(*http.Request, []*http.Request) error\n}\n\nfunc (f *MockClientFactory) Get() client.Client {\n\tif f.NextClient != nil {\n\t\tc := f.NextClient\n\t\tf.NextClient = nil\n\t\treturn c\n\t}\n\tif f.ForeverClient != nil {\n\t\treturn f.ForeverClient\n\t}\n\treturn &MockClient{}\n}\n\nfunc (c *MockClient) RequestURL(u *url.URL) (*http.Response, error) {\n\treturn c.Request(u, \"\", \"GET\", nil)\n}\n\n\n\nfunc (c *MockClient) SetCheckRedirect(f func(*http.Request, []*http.Request) error) {\n\tc.CheckRedirect = f\n}\n\nfunc ResponseFromString(s string) *http.Response {\n\tcb := ioutil.NopCloser(bytes.NewBufferString(s))\n\treturn &http.Response{\n\t\tBody: cb,\n\t}\n}\n\nfunc MockRobotsResponse() *http.Response {\n\ts := `User-agent: *\nDisallow: /a`\n\treturn ResponseFromString(s)\n}\n\nfunc (c *MockClient) Request(u *url.URL, host, method string, header http.Header) (*http.Response, error) ", "output": "{\n\tc.Requests = append(c.Requests, u)\n\tif c.Redir != nil && c.CheckRedirect != nil {\n\t\treq := &http.Request{URL: c.Redir}\n\t\tif err := c.CheckRedirect(req, []*http.Request{}); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif c.ForeverResponse != nil {\n\t\treturn c.ForeverResponse, nil\n\t}\n\tif c.NextResponse == nil {\n\t\treturn nil, errors.New(\"No NextResponse for MockClient.\")\n\t}\n\tr := c.NextResponse\n\tc.NextResponse = nil\n\treturn r, nil\n}"} {"input": "package addrmgr\n\nimport (\n\t\"time\"\n\n\t\"github.com/abcsuite/abcd/wire\"\n)\n\n\n\nfunc TstKnownAddressChance(ka *KnownAddress) float64 {\n\treturn ka.chance()\n}\n\nfunc TstNewKnownAddress(na *wire.NetAddress, attempts int,\n\tlastattempt, lastsuccess time.Time, tried bool, refs int) *KnownAddress {\n\treturn &KnownAddress{na: na, attempts: attempts, lastattempt: lastattempt,\n\t\tlastsuccess: lastsuccess, tried: tried, refs: refs}\n}\n\nfunc TstKnownAddressIsBad(ka *KnownAddress) bool ", "output": "{\n\treturn ka.isBad()\n}"} {"input": "package testutil\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gopkg.in/yaml.v3\"\n)\n\ntype Context struct {\n\tName string `yaml:\"name,omitempty\"`\n\tContext struct {\n\t\tNamespace string `yaml:\"namespace,omitempty\"`\n\t} `yaml:\"context,omitempty\"`\n}\n\nfunc Ctx(name string) *Context { return &Context{Name: name} }\nfunc (c *Context) Ns(ns string) *Context { c.Context.Namespace = ns; return c }\n\ntype Kubeconfig map[string]interface{}\n\nfunc KC() *Kubeconfig {\n\treturn &Kubeconfig{\n\t\t\"apiVersion\": \"v1\",\n\t\t\"kind\": \"Config\"}\n}\n\nfunc (k *Kubeconfig) Set(key string, v interface{}) *Kubeconfig { (*k)[key] = v; return k }\n\nfunc (k *Kubeconfig) WithCtxs(c ...*Context) *Kubeconfig { (*k)[\"contexts\"] = c; return k }\n\nfunc (k *Kubeconfig) ToYAML(t *testing.T) string {\n\tt.Helper()\n\tvar v strings.Builder\n\tif err := yaml.NewEncoder(&v).Encode(*k); err != nil {\n\t\tt.Fatalf(\"failed to encode mock kubeconfig: %v\", err)\n\t}\n\treturn v.String()\n}\n\nfunc (k *Kubeconfig) WithCurrentCtx(s string) *Kubeconfig ", "output": "{ (*k)[\"current-context\"] = s; return k }"} {"input": "package cpumanager\n\nimport (\n\t\"k8s.io/api/core/v1\"\n\t\"k8s.io/klog\"\n\t\"k8s.io/kubernetes/pkg/kubelet/cm/cpumanager/state\"\n\t\"k8s.io/kubernetes/pkg/kubelet/cm/topologymanager\"\n)\n\ntype nonePolicy struct{}\n\nvar _ Policy = &nonePolicy{}\n\n\nconst PolicyNone policyName = \"none\"\n\n\nfunc NewNonePolicy() Policy {\n\treturn &nonePolicy{}\n}\n\nfunc (p *nonePolicy) Name() string {\n\treturn string(PolicyNone)\n}\n\n\n\nfunc (p *nonePolicy) AddContainer(s state.State, pod *v1.Pod, container *v1.Container) error {\n\treturn nil\n}\n\nfunc (p *nonePolicy) RemoveContainer(s state.State, podUID string, containerName string) error {\n\treturn nil\n}\n\nfunc (p *nonePolicy) GetTopologyHints(s state.State, pod v1.Pod, container v1.Container) map[string][]topologymanager.TopologyHint {\n\treturn nil\n}\n\nfunc (p *nonePolicy) Start(s state.State) ", "output": "{\n\tklog.Info(\"[cpumanager] none policy: Start\")\n}"} {"input": "package fields\n\nimport (\n\t\"regexp\"\n\t\"time\"\n)\n\nfunc UseDefaultKeyIfCustomKeyIsEmpty(defaultKey, customKey string) string {\n\tif \"\" != customKey {\n\t\treturn customKey\n\t}\n\treturn defaultKey\n}\n\nfunc ExecFuncIfErrIsNotNil(err error, fn func()) (b bool) {\n\tif nil != err {\n\t\tfn()\n\t\tb = true\n\t}\n\treturn\n}\n\n\n\nfunc getPatternFromRegExp(re *regexp.Regexp) string {\n\tif nil == re {\n\t\treturn \"\"\n\t}\n\treturn re.String()\n}\n\nfunc execFnIfNotNil(fn func()) {\n\tif nil != fn {\n\t\tfn()\n\t}\n}\n\nfunc addSuffix(name string, suffix *string) string {\n\tif nil != suffix {\n\t\treturn name + \"-\" + *suffix\n\t}\n\treturn name\n}\n\nfunc _useDefaultIfNotUserDefinedOrCouldntFindIt(defaultLoc *time.Location, locationByString *string) (*time.Location, int) {\n\tif nil == locationByString || \"\" == *locationByString {\n\t\treturn defaultLoc, 1\n\t}\n\n\tif loc, err := time.LoadLocation(*locationByString); nil == err {\n\t\treturn loc, 2\n\t}\n\n\treturn defaultLoc, 0\n}\n\n\nfunc useDefaultIfNotUserDefinedOrCouldntFindIt(defaultLoc *time.Location, locationByString *string) *time.Location {\n\tloc, _ := _useDefaultIfNotUserDefinedOrCouldntFindIt(defaultLoc, locationByString)\n\treturn loc\n}\n\nfunc getMessageFromError(err error) string ", "output": "{\n\tif nil == err {\n\t\treturn \"\"\n\t}\n\treturn err.Error()\n}"} {"input": "package models\n\n\n\n\nimport (\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/validate\"\n)\n\n\n\ntype Item struct {\n\n\tCompleted bool `json:\"completed,omitempty\"`\n\n\tDescription *string `json:\"description\"`\n\n\tID int64 `json:\"id,omitempty\"`\n}\n\n\nfunc (m *Item) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateDescription(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\n\nfunc (m *Item) validateDescription(formats strfmt.Registry) error ", "output": "{\n\n\tif err := validate.Required(\"description\", \"body\", m.Description); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validate.MinLength(\"description\", \"body\", string(*m.Description), 1); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package util\n\nimport \"go/build\"\n\n\n\n\n\n\n\n\n\n\nfunc DirToImport(p string) (string, error) {\n\tpkg, err := build.ImportDir(p, build.FindOnly)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn pkg.ImportPath, nil\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc ImportToDir(imp string) (string, error) ", "output": "{\n\tpkg, err := build.Import(imp, \"\", build.FindOnly)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn pkg.Dir, nil\n}"} {"input": "package subscriptions\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/status-im/status-go/rpc\"\n)\n\ntype ethFilter struct {\n\tid string\n\trpcClient *rpc.Client\n}\n\nfunc installEthFilter(rpcClient *rpc.Client, method string, args []interface{}) (*ethFilter, error) {\n\n\tif err := validateEthMethod(method); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result string\n\n\terr := rpcClient.Call(&result, rpcClient.UpstreamChainID, method, args...)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfilter := ðFilter{\n\t\tid: result,\n\t\trpcClient: rpcClient,\n\t}\n\n\treturn filter, nil\n\n}\n\nfunc (ef *ethFilter) getID() string {\n\treturn ef.id\n}\n\nfunc (ef *ethFilter) getChanges() ([]interface{}, error) {\n\tvar result []interface{}\n\n\terr := ef.rpcClient.Call(&result, ef.rpcClient.UpstreamChainID, \"eth_getFilterChanges\", ef.getID())\n\n\treturn result, err\n}\n\nfunc (ef *ethFilter) uninstall() error {\n\treturn ef.rpcClient.Call(nil, ef.rpcClient.UpstreamChainID, \"eth_uninstallFilter\", ef.getID())\n}\n\n\n\nfunc validateEthMethod(method string) error ", "output": "{\n\tfor _, allowedMethod := range []string{\n\t\t\"eth_newFilter\",\n\t\t\"eth_newBlockFilter\",\n\t\t\"eth_newPendingTransactionFilter\",\n\t} {\n\t\tif method == allowedMethod {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"unexpected filter method: %s\", method)\n}"} {"input": "package terminal\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"golang.org/x/crypto/ssh/terminal\"\n)\n\n\n\nfunc GetSize() (w, h int) {\n\tw, h, err := terminal.GetSize(int(os.Stdout.Fd()))\n\tif err != nil {\n\t\tw, h = 80, 25\n\t}\n\treturn w, h\n}\n\n\nfunc IsTerminal(fd int) bool {\n\treturn terminal.IsTerminal(fd)\n}\n\n\n\n\n\n\n\nfunc WriteTerminalTitle(title string) {\n\tfmt.Printf(ChangeTitle + title + BEL)\n}\n\nfunc ReadPassword(fd int) ([]byte, error) ", "output": "{\n\treturn terminal.ReadPassword(fd)\n}"} {"input": "package blanket_emulator\n\nimport (\n\t\"fmt\"\n)\n\ntype Event interface {\n\tHash() uint64\n\tInspect() string\n}\n\ntype ReturnEvent uint64\ntype ReadEvent uint64\ntype WriteEvent struct {\n\tAddr uint64\n\tValue uint64\n}\ntype SyscallEvent uint64\ntype InvalidInstructionEvent uint64\n\nfunc (addr ReadEvent) Hash() uint64 {\n\treturn ReadEventHash(uint64(addr))\n}\n\nfunc (s WriteEvent) Hash() uint64 {\n\treturn WriteEventHash(s.Addr, s.Value)\n}\n\nfunc (s SyscallEvent) Hash() uint64 {\n\treturn SysEventHash(uint64(s))\n}\n\nfunc (s ReturnEvent) Hash() uint64 {\n\treturn ReturnEventHash(uint64(s))\n}\n\n\n\nfunc (addr ReadEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Read([%x])\", addr)\n}\n\nfunc (addr ReturnEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Return([%x])\", addr)\n}\n\nfunc (s WriteEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Write([%x]=%x)\", s.Addr, s.Value)\n}\n\nfunc (s SyscallEvent) Inspect() string {\n\treturn fmt.Sprintf(\"Sys(%x)\", s)\n}\n\nfunc (s InvalidInstructionEvent) Inspect() string {\n\treturn fmt.Sprintf(\"InvalidOpcode([%x])\", s)\n}\n\nfunc (s InvalidInstructionEvent) Hash() uint64 ", "output": "{\n\treturn InvalidInstructionEventHash(uint64(s))\n}"} {"input": "package util\n\nimport (\n\t\"fmt\"\n\t\"os/exec\"\n)\n\n\n\nfunc HRBserive(SetRun bool) ", "output": "{\n\tvar cmd *exec.Cmd\n\n\tif SetRun {\n\t\tcmd = exec.Command(\"net\", \"start\", \"HitRobotBase\")\n\t} else {\n\t\tcmd = exec.Command(\"net\", \"stop\", \"HitRobotBase\")\n\n\t}\n\n\terr := cmd.Run()\n\tif err !=nil{\n\t\tfmt.Printf(\"%+v\",err)\n\t}\n\n\tcmd.Wait()\n\n\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\t\"testing\"\n\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http/httptest\"\n\t\"sync\"\n\n\t\"github.com/NyaaPantsu/nyaa/config\"\n)\n\ntype MyHandler struct {\n\tsync.Mutex\n\tcount int\n}\n\n\n\nfunc TestCreateHTTPListener(t *testing.T) {\n\tconf := config.Get()\n\ttestListener, err := CreateHTTPListener(conf)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tsrv := httptest.NewUnstartedServer(&MyHandler{})\n\tsrv.Listener = testListener\n\tdefer srv.Close()\n\n\tsrv.Start()\n\tfor _, i := range []int{1, 2} {\n\t\tresp, err := http.Get(srv.URL)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif resp.StatusCode != 200 {\n\t\t\tt.Fatalf(\"Received non-200 response: %d\\n\", resp.StatusCode)\n\t\t}\n\t\texpected := fmt.Sprintf(\"Visitor count: %d.\", i)\n\t\tactual, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif expected != string(actual) {\n\t\t\tt.Errorf(\"Expected the message '%s', got '%s'\\n\", expected, string(actual))\n\t\t}\n\t}\n}\n\nfunc (h *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tvar count int\n\th.Lock()\n\th.count++\n\tcount = h.count\n\th.Unlock()\n\n\tfmt.Fprintf(w, \"Visitor count: %d.\", count)\n}"} {"input": "package imageutil\n\nimport (\n\t\"image\"\n\t\"os\"\n)\n\n\n\n\n\nfunc OpenImage(name string) (image.Image, string, error) ", "output": "{\n\timageFile, err := os.Open(name)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\timageFileDecoded, format, err := image.Decode(imageFile)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tif err := imageFile.Close(); err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\treturn imageFileDecoded, format, nil\n}"} {"input": "package sqlbuilder\n\n\ntype DeleteStatement struct {\n\tfrom Table\n\twhere Condition\n\n\terr error\n}\n\n\nfunc Delete(from Table) *DeleteStatement {\n\tif from == nil {\n\t\treturn &DeleteStatement{\n\t\t\terr: newError(\"from is nil.\"),\n\t\t}\n\t}\n\tif _, ok := from.(*table); !ok {\n\t\treturn &DeleteStatement{\n\t\t\terr: newError(\"CreateTable can use only natural table.\"),\n\t\t}\n\t}\n\treturn &DeleteStatement{\n\t\tfrom: from,\n\t}\n}\n\n\n\n\n\nfunc (b *DeleteStatement) ToSql() (query string, args []interface{}, err error) {\n\tbldr := newBuilder()\n\tdefer func() {\n\t\tquery, args, err = bldr.Query(), bldr.Args(), bldr.Err()\n\t}()\n\tif b.err != nil {\n\t\tbldr.SetError(b.err)\n\t\treturn\n\t}\n\n\tbldr.Append(\"DELETE FROM \")\n\tbldr.AppendItem(b.from)\n\n\tif b.where != nil {\n\t\tbldr.Append(\" WHERE \")\n\t\tbldr.AppendItem(b.where)\n\t}\n\treturn\n}\n\nfunc (b *DeleteStatement) Where(cond Condition) *DeleteStatement ", "output": "{\n\tif b.err != nil {\n\t\treturn b\n\t}\n\tfor _, col := range cond.columns() {\n\t\tif !b.from.hasColumn(col) {\n\t\t\tb.err = newError(\"column not found in FROM\")\n\t\t\treturn b\n\t\t}\n\t}\n\tb.where = cond\n\treturn b\n}"} {"input": "package output\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/jutkko/mindown/util\"\n)\n\nconst DEPTH_LIMIT int = 6\n\n\n\nfunc writeMarkdownRecursively(depth int, file *os.File, node *util.Node) error {\n\terr := appendToFile(fmt.Sprintf(\"%s%s\\n\", getHash(depth), node.GetTitle()), file)\n\n\tif err != nil || len(node.GetChildren()) == 0 {\n\t\treturn err\n\t}\n\n\tfor _, node := range node.GetChildren() {\n\t\terr := writeMarkdownRecursively(depth+1, file, node)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc getHash(level int) (result string) {\n\tresult = \"\"\n\n\tif level <= DEPTH_LIMIT {\n\t\tfor i := 0; i < level; i++ {\n\t\t\tresult += \"#\"\n\t\t}\n\t\tresult += \" \"\n\t}\n\n\treturn\n}\n\nfunc appendToFile(data string, file *os.File) error {\n\tif _, err := file.WriteString(data); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc WriteMarkdown(filename string, forceWrite bool, graph *util.Graph) error ", "output": "{\n\tif !forceWrite {\n\t\tif _, err := os.Stat(filename); !os.IsNotExist(err) {\n\t\t\treturn errors.New(\"File exists\")\n\t\t}\n\t}\n\n\tos.Remove(filename)\n\n\tfile, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)\n\tif err != nil {\n\t\treturn errors.New(\"Failed to open file\")\n\t}\n\tdefer file.Close()\n\n\tif graph == nil {\n\t\treturn errors.New(\"Graph is nil\")\n\t}\n\n\tfor _, node := range graph.GetNodes() {\n\t\terr := writeMarkdownRecursively(1, file, node)\n\n\t\tif err != nil {\n\t\t\treturn errors.New(fmt.Sprintf(\"Failed to write file: %s %s\", filename, err.Error()))\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package rpc\n\nimport (\n\t\"net\"\n\t\"net/rpc\"\n\t\"net/rpc/jsonrpc\"\n\t\"time\"\n\n\tlog \"github.com/sirupsen/logrus\"\n\n\t\"github.com/Cepave/open-falcon-backend/modules/hbs/g\"\n)\n\ntype Hbs int\ntype Agent int\ntype NqmAgent int\n\n\nfunc Stop() {\n\tnqmAgentHbsService.Stop()\n\tAgentHeartbeatService.Stop()\n}\n\nfunc Start() ", "output": "{\n\tnqmAgentHbsService.Start()\n\tAgentHeartbeatService.Start()\n\n\taddr := g.Config().Listen\n\n\tserver := rpc.NewServer()\n\tserver.Register(new(Agent))\n\tserver.Register(new(Hbs))\n\tserver.Register(new(NqmAgent))\n\n\tl, e := net.Listen(\"tcp\", addr)\n\tif e != nil {\n\t\tlog.Fatalln(\"listen error:\", e)\n\t} else {\n\t\tlog.Println(\"listening\", addr)\n\t}\n\n\tfor {\n\t\tconn, err := l.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(\"listener accept fail:\", err)\n\t\t\ttime.Sleep(time.Duration(100) * time.Millisecond)\n\t\t\tcontinue\n\t\t}\n\t\tgo server.ServeCodec(jsonrpc.NewServerCodec(conn))\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\n\t\"fmt\"\n\n\t\"github.com/ammario/fastpass\"\n)\n\n\n\nfunc cmdGet(fp *fastpass.FastPass) ", "output": "{\n\tsearch := flag.Arg(0)\n\n\tif len(flag.Args()) != 1 {\n\t\tusage()\n\t}\n\n\tresults := fp.Entries.SortByName()\n\n\tif search != \"\" {\n\t\tresults = fp.Entries.SortByBestMatch(search)\n\t}\n\n\tif len(results) == 0 {\n\t\tfail(\"no results found\")\n\t}\n\n\te := results[0]\n\te.Stats.Hit()\n\n\tif len(results) > 1 {\n\t\tfmt.Printf(\"similar: \")\n\t\tfor i, r := range results[1:] {\n\t\t\tif i > 5 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfmt.Printf(\"%v \", r.Name)\n\t\t}\n\t\tfmt.Printf(\"\\n\")\n\t}\n\n\tcopyPassword(e)\n}"} {"input": "package fakes\n\nimport \"os\"\n\ntype FileIO struct {\n\tTempFileCall struct {\n\t\tCallCount int\n\t\tReceives struct {\n\t\t\tDir string\n\t\t\tPrefix string\n\t\t}\n\t\tReturns struct {\n\t\t\tFile *os.File\n\t\t\tError error\n\t\t}\n\t}\n\tReadFileCall struct {\n\t\tCallCount int\n\t\tReceives struct {\n\t\t\tFilename string\n\t\t}\n\t\tReturns struct {\n\t\t\tContents []byte\n\t\t\tError error\n\t\t}\n\t}\n\tWriteFileCall struct {\n\t\tCallCount int\n\t\tReceives struct {\n\t\t\tFilename string\n\t\t\tContents []byte\n\t\t}\n\t\tReturns struct {\n\t\t\tError error\n\t\t}\n\t}\n\tStatCall struct {\n\t\tCallCount int\n\t\tReceives struct {\n\t\t\tName string\n\t\t}\n\t\tReturns struct {\n\t\t\tFileInfo os.FileInfo\n\t\t\tError error\n\t\t}\n\t}\n}\n\n\n\nfunc (fake *FileIO) ReadFile(filename string) ([]byte, error) {\n\tfake.ReadFileCall.CallCount++\n\tfake.ReadFileCall.Receives.Filename = filename\n\treturn fake.ReadFileCall.Returns.Contents, fake.ReadFileCall.Returns.Error\n}\n\nfunc (fake *FileIO) WriteFile(filename string, contents []byte, perm os.FileMode) error {\n\tfake.WriteFileCall.CallCount++\n\tfake.WriteFileCall.Receives.Filename = filename\n\tfake.WriteFileCall.Receives.Contents = contents\n\treturn fake.WriteFileCall.Returns.Error\n}\n\nfunc (fake *FileIO) Stat(name string) (os.FileInfo, error) {\n\tfake.StatCall.CallCount++\n\tfake.StatCall.Receives.Name = name\n\treturn fake.StatCall.Returns.FileInfo, fake.StatCall.Returns.Error\n}\n\nfunc (fake *FileIO) TempFile(dir, prefix string) (f *os.File, err error) ", "output": "{\n\tfake.TempFileCall.CallCount++\n\tfake.TempFileCall.Receives.Dir = dir\n\tfake.TempFileCall.Receives.Prefix = prefix\n\treturn fake.TempFileCall.Returns.File, fake.TempFileCall.Returns.Error\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\nfunc init() {\n\td1 := &D1{}\n\tchallenges[1] = &challenge{\"Day 01\", \"input/day01.txt\", d1}\n}\n\n\nfunc MFR(mass int) int {\n\treturn (mass / 3) - 2\n}\n\ntype D1 struct {\n\tmodules []int\n}\n\nfunc (d1 *D1) parse(line string) error {\n\tv, err := strconv.Atoi(line)\n\tif err == nil {\n\t\td1.modules = append(d1.modules, v)\n\t}\n\treturn err\n}\n\nfunc (d1 *D1) part1() (string, error) {\n\tsum := 0\n\tfor _, module := range d1.modules {\n\t\tsum += MFR(module)\n\t}\n\treturn fmt.Sprintf(\"Sum of fuel requirements is %d\", sum), nil\n}\n\n\n\nfunc (d1 *D1) part2() (string, error) {\n\tsum := 0\n\tfor _, module := range d1.modules {\n\t\tsum += TotalMFR(module)\n\t}\n\treturn fmt.Sprintf(\"Sum of fuel requirements is %d\", sum), nil\n}\n\nfunc TotalMFR(mass int) int ", "output": "{\n\treq := MFR(mass)\n\tif req > 0 {\n\t\treq += TotalMFR(req)\n\t} else {\n\t\treq = 0\n\t}\n\treturn req\n}"} {"input": "package commands\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype basicHandler struct {\n\thandler func(args ...string) (string, error)\n\thelp func(args ...string) string\n}\n\nvar _ CommandHandler = (*basicHandler)(nil)\n\nfunc (h *basicHandler) Handle(argv ...string) (string, error) {\n\treturn h.handler(argv...)\n}\n\nfunc (h *basicHandler) Help(argv ...string) string {\n\treturn h.help(argv...)\n}\n\n\n\nfunc Simple(responder func(...string) (string, error), help string) CommandHandler {\n\treturn &basicHandler{\n\t\thandler: func(argv ...string) (string, error) {\n\t\t\treturn responder(argv...)\n\t\t},\n\t\thelp: func(argv ...string) string {\n\t\t\treturn fmt.Sprintf(\"`!%s` - %s\", strings.Join(argv, \" \"), help)\n\t\t},\n\t}\n}\n\nfunc Static(response, help string) CommandHandler ", "output": "{\n\treturn &basicHandler{\n\t\thandler: func(argv ...string) (string, error) {\n\t\t\treturn response, nil\n\t\t},\n\t\thelp: func(argv ...string) string {\n\t\t\treturn fmt.Sprintf(\"`!%s` - %s\", strings.Join(argv, \" \"), help)\n\t\t},\n\t}\n}"} {"input": "package models\n\nimport (\n\t\"github.com/go-swagger/go-swagger/errors\"\n\t\"github.com/go-swagger/go-swagger/strfmt\"\n)\n\n\n\n\n\ntype Post struct {\n\tResource\n\n\tAuthor *Author `json:\"author,omitempty\"`\n\n\tContent string `json:\"content,omitempty\"`\n\n\tStatus int32 `json:\"status,omitempty\"`\n\n\tTitle string `json:\"title,omitempty\"`\n\n\tViewCount int64 `json:\"viewCount,omitempty\"`\n}\n\n\n\n\nfunc (m *Post) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tif err := m.Resource.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package probe_test\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/minio/mc/pkg/probe\"\n\t. \"gopkg.in/check.v1\"\n)\n\n\n\ntype MySuite struct{}\n\nvar _ = Suite(&MySuite{})\n\nfunc testDummy0() *probe.Error {\n\t_, e := os.Stat(\"this-file-cannot-exit\")\n\treturn probe.NewError(e)\n}\n\nfunc testDummy1() *probe.Error {\n\treturn testDummy0().Trace(\"DummyTag1\")\n}\n\nfunc testDummy2() *probe.Error {\n\treturn testDummy1().Trace(\"DummyTag2\")\n}\n\nfunc (s *MySuite) TestProbe(c *C) {\n\tprobe.Init() \n\tprobe.SetAppInfo(\"Commit-ID\", \"7390cc957239\")\n\tes := testDummy2().Trace(\"TopOfStack\")\n\tc.Assert(es, Not(Equals), nil)\n\n\tnewES := es.Trace()\n\tc.Assert(newES, Not(Equals), nil)\n}\n\nfunc (s *MySuite) TestWrappedError(c *C) {\n\t_, e := os.Stat(\"this-file-cannot-exit\")\n\tes := probe.NewError(e) \n\te = probe.WrapError(es) \n\t_, ok := probe.UnwrapError(e)\n\tc.Assert(ok, Equals, true)\n}\n\nfunc Test(t *testing.T) ", "output": "{ TestingT(t) }"} {"input": "package install\n\nimport (\n\t\"k8s.io/apimachinery/pkg/apimachinery/announced\"\n\t\"k8s.io/apimachinery/pkg/apimachinery/registered\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/client-go/pkg/api\"\n\t\"k8s.io/client-go/pkg/apis/autoscaling\"\n\t\"k8s.io/client-go/pkg/apis/autoscaling/v1\"\n)\n\n\n\n\nfunc Install(groupFactoryRegistry announced.APIGroupFactoryRegistry, registry *registered.APIRegistrationManager, scheme *runtime.Scheme) {\n\tif err := announced.NewGroupMetaFactory(\n\t\t&announced.GroupMetaFactoryArgs{\n\t\t\tGroupName: autoscaling.GroupName,\n\t\t\tVersionPreferenceOrder: []string{v1.SchemeGroupVersion.Version},\n\t\t\tImportPrefix: \"k8s.io/client-go/pkg/apis/autoscaling\",\n\t\t\tAddInternalObjectsToScheme: autoscaling.AddToScheme,\n\t\t},\n\t\tannounced.VersionToSchemeFunc{\n\t\t\tv1.SchemeGroupVersion.Version: v1.AddToScheme,\n\t\t},\n\t).Announce(groupFactoryRegistry).RegisterAndEnable(registry, scheme); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc init() ", "output": "{\n\tInstall(api.GroupFactoryRegistry, api.Registry, api.Scheme)\n}"} {"input": "package protect\n\nimport \"golang.org/x/sys/unix\"\n\n\nvar ProtectEnabled = true\n\n\n\n\n\nfunc Pledge(s string) error ", "output": "{\n\treturn unix.PledgePromises(s)\n}"} {"input": "package matchers\n\nimport (\n\t\"fmt\"\n\t\"github.com/bfontaine/go-tchoutchou/Godeps/_workspace/src/github.com/onsi/gomega/format\"\n\t\"reflect\"\n)\n\ntype BeEquivalentToMatcher struct {\n\tExpected interface{}\n}\n\n\n\nfunc (matcher *BeEquivalentToMatcher) FailureMessage(actual interface{}) (message string) {\n\treturn format.Message(actual, \"to be equivalent to\", matcher.Expected)\n}\n\nfunc (matcher *BeEquivalentToMatcher) NegatedFailureMessage(actual interface{}) (message string) {\n\treturn format.Message(actual, \"not to be equivalent to\", matcher.Expected)\n}\n\nfunc (matcher *BeEquivalentToMatcher) Match(actual interface{}) (success bool, err error) ", "output": "{\n\tif actual == nil && matcher.Expected == nil {\n\t\treturn false, fmt.Errorf(\"Both actual and expected must not be nil.\")\n\t}\n\n\tconvertedActual := actual\n\n\tif actual != nil && matcher.Expected != nil && reflect.TypeOf(actual).ConvertibleTo(reflect.TypeOf(matcher.Expected)) {\n\t\tconvertedActual = reflect.ValueOf(actual).Convert(reflect.TypeOf(matcher.Expected)).Interface()\n\t}\n\n\treturn reflect.DeepEqual(convertedActual, matcher.Expected), nil\n}"} {"input": "package scoring\n\nimport (\n\t\"github.com/timpalpant/rummy/deck\"\n)\n\n\n\n\n\nfunc Value(card deck.Card) int ", "output": "{\n\tswitch {\n\tcase deck.Card_TWO <= card.Rank && card.Rank <= deck.Card_NINE:\n\t\treturn 5\n\tcase deck.Card_TEN <= card.Rank && card.Rank <= deck.Card_KING:\n\t\treturn 10\n\tcase card.Rank == deck.Card_ACE:\n\t\treturn 15\n\t}\n\n\treturn -1\n}"} {"input": "package graph\n\nimport (\n\t\"github.com/docker/docker/engine\"\n\t\"github.com/docker/docker/pkg/parsers\"\n)\n\n\n\n\n\n\n\n\n\n\nfunc (s *TagStore) CmdTagLegacy(job *engine.Job) engine.Status {\n\tif len(job.Args) != 2 && len(job.Args) != 3 {\n\t\treturn job.Errorf(\"Usage: %s IMAGE REPOSITORY [TAG]\\n\", job.Name)\n\t}\n\tvar tag string\n\tif len(job.Args) == 3 {\n\t\ttag = job.Args[2]\n\t}\n\tif err := s.Set(job.Args[1], tag, job.Args[0], job.GetenvBool(\"force\")); err != nil {\n\t\treturn job.Error(err)\n\t}\n\treturn engine.StatusOK\n}\n\nfunc (s *TagStore) CmdTag(job *engine.Job) engine.Status ", "output": "{\n\tif len(job.Args) != 2 {\n\t\treturn job.Errorf(\"usage: %s NEWNAME OLDNAME\", job.Name)\n\t}\n\tvar (\n\t\tnewName = job.Args[0]\n\t\toldName = job.Args[1]\n\t)\n\tnewRepo, newTag := parsers.ParseRepositoryTag(newName)\n\tif err := s.Set(newRepo, newTag, oldName, true); err != nil {\n\t\treturn job.Error(err)\n\t}\n\treturn engine.StatusOK\n}"} {"input": "package iso20022\n\n\ntype ClosingBalance5Choice struct {\n\n\tFinal *BalanceQuantity12Choice `xml:\"Fnl\"`\n\n\tIntermediary *BalanceQuantity12Choice `xml:\"Intrmy\"`\n}\n\nfunc (c *ClosingBalance5Choice) AddFinal() *BalanceQuantity12Choice {\n\tc.Final = new(BalanceQuantity12Choice)\n\treturn c.Final\n}\n\n\n\nfunc (c *ClosingBalance5Choice) AddIntermediary() *BalanceQuantity12Choice ", "output": "{\n\tc.Intermediary = new(BalanceQuantity12Choice)\n\treturn c.Intermediary\n}"} {"input": "package net\n\nimport (\n\t\"io\"\n)\n\nconst (\n\tbufferSize = 4 * 1024\n)\n\n\nfunc ReaderToChan(stream chan<- []byte, reader io.Reader) error {\n\tfor {\n\t\tbuffer := make([]byte, bufferSize)\n\t\tnBytes, err := reader.Read(buffer)\n\t\tif nBytes > 0 {\n\t\t\tstream <- buffer[:nBytes]\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}\n\n\n\n\nfunc ChanToWriter(writer io.Writer, stream <-chan []byte) error ", "output": "{\n\tfor buffer := range stream {\n\t\t_, err := writer.Write(buffer)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"input": "package memlimit\n\nimport (\n \"testing\"\n)\n\n\n\nfunc TestMemLimit(t *testing.T) ", "output": "{\n r, _ := MemToUse(1, 0.3)\n mib := uint64(1024*1024)\n if r != mib {\n t.Error(\"min failed\")\n }\n\n twomib := 2*mib\n r, _ = MemToUse(twomib, 0.3)\n if r != twomib {\n t.Error(\"2mib failed\")\n }\n\n tib := mib*mib\n r, _ = MemToUse(tib, 0.3)\n if r == tib {\n t.Error(\"tib failed\")\n }\n}"} {"input": "package longrunning_test\n\nimport (\n\t\"cloud.google.com/go/longrunning/autogen\"\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/api/iterator\"\n\tlongrunningpb \"google.golang.org/genproto/googleapis/longrunning\"\n)\n\nfunc ExampleNewOperationsClient() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\t_ = c\n}\n\nfunc ExampleOperationsClient_GetOperation() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.GetOperationRequest{\n\t}\n\tresp, err := c.GetOperation(ctx, req)\n\tif err != nil {\n\t}\n\t_ = resp\n}\n\nfunc ExampleOperationsClient_ListOperations() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.ListOperationsRequest{\n\t}\n\tit := c.ListOperations(ctx, req)\n\tfor {\n\t\tresp, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t}\n\t\t_ = resp\n\t}\n}\n\n\n\nfunc ExampleOperationsClient_DeleteOperation() {\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.DeleteOperationRequest{\n\t}\n\terr = c.DeleteOperation(ctx, req)\n\tif err != nil {\n\t}\n}\n\nfunc ExampleOperationsClient_CancelOperation() ", "output": "{\n\tctx := context.Background()\n\tc, err := longrunning.NewOperationsClient(ctx)\n\tif err != nil {\n\t}\n\n\treq := &longrunningpb.CancelOperationRequest{\n\t}\n\terr = c.CancelOperation(ctx, req)\n\tif err != nil {\n\t}\n}"} {"input": "package sw\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport (\n\t\"fmt\"\n\t\"github.com/kortschak/BioGo/seq\"\n)\n\n\n\nfunc ExampleAligner_Align() ", "output": "{\n\tswsa := &seq.Seq{Seq: []byte(\"ACACACTA\")}\n\tswsb := &seq.Seq{Seq: []byte(\"AGCACACA\")}\n\n\tswm := [][]int{\n\t\t{2, -1, -1, -1, -1},\n\t\t{-1, 2, -1, -1, -1},\n\t\t{-1, -1, 2, -1, -1},\n\t\t{-1, -1, -1, 2, -1},\n\t\t{-1, -1, -1, -1, 0},\n\t}\n\n\tsmith := &Aligner{Matrix: swm, LookUp: LookUpN, GapChar: '-'}\n\tif swa, err := smith.Align(swsa, swsb); err == nil {\n\t\tfmt.Printf(\"%s\\n%s\\n\", swa[0].Seq, swa[1].Seq)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"text/tabwriter\"\n)\n\ntype depaccountTableOutput struct{ w *tabwriter.Writer }\n\n\n\nfunc (out *depaccountTableOutput) BasicFooter() {\n\tout.w.Flush()\n}\n\nfunc (cmd *getCommand) getDEPAccount(args []string) error {\n\tflagset := flag.NewFlagSet(\"dep-account\", flag.ExitOnError)\n\tflagset.Usage = usageFor(flagset, \"mdmctl get dep-account [flags]\")\n\tif err := flagset.Parse(args); err != nil {\n\t\treturn err\n\t}\n\tw := tabwriter.NewWriter(os.Stdout, 0, 4, 2, ' ', 0)\n\tout := &depaccountTableOutput{w}\n\tout.BasicHeader()\n\tdefer out.BasicFooter()\n\tctx := context.Background()\n\tresp, err := cmd.depsvc.GetAccountInfo(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Fprintf(out.w, \"%s\\t%s\\t%s\\t%s\\n\", resp.OrgName, resp.OrgPhone, resp.OrgEmail, resp.ServerName)\n\treturn nil\n}\n\nfunc (out *depaccountTableOutput) BasicHeader() ", "output": "{\n\tfmt.Fprintf(out.w, \"OrgName\\tOrgPhone\\tOrgEmail\\tServerName\\n\")\n}"} {"input": "package hdiutil\n\nimport \"os/exec\"\n\n\ntype formatFlag interface {\n\tformatFlag() []string\n}\n\ntype convertFormot int\n\nconst (\n\tConvertUDRW convertFormot = 1 << iota\n\tConvertUDRO\n\tConvertUDCO\n\tConvertUDZO\n\tConvertULFO\n\tConvertUDBZ\n\tConvertUDTO\n\tConvertUDSP\n\tConvertUDSB\n\tConvertUFBI\n\tConvertUDRo\n\tConvertUDCo\n\tConvertRdWr\n\tConvertRdxx\n\tConvertROCo\n\tConvertRken\n\tConvertDC42\n)\n\n\ntype convertFlag interface {\n\tconvertFlag() []string\n}\n\n\ntype ConvertAlign int\n\nfunc (c ConvertAlign) convertFlag() []string { return intFlag(\"align\", int(c)) }\n\ntype convertPmap bool\n\nfunc (c convertPmap) convertFlag() []string { return boolFlag(\"pmap\", bool(c)) }\n\n\n\n\n\n\ntype ConvertSegmentSize string\n\nfunc (c ConvertSegmentSize) convertFlag() []string { return stringFlag(\"segmentSize\", string(c)) }\n\n\n\n\ntype ConvertTasks int\n\n\n\nconst (\n\tConvertPmap convertPmap = true\n)\n\n\nfunc Convert(image string, format formatFlag, outfile string, flags ...convertFlag) error {\n\tcmd := exec.Command(hdiutilPath, \"convert\", image)\n\tcmd.Args = append(cmd.Args, format.formatFlag()...)\n\tcmd.Args = append(cmd.Args, outfile)\n\tif len(flags) > 0 {\n\t\tfor _, flag := range flags {\n\t\t\tcmd.Args = append(cmd.Args, flag.convertFlag()...)\n\t\t}\n\t}\n\n\terr := cmd.Run()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (c ConvertTasks) convertFlag() []string ", "output": "{ return intFlag(\"tasks\", int(c)) }"} {"input": "package utils\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"os\"\n\t\"strconv\"\n)\n\nvar path string\n\nfunc init() {\n\tflag.StringVar(&path, \"path\", \"\", \"Path to the inputfile\")\n\tflag.Parse()\n}\n\ntype Input struct {\n\t*bufio.Scanner\n}\n\n\nfunc GetInput() (*Input, error) {\n\tif len(path) > 0 {\n\t\tfile, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn &Input{}, err\n\t\t}\n\n\t\treturn &Input{bufio.NewScanner(file)}, nil\n\t}\n\treturn &Input{bufio.NewScanner(os.Stdin)}, nil\n}\n\n\n\nfunc (input *Input) ReadInts(size int) []int {\n\tinput.Split(bufio.ScanWords)\n\tints := make([]int, size)\n\n\tfor i := 0; i < size && input.Scan(); i++ {\n\t\tresult, err := strconv.Atoi(input.Text())\n\t\tif err == nil {\n\t\t\tints[i] = result\n\t\t}\n\t}\n\n\treturn ints\n}\n\nfunc (input *Input) ReadString() string {\n\tinput.Split(bufio.ScanWords)\n\n\tif input.Scan() {\n\t\treturn input.Text()\n\t}\n\n\treturn \"\"\n}\n\nfunc (input *Input) ReadStrings(size int) []string {\n\tinput.Split(bufio.ScanWords)\n\n\tstrings := make([]string, size)\n\n\tfor i := 0; i < size && input.Scan(); i++ {\n\t\tstrings[i] = input.Text()\n\t}\n\n\treturn strings\n}\n\nfunc (input *Input) ReadInt() int ", "output": "{\n\tinput.Split(bufio.ScanWords)\n\n\tif input.Scan() {\n\t\tresult, err := strconv.Atoi(input.Text())\n\t\tif err == nil {\n\t\t\treturn result\n\t\t}\n\t}\n\n\treturn 3\n}"} {"input": "package main\n\n\n\nimport (\n\t\"code.google.com/p/mx3/cuda\"\n\t\"code.google.com/p/mx3/data\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n)\n\nfunc main() {\n\tcuda.Init()\n\n\tN0, N1, N2 := 1, 64, 128\n\tc := 1.\n\tmesh := data.NewMesh(N0, N1, N2, c/2, c*2, c)\n\n\tm := cuda.NewSlice(3, mesh)\n\tconv := cuda.NewDemag(mesh)\n\tcuda.Memset(m, 1, 1, 1)\n\n\tB := cuda.NewSlice(3, mesh)\n\tBsat := 1.\n\tvol := data.NilSlice(1, mesh)\n\tconv.Exec(B, m, vol, Bsat)\n\tout := B.HostCopy()\n\n\tbx := out.Vectors()[0][N0/2][N1/2][N2/2]\n\tby := out.Vectors()[1][N0/2][N1/2][N2/2]\n\tbz := out.Vectors()[2][N0/2][N1/2][N2/2]\n\tfmt.Println(\"demag tensor:\", bx, by, bz)\n\tcheck(bx, -1)\n\tcheck(by, 0)\n\tcheck(bz, 0)\n\tfmt.Println(\"OK\")\n}\n\n\n\nfunc check(have, want float32) ", "output": "{\n\tif math.Abs(float64(have-want)) > 1e-2 {\n\t\tlog.Fatal(\"error too large: want \", want, \" have \", have)\n\t}\n}"} {"input": "package database\n\nimport (\n\t\"context\"\n\n\t\"github.com/grafana/grafana/pkg/models\"\n\t\"github.com/grafana/grafana/pkg/services/sqlstore\"\n)\n\ntype TeamGuardianStoreImpl struct {\n\tsqlStore sqlstore.Store\n}\n\n\n\nfunc (t *TeamGuardianStoreImpl) GetTeamMembers(ctx context.Context, query models.GetTeamMembersQuery) ([]*models.TeamMemberDTO, error) {\n\tif err := t.sqlStore.GetTeamMembers(ctx, &query); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn query.Result, nil\n}\n\nfunc ProvideTeamGuardianStore(sqlStore sqlstore.Store) *TeamGuardianStoreImpl ", "output": "{\n\treturn &TeamGuardianStoreImpl{sqlStore: sqlStore}\n}"} {"input": "package memcachep\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"strconv\"\n)\n\ntype Stats map[string]fmt.Stringer\n\n\ntype FuncStat struct {\n\tCallable func() string\n}\n\nfunc (f *FuncStat) String() string {\n\treturn f.Callable()\n}\n\n\ntype StaticStat struct {\n\tValue string\n}\n\nfunc (s *StaticStat) String() string {\n\treturn s.Value\n}\n\n\ntype CounterStat struct {\n\tCount int\n\tcalculations chan int\n}\n\nfunc (c *CounterStat) Increment(num int) {\n\tc.calculations <- num\n}\n\nfunc (c *CounterStat) SetCount(num int) {\n\tc.Count = num\n}\n\nfunc (c *CounterStat) Decrement(num int) {\n\tc.calculations <- -num\n}\n\nfunc (c *CounterStat) String() string {\n\treturn strconv.Itoa(c.Count)\n}\n\n\n\nfunc NewCounterStat() *CounterStat {\n\tc := &CounterStat{}\n\tc.calculations = make(chan int, 100)\n\tgo c.work()\n\treturn c\n}\n\nfunc NewStats() Stats {\n\ts := make(Stats)\n\ts[\"pid\"] = &StaticStat{strconv.Itoa(os.Getpid())}\n\ts[\"version\"] = &StaticStat{VERSION}\n\ts[\"golang\"] = &StaticStat{runtime.Version()}\n\ts[\"goroutines\"] = &FuncStat{func() string { return strconv.Itoa(runtime.NumGoroutine()) }}\n\ts[\"cpu_num\"] = &StaticStat{strconv.Itoa(runtime.NumCPU())}\n\ts[\"total_connections\"] = NewCounterStat()\n\ts[\"curr_connections\"] = NewCounterStat()\n\ts[\"cmd_get\"] = NewCounterStat()\n\treturn s\n}\n\nfunc (c *CounterStat) work() ", "output": "{\n\tfor num := range c.calculations {\n\t\tc.Count = c.Count + num\n\t}\n}"} {"input": "package db\n\nimport (\n\t\"database/sql\"\n\t\"github.com/simplemvc/gocorelib/revel\"\n)\n\nvar (\n\tDb *sql.DB\n\tDriver string\n\tSpec string\n)\n\nfunc Init() {\n\tvar found bool\n\tif Driver, found = revel.Config.String(\"db.driver\"); !found {\n\t\trevel.ERROR.Fatal(\"No db.driver found.\")\n\t}\n\tif Spec, found = revel.Config.String(\"db.spec\"); !found {\n\t\trevel.ERROR.Fatal(\"No db.spec found.\")\n\t}\n\n\tvar err error\n\tDb, err = sql.Open(Driver, Spec)\n\tif err != nil {\n\t\trevel.ERROR.Fatal(err)\n\t}\n}\n\ntype Transactional struct {\n\t*revel.Controller\n\tTxn *sql.Tx\n}\n\n\n\n\n\nfunc (c *Transactional) Rollback() revel.Result {\n\tif c.Txn != nil {\n\t\tif err := c.Txn.Rollback(); err != nil {\n\t\t\tif err != sql.ErrTxDone {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t\tc.Txn = nil\n\t}\n\treturn nil\n}\n\n\nfunc (c *Transactional) Commit() revel.Result {\n\tif c.Txn != nil {\n\t\tif err := c.Txn.Commit(); err != nil {\n\t\t\tif err != sql.ErrTxDone {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t\tc.Txn = nil\n\t}\n\treturn nil\n}\n\nfunc init() {\n\trevel.InterceptMethod((*Transactional).Begin, revel.BEFORE)\n\trevel.InterceptMethod((*Transactional).Commit, revel.AFTER)\n\trevel.InterceptMethod((*Transactional).Rollback, revel.FINALLY)\n}\n\nfunc (c *Transactional) Begin() revel.Result ", "output": "{\n\ttxn, err := Db.Begin()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tc.Txn = txn\n\treturn nil\n}"} {"input": "package fs\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\nvar execExts map[string]bool\n\nfunc init() {\n\tpathext := filepath.SplitList(os.Getenv(\"PATHEXT\"))\n\texecExts = make(map[string]bool, len(pathext))\n\tfor _, ext := range pathext {\n\t\texecExts[strings.ToLower(ext)] = true\n\t}\n}\n\n\n\nfunc isWindowsExecutable(path string) bool {\n\treturn execExts[strings.ToLower(filepath.Ext(path))]\n}\n\nfunc (e basicFileInfo) Mode() FileMode {\n\tm := e.FileInfo.Mode()\n\tif m&os.ModeSymlink != 0 && e.Size() > 0 {\n\t\tm &^= os.ModeSymlink\n\t}\n\tif isWindowsExecutable(e.Name()) {\n\t\tm |= 0111\n\t}\n\tm &^= 0022\n\treturn FileMode(m)\n}\n\n\n\nfunc (e basicFileInfo) Group() int {\n\treturn -1\n}\n\n\n\nfunc (e *basicFileInfo) osFileInfo() os.FileInfo {\n\tfi := e.FileInfo\n\tif fi, ok := fi.(*dirJunctFileInfo); ok {\n\t\treturn fi.FileInfo\n\t}\n\treturn fi\n}\n\nfunc (e basicFileInfo) Owner() int ", "output": "{\n\treturn -1\n}"} {"input": "package egoscale\n\nimport (\n\t\"encoding/json\"\n\t\"net/url\"\n)\n\nfunc (exo *Client) PollAsyncJob(jobid string) (*QueryAsyncJobResultResponse, error) {\n\tparams := url.Values{}\n\n\tparams.Set(\"jobid\", jobid)\n\n\tresp, err := exo.Request(\"queryAsyncJobResult\", params)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar r QueryAsyncJobResultResponse\n\n\tif err := json.Unmarshal(resp, &r); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &r, nil\n}\n\n\n\nfunc (exo *Client) AsyncToVirtualMachine(resp QueryAsyncJobResultResponse) (*DeployVirtualMachineResponse, error) ", "output": "{\n\tvar r DeployVirtualMachineWrappedResponse\n\n\tif err := json.Unmarshal(resp.Jobresult, &r); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &r.Wrapped, nil\n}"} {"input": "package persist\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n\t\"os\"\n)\n\n\nfunc Load(meta Metadata, data interface{}, r io.Reader) error {\n\tvar header, version string\n\tdec := json.NewDecoder(r)\n\tif err := dec.Decode(&header); err != nil {\n\t\treturn err\n\t}\n\tif header != meta.Header {\n\t\treturn ErrBadHeader\n\t}\n\tif err := dec.Decode(&version); err != nil {\n\t\treturn err\n\t}\n\tif version != meta.Version {\n\t\treturn ErrBadVersion\n\t}\n\tif err := dec.Decode(data); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc LoadFile(meta Metadata, data interface{}, filename string) error {\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\terr = Load(meta, data, file)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc SaveFile(meta Metadata, data interface{}, filename string) error {\n\tfile, err := NewSafeFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\terr = Save(meta, data, file)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn file.Commit()\n}\n\n\nfunc SaveFileSync(meta Metadata, data interface{}, filename string) error {\n\tfile, err := NewSafeFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\terr = Save(meta, data, file)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn file.CommitSync()\n}\n\nfunc Save(meta Metadata, data interface{}, w io.Writer) error ", "output": "{\n\tb, err := json.MarshalIndent(data, \"\", \"\\t\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tenc := json.NewEncoder(w)\n\tif err := enc.Encode(meta.Header); err != nil {\n\t\treturn err\n\t}\n\tif err := enc.Encode(meta.Version); err != nil {\n\t\treturn err\n\t}\n\tif _, err = w.Write(b); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package operations\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/tompscanlan/labreserved/models\"\n)\n\n\n\n\n\n\n\nfunc NewPostItemParamsWithTimeout(timeout time.Duration) *PostItemParams {\n\tvar ()\n\treturn &PostItemParams{\n\n\t\ttimeout: timeout,\n\t}\n}\n\n\ntype PostItemParams struct {\n\n\tAdditem *models.Item\n\n\ttimeout time.Duration\n}\n\n\nfunc (o *PostItemParams) WithAdditem(Additem *models.Item) *PostItemParams {\n\to.Additem = Additem\n\treturn o\n}\n\n\nfunc (o *PostItemParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif o.Additem == nil {\n\t\to.Additem = new(models.Item)\n\t}\n\n\tif err := r.SetBodyParam(o.Additem); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc NewPostItemParams() *PostItemParams ", "output": "{\n\tvar ()\n\treturn &PostItemParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}"} {"input": "package logstash\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\n\n\n\n\n\nfunc allFilesExist(dir string, filenames []string) bool {\n\tfor _, filename := range filenames {\n\t\tpath := filepath.Join(dir, filename)\n\t\tif _, err := os.Stat(path); err != nil {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\n\n\nfunc copyAllFiles(sourceDirs []string, sourceFiles []string, dest string) (string, error) {\n\tfor _, sourceDir := range sourceDirs {\n\t\tif !allFilesExist(sourceDir, sourceFiles) {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, sourceFile := range sourceFiles {\n\t\t\tsrcFile := filepath.Join(sourceDir, sourceFile)\n\t\t\tdestFile := filepath.Join(dest, sourceFile)\n\t\t\tif err := copyFile(srcFile, destFile); err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t}\n\t\treturn sourceDir, nil\n\t}\n\treturn \"\", fmt.Errorf(\"couldn't find the wanted files (%s) in any of these directories: %s\",\n\t\tstrings.Join(sourceFiles, \", \"), strings.Join(sourceDirs, \", \"))\n}\n\n\n\n\n\n\n\nfunc copyFile(sourcePath, destPath string) error ", "output": "{\n\tr, err := os.Open(sourcePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer r.Close()\n\tw, err := os.Create(destPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = io.Copy(w, r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn w.Close()\n}"} {"input": "package cachestore\n\nimport (\n\t\"encoding/json\"\n\t\"sync\"\n)\n\n\ntype CacheStore struct {\n\tstores map[string]*KVStore\n\tmutex sync.RWMutex\n}\n\n\n\nfunc (c *CacheStore) GetStore(svcName string) *KVStore {\n\tc.mutex.RLock()\n\tkvstore := c.stores[svcName]\n\tc.mutex.RUnlock()\n\n\treturn kvstore\n}\n\n\n\nfunc (c *CacheStore) CreateStore(svcName string) *KVStore {\n\tkvstore := NewKVStore()\n\tc.mutex.Lock()\n\tc.stores[svcName] = kvstore\n\tc.mutex.Unlock()\n\n\treturn kvstore\n}\n\n\nfunc (c *CacheStore) DeleteStore(svcName string) {\n\tc.mutex.Lock()\n\tdelete(c.stores, svcName)\n\tc.mutex.Unlock()\n}\n\n\nfunc (c *CacheStore) SetCache(svcName string, key string, value interface{}) {\n\tsvcStore := c.GetStore(svcName)\n\tif svcStore == nil {\n\t\tsvcStore = c.CreateStore(svcName)\n\t}\n\n\tsvcStore.Set(key, value)\n}\n\n\n\nfunc (c *CacheStore) GetCache(svcName string, key string) interface{} {\n\tsvcStore := c.GetStore(svcName)\n\tif svcStore == nil {\n\t\treturn nil\n\t}\n\treturn svcStore.Get(key)\n}\n\n\nfunc (c *CacheStore) DeleteCache(svcName string, key string) {\n\tsvcStore := c.GetStore(svcName)\n\tif svcStore != nil {\n\t\tsvcStore.Delete(key)\n\t}\n}\n\n\n\n\n\nfunc NewCacheStore() *CacheStore {\n\treturn &CacheStore{map[string]*KVStore{}, sync.RWMutex{}}\n}\n\nfunc (c *CacheStore) MarshalJSON() ([]byte, error) ", "output": "{\n\tc.mutex.RLock()\n\tbytes, err := json.Marshal(&c.stores)\n\tc.mutex.RUnlock()\n\treturn bytes, err\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\nconst AddForm = `\n
\nURL: \n\n
\n`\nvar store = NewURLStore()\n\nfunc main() {\n\thttp.HandleFunc(\"/\", Redirect)\n\thttp.HandleFunc(\"/add\", Add)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc Redirect(w http.ResponseWriter, r *http.Request) {\n\tkey := r.URL.Path[1:]\n\turl := store.Get(key)\n\tif url == \"\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\thttp.Redirect(w, r, url, http.StatusFound)\n}\n\n\n\n\nfunc Add(w http.ResponseWriter, r *http.Request) ", "output": "{\n\turl := r.FormValue(\"url\")\n\tif url == \"\" {\n\t\tfmt.Fprint(w, AddForm)\n\t\treturn\n\t}\n\tkey := store.Put(url)\n\tfmt.Fprintf(w, \"http://localhost:8080/%s\", key)\n}"} {"input": "package api\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"mime/multipart\"\n\t\"net/http\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc TestParseParamsValidMultipart(t *testing.T) {\n\tr, err := http.NewRequest(\"POST\", \"/\", bytes.NewReader([]byte(\"blabla\")))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tbuf := bytes.NewBuffer(nil)\n\tmw := multipart.NewWriter(buf)\n\tif err := mw.SetBoundary(\"Boundary+0xAbCdEfGbOuNdArY\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tw, err := mw.CreateFormFile(\"test\", \"toto.txt\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tw.Write([]byte(\"blabla\"))\n\tmw.Close()\n\tr.Header.Set(\"Content-Type\", \"multipart/form-data; boundary=Boundary+0xAbCdEfGbOuNdArY\")\n\tr.Body = ioutil.NopCloser(buf)\n\treq := &Req{Request: r,\n\t\tResponse: nil,\n\t\tParams: new(Params),\n\t}\n\terr = req.ParseParams()\n\tif err != nil {\n\t\tt.Errorf(\"expected no error, got %s\", err)\n\t}\n}\n\nfunc TestParseParamsInvalidMultipart(t *testing.T) ", "output": "{\n\tr, err := http.NewRequest(\"POST\", \"/\", bytes.NewReader([]byte(\"blabla\")))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tr.Header.Set(\"Content-Type\", \"multipart/form-data; boundary=Boundary+0xAbCdEfGbOuNdArY\")\n\treq := &Req{Request: r,\n\t\tResponse: nil,\n\t\tParams: new(Params),\n\t}\n\terr = req.ParseParams()\n\tif !strings.HasPrefix(err.Error(), \"multipart:\") {\n\t\tt.Errorf(\"expected multipart error, got %s\", err)\n\t}\n}"} {"input": "package v2\n\nimport (\n\t\"os\"\n\n\t\"code.cloudfoundry.org/cli/cf/cmd\"\n\t\"code.cloudfoundry.org/cli/commands\"\n\t\"code.cloudfoundry.org/cli/commands/flags\"\n)\n\ntype DeleteRouteCommand struct {\n\tRequiredArgs flags.Domain `positional-args:\"yes\"`\n\tForce bool `short:\"f\" description:\"Force deletion without confirmation\"`\n\tHostname string `long:\"hostname\" short:\"n\" description:\"Hostname used to identify the HTTP route\"`\n\tPath string `long:\"path\" description:\"Path used to identify the HTTP route\"`\n\tPort int `long:\"port\" description:\"Port used to identify the TCP route\"`\n\tusage interface{} `usage:\"Delete an HTTP route:\\n CF_NAME delete-route DOMAIN [--hostname HOSTNAME] [--path PATH] [-f]\\n\\n Delete a TCP route:\\n CF_NAME delete-route DOMAIN --port PORT [-f]\\n\\nEXAMPLES:\\n CF_NAME delete-route example.com # example.com\\n CF_NAME delete-route example.com --hostname myhost # myhost.example.com\\n CF_NAME delete-route example.com --hostname myhost --path foo # myhost.example.com/foo\\n CF_NAME delete-route example.com --port 5000 # example.com:5000\"`\n\trelatedCommands interface{} `related_commands:\"delete-orphaned-routes, routes, unmap-route\"`\n}\n\nfunc (_ DeleteRouteCommand) Setup(config commands.Config, ui commands.UI) error {\n\treturn nil\n}\n\n\n\nfunc (_ DeleteRouteCommand) Execute(args []string) error ", "output": "{\n\tcmd.Main(os.Getenv(\"CF_TRACE\"), os.Args)\n\treturn nil\n}"} {"input": "package fake\n\nimport (\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n\tv1beta1 \"knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1beta1\"\n)\n\ntype FakeServingV1beta1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeServingV1beta1) Configurations(namespace string) v1beta1.ConfigurationInterface {\n\treturn &FakeConfigurations{c, namespace}\n}\n\n\n\nfunc (c *FakeServingV1beta1) Routes(namespace string) v1beta1.RouteInterface {\n\treturn &FakeRoutes{c, namespace}\n}\n\nfunc (c *FakeServingV1beta1) Services(namespace string) v1beta1.ServiceInterface {\n\treturn &FakeServices{c, namespace}\n}\n\n\n\nfunc (c *FakeServingV1beta1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeServingV1beta1) Revisions(namespace string) v1beta1.RevisionInterface ", "output": "{\n\treturn &FakeRevisions{c, namespace}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/f483/dejavu\"\n\t\"github.com/wcharczuk/go-chart\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\n\nfunc runBenchmarks() ([]float64, []float64) {\n\treturn []float64{4096, 8192, 16384, 32768, 65536}, []float64{\n\t\trunBenchmark(4096),\n\t\trunBenchmark(8192),\n\t\trunBenchmark(16384),\n\t\trunBenchmark(32768),\n\t\trunBenchmark(65536),\n\t}\n}\n\nfunc drawChart(res http.ResponseWriter, req *http.Request) {\n\n\txValues, yValues := runBenchmarks()\n\n\tgraph := chart.Chart{\n\t\tXAxis: chart.XAxis{\n\t\t\tName: \"max entrie size\",\n\t\t\tNameStyle: chart.StyleShow(),\n\t\t\tStyle: chart.StyleShow(),\n\t\t},\n\t\tYAxis: chart.YAxis{\n\t\t\tName: \"seconds to witness 1000000 entries\",\n\t\t\tNameStyle: chart.StyleShow(),\n\t\t\tStyle: chart.StyleShow(),\n\t\t},\n\t\tSeries: []chart.Series{\n\t\t\tchart.ContinuousSeries{\n\t\t\t\tStyle: chart.Style{\n\t\t\t\t\tShow: true,\n\t\t\t\t\tStrokeColor: chart.GetDefaultColor(0).WithAlpha(64),\n\t\t\t\t\tFillColor: chart.GetDefaultColor(0).WithAlpha(64),\n\t\t\t\t},\n\t\t\t\tXValues: xValues,\n\t\t\t\tYValues: yValues,\n\t\t\t},\n\t\t},\n\t}\n\n\tres.Header().Set(\"Content-Type\", \"image/png\")\n\tgraph.Render(chart.PNG, res)\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/\", drawChart)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc runBenchmark(size uint32) float64 ", "output": "{\n\n\tbegin := time.Now().UnixNano()\n\td := dejavu.NewDeterministic(size)\n\tfor i := 0; i < 1000000; i++ {\n\t\tif i%10 == 0 {\n\t\t\ts := strconv.FormatInt(int64(i-10), 10)\n\t\t\td.Witness([]byte(s))\n\t\t} else {\n\t\t\ts := strconv.FormatInt(int64(i), 10)\n\t\t\td.Witness([]byte(s))\n\t\t}\n\t}\n\tend := time.Now().UnixNano()\n\n\treturn float64(end-begin) / 1000000000.0\n}"} {"input": "package elementary\n\nimport \"unicode\"\n\n\n\nfunc secret_message(s string) string ", "output": "{\n\tvar letters []rune\n\n\tfor _, l := range s {\n\t\tif unicode.IsUpper(l) {\n\t\t\tletters = append(letters, l)\n\t\t}\n\t}\n\n\treturn string(letters)\n}"} {"input": "package slapi_test\n\nimport (\n\t\"log\"\n\n\tsoftlayer_account \"github.com/sudorandom/softlayer-go-gen/methods/softlayer_account\"\n\tgentypes \"github.com/sudorandom/softlayer-go-gen/types\"\n\tslapi \"github.com/sudorandom/softlayer-go/slapi\"\n)\n\nvar (\n\tusername = \"INSERT_USERNAME\"\n\tapiKey = \"INSERT_API_KEY\"\n)\n\n\n\n\n\nfunc ExampleClient_Call_customAPICall() {\n\tclient := slapi.Client{\n\t\tEndpoint: \"https://api.softlayer.com/rest/v3.1/\",\n\t\tAuth: slapi.BasicAuth{Username: username, APIKey: apiKey},\n\t}\n\n\treq := softlayer_account.GetObject()\n\treq.Mask = `mask[id,virtualGuests,companyName]`\n\n\ttype myCustomAccount struct {\n\t\tID int64 `json:\"id\"`\n\t\tCompanyName string `json:\"companyName\"`\n\n\t\tVirtualGuests []*gentypes.SoftLayer_Virtual_Guest `json:\"virtualGuests\"`\n\t}\n\n\tcustomAccount := &myCustomAccount{}\n\terr := client.Call(req, customAccount)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Println(\"Custom Extended:\")\n\tlog.Println(customAccount.ID)\n\tlog.Println(customAccount.CompanyName)\n\tlog.Println(customAccount.VirtualGuests)\n}\n\nfunc ExampleClient_Call_basicAPICall() ", "output": "{\n\tclient := slapi.Client{\n\t\tEndpoint: \"https://api.softlayer.com/rest/v3.1/\",\n\t\tAuth: slapi.BasicAuth{Username: username, APIKey: apiKey},\n\t}\n\n\treq := softlayer_account.GetObject()\n\treq.Mask = `mask[id,companyName]`\n\n\tbasicAccount := &gentypes.SoftLayer_Account{}\n\terr := client.Call(req, basicAccount)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Println(\"Basic:\")\n\tlog.Println(basicAccount.Id)\n\tlog.Println(basicAccount.CompanyName)\n}"} {"input": "package Plugin\n\nimport \"github.com/MPjct/GoMP/MySQLProtocol\"\n\ntype Plugin_interface interface {\n\tinit(context MySQLProtocol.Context)\n\tread_handshake(context MySQLProtocol.Context)\n\tsend_handshake(context MySQLProtocol.Context)\n\tread_auth(context MySQLProtocol.Context)\n\tsend_auth(context MySQLProtocol.Context)\n\tread_auth_result(context MySQLProtocol.Context)\n\tsend_auth_result(context MySQLProtocol.Context)\n\tread_query(context MySQLProtocol.Context)\n\tsend_query(context MySQLProtocol.Context)\n\tread_query_result(context MySQLProtocol.Context)\n\tsend_query_result(context MySQLProtocol.Context)\n\tcleanup(context MySQLProtocol.Context)\n}\n\ntype Plugin struct {\n}\n\nfunc (plugin *Plugin) init(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_handshake(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_handshake(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_auth(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_auth(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_auth_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_auth_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) read_query(context MySQLProtocol.Context) {\n\treturn\n}\n\n\n\nfunc (plugin *Plugin) read_query_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_query_result(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) cleanup(context MySQLProtocol.Context) {\n\treturn\n}\n\nfunc (plugin *Plugin) send_query(context MySQLProtocol.Context) ", "output": "{\n\treturn\n}"} {"input": "package system\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/influxdb/telegraf/plugins\"\n)\n\ntype MemStats struct {\n\tps PS\n}\n\nfunc (_ *MemStats) Description() string {\n\treturn \"Read metrics about memory usage\"\n}\n\nfunc (_ *MemStats) SampleConfig() string { return \"\" }\n\nfunc (s *MemStats) Gather(acc plugins.Accumulator) error {\n\tvm, err := s.ps.VMStat()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting virtual memory info: %s\", err)\n\t}\n\n\tvmtags := map[string]string(nil)\n\n\tacc.Add(\"total\", vm.Total, vmtags)\n\tacc.Add(\"available\", vm.Available, vmtags)\n\tacc.Add(\"used\", vm.Used, vmtags)\n\tacc.Add(\"used_prec\", vm.UsedPercent, vmtags)\n\tacc.Add(\"free\", vm.Free, vmtags)\n\tacc.Add(\"active\", vm.Active, vmtags)\n\tacc.Add(\"inactive\", vm.Inactive, vmtags)\n\tacc.Add(\"buffers\", vm.Buffers, vmtags)\n\tacc.Add(\"cached\", vm.Cached, vmtags)\n\tacc.Add(\"wired\", vm.Wired, vmtags)\n\tacc.Add(\"shared\", vm.Shared, vmtags)\n\n\treturn nil\n}\n\ntype SwapStats struct {\n\tps PS\n}\n\nfunc (_ *SwapStats) Description() string {\n\treturn \"Read metrics about swap memory usage\"\n}\n\nfunc (_ *SwapStats) SampleConfig() string { return \"\" }\n\n\n\nfunc init() {\n\tplugins.Add(\"mem\", func() plugins.Plugin {\n\t\treturn &MemStats{ps: &systemPS{}}\n\t})\n\n\tplugins.Add(\"swap\", func() plugins.Plugin {\n\t\treturn &SwapStats{ps: &systemPS{}}\n\t})\n}\n\nfunc (s *SwapStats) Gather(acc plugins.Accumulator) error ", "output": "{\n\tswap, err := s.ps.SwapStat()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting swap memory info: %s\", err)\n\t}\n\n\tswaptags := map[string]string(nil)\n\n\tacc.Add(\"total\", swap.Total, swaptags)\n\tacc.Add(\"used\", swap.Used, swaptags)\n\tacc.Add(\"free\", swap.Free, swaptags)\n\tacc.Add(\"used_perc\", swap.UsedPercent, swaptags)\n\tacc.Add(\"in\", swap.Sin, swaptags)\n\tacc.Add(\"out\", swap.Sout, swaptags)\n\n\treturn nil\n}"} {"input": "package palette\n\nimport (\n\t\"image/color\"\n\t\"testing\"\n)\n\n\n\nfunc TestParseColor(t *testing.T) {\n\tvar testParse = []struct {\n\t\tin string\n\t\tout color.RGBA\n\t}{\n\t\t{\"#fff\", color.RGBA{255, 255, 255, 255}},\n\t\t{\"#123\", color.RGBA{17, 34, 51, 255}},\n\t\t{\"#f0c0a0\", color.RGBA{240, 192, 160, 255}},\n\t\t{\"#01f203\", color.RGBA{1, 242, 3, 255}},\n\t\t{\"#01f20380\", color.RGBA{1, 242, 3, 128}},\n\t}\n\n\tfor _, tp := range testParse {\n\t\tres, err := ParseColor(tp.in)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif *res != tp.out {\n\t\t\tt.Errorf(\"%s does not match %v, got %v\", tp.in, tp.out, res)\n\t\t}\n\t}\n\n\t_, err := ParseColor(\"white\")\n\tif err == nil {\n\t\tt.Error(\"Expected error parsing \\\"white\\\"\")\n\t}\n}\n\nfunc TestConvert(t *testing.T) ", "output": "{\n\tx := col2hex(&color.RGBA{128, 192, 64, 255})\n\tif x != \"#80c040\" {\n\t\tt.Fatal(x)\n\t}\n\tx = col2hex(&color.RGBA{80, 32, 11, 255})\n\tif x != \"#50200b\" {\n\t\tt.Fatal(x)\n\t}\n}"} {"input": "package ftpclient\n\nimport (\n\t\"log\"\n\t\"os\"\n)\n\n\ntype Logger interface {\n\tLog(v ...interface{})\n\tLogf(format string, v ...interface{})\n}\n\n\n\n\ntype defaultLogger struct {\n\tlogger *log.Logger\n}\n\nfunc (l defaultLogger) Log(args ...interface{}) {\n\tl.logger.Println(args...)\n}\n\nfunc (l defaultLogger) Logf(format string, args ...interface{}) {\n\tl.logger.Printf(format, args...)\n}\n\nfunc NewDefaultLogger() Logger ", "output": "{\n\treturn &defaultLogger{\n\t\tlogger: log.New(os.Stdout, \"\", log.LstdFlags),\n\t}\n}"} {"input": "package util\n\nimport (\n\t\"github.com/spf13/viper\"\n\t\"log\"\n\t\"path/filepath\"\n)\n\n\n\n\nfunc GetTestConfig(packageName string) map[string]string ", "output": "{\n\tpath, _ := filepath.Abs(\"../\")\n\tviper.SetConfigName(\"test_config\")\n\tviper.AddConfigPath(path)\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tlog.Fatalf(\"Error : %s\", err)\n\t}\n\n\treturn viper.GetStringMapString(packageName)\n}"} {"input": "package dev\n\nimport \"fmt\"\n\n\n\ntype Configuration struct {\n\tid uint32\n\tnodes []*Node\n\tn int\n\tmgr *Manager\n\tqspec QuorumSpec\n\terrs chan CallGRPCError\n}\n\n\n\nfunc (c *Configuration) SubError() <-chan CallGRPCError {\n\treturn c.errs\n}\n\n\nfunc (c *Configuration) ID() uint32 {\n\treturn c.id\n}\n\n\n\n\n\n\n\n\nfunc (c *Configuration) Nodes() []*Node {\n\treturn c.nodes\n}\n\n\nfunc (c *Configuration) Size() int {\n\treturn c.n\n}\n\nfunc (c *Configuration) String() string {\n\treturn fmt.Sprintf(\"configuration %d\", c.id)\n}\n\nfunc (c *Configuration) tstring() string {\n\treturn fmt.Sprintf(\"config-%d\", c.id)\n}\n\n\n\nfunc Equal(a, b *Configuration) bool { return a.id == b.id }\n\n\n\n\nfunc NewTestConfiguration(q, n int) *Configuration {\n\treturn &Configuration{\n\t\tnodes: make([]*Node, n),\n\t}\n}\n\nfunc (c *Configuration) NodeIDs() []uint32 ", "output": "{\n\tids := make([]uint32, len(c.nodes))\n\tfor i, node := range c.nodes {\n\t\tids[i] = node.ID()\n\t}\n\treturn ids\n}"} {"input": "package mocks\n\nimport mock \"github.com/stretchr/testify/mock\"\n\n\ntype Allow struct {\n\tmock.Mock\n}\n\n\nfunc (_m *Allow) Emails() []string {\n\tret := _m.Called()\n\n\tvar r0 []string\n\tif rf, ok := ret.Get(0).(func() []string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]string)\n\t\t}\n\t}\n\n\treturn r0\n}\n\n\n\n\nfunc (_m *Allow) Member(email string) bool ", "output": "{\n\tret := _m.Called(email)\n\n\tvar r0 bool\n\tif rf, ok := ret.Get(0).(func(string) bool); ok {\n\t\tr0 = rf(email)\n\t} else {\n\t\tr0 = ret.Get(0).(bool)\n\t}\n\n\treturn r0\n}"} {"input": "package server\n\nimport (\n\t\"testing\"\n\n\t\"github.com/docker/docker/pkg/version\"\n\t\"github.com/docker/docker/runconfig\"\n)\n\nfunc TestAdjustCpuSharesOldApi(t *testing.T) {\n\tapiVersion := version.Version(\"1.18\")\n\thostConfig := &runconfig.HostConfig{\n\t\tCpuShares: linuxMinCpuShares - 1,\n\t}\n\tadjustCpuShares(apiVersion, hostConfig)\n\tif hostConfig.CpuShares != linuxMinCpuShares {\n\t\tt.Errorf(\"Expected CpuShares to be %d\", linuxMinCpuShares)\n\t}\n\n\thostConfig.CpuShares = linuxMaxCpuShares + 1\n\tadjustCpuShares(apiVersion, hostConfig)\n\tif hostConfig.CpuShares != linuxMaxCpuShares {\n\t\tt.Errorf(\"Expected CpuShares to be %d\", linuxMaxCpuShares)\n\t}\n\n\thostConfig.CpuShares = 0\n\tadjustCpuShares(apiVersion, hostConfig)\n\tif hostConfig.CpuShares != 0 {\n\t\tt.Error(\"Expected CpuShares to be unchanged\")\n\t}\n\n\thostConfig.CpuShares = 1024\n\tadjustCpuShares(apiVersion, hostConfig)\n\tif hostConfig.CpuShares != 1024 {\n\t\tt.Error(\"Expected CpuShares to be unchanged\")\n\t}\n}\n\n\n\nfunc TestAdjustCpuSharesNoAdjustment(t *testing.T) ", "output": "{\n\tapiVersion := version.Version(\"1.19\")\n\thostConfig := &runconfig.HostConfig{\n\t\tCpuShares: linuxMinCpuShares - 1,\n\t}\n\tadjustCpuShares(apiVersion, hostConfig)\n\tif hostConfig.CpuShares != linuxMinCpuShares-1 {\n\t\tt.Errorf(\"Expected CpuShares to be %d\", linuxMinCpuShares-1)\n\t}\n\n\thostConfig.CpuShares = linuxMaxCpuShares + 1\n\tadjustCpuShares(apiVersion, hostConfig)\n\tif hostConfig.CpuShares != linuxMaxCpuShares+1 {\n\t\tt.Errorf(\"Expected CpuShares to be %d\", linuxMaxCpuShares+1)\n\t}\n\n\thostConfig.CpuShares = 0\n\tadjustCpuShares(apiVersion, hostConfig)\n\tif hostConfig.CpuShares != 0 {\n\t\tt.Error(\"Expected CpuShares to be unchanged\")\n\t}\n\n\thostConfig.CpuShares = 1024\n\tadjustCpuShares(apiVersion, hostConfig)\n\tif hostConfig.CpuShares != 1024 {\n\t\tt.Error(\"Expected CpuShares to be unchanged\")\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/julienschmidt/httprouter\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestHealthzHandler(t *testing.T) {\n\trouter := httprouter.New()\n\trouter.GET(\"/healthz\", HealthzHandler)\n\n\tsrv := httptest.NewServer(router)\n\tdefer srv.Close()\n\n\tresponse := doHTTPRequest(\"GET\", fmt.Sprintf(\"%s/healthz\", srv.URL))\n\tassert.Exactly(t, http.StatusOK, response.StatusCode)\n}\n\nfunc doHTTPRequest(method, url string) *http.Response ", "output": "{\n\tclient := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tDisableKeepAlives: true,\n\t\t},\n\t}\n\n\trequest, _ := http.NewRequest(method, url, nil)\n\tresponse, _ := client.Do(request)\n\treturn response\n}"} {"input": "package godot\n\nimport (\n\t\"github.com/shadowapex/godot-go/gdnative\"\n)\n\n\n\n\nfunc newStyleBoxEmptyFromPointer(ptr gdnative.Pointer) StyleBoxEmpty {\n\towner := gdnative.NewObjectFromPointer(ptr)\n\tobj := StyleBoxEmpty{}\n\tobj.SetBaseObject(owner)\n\n\treturn obj\n}\n\n\ntype StyleBoxEmpty struct {\n\tStyleBox\n\towner gdnative.Object\n}\n\n\n\n\n\ntype StyleBoxEmptyImplementer interface {\n\tStyleBoxImplementer\n}\n\nfunc (o *StyleBoxEmpty) BaseClass() string ", "output": "{\n\treturn \"StyleBoxEmpty\"\n}"} {"input": "package testutil\n\nimport (\n\t\"testing\"\n\n\tci \"gx/ipfs/QmP1DfoUjiWH2ZBo1PBH6FupdBucbDepx3HpWmEY6JMUpY/go-libp2p-crypto\"\n\tma \"gx/ipfs/QmcyqRMCAXVtYPS4DiBrA7sezL9rRGfW8Ctx7cywL4TXJj/go-multiaddr\"\n\tpeer \"gx/ipfs/QmdS9KpbDyPrieswibZhkod1oXqRwZJrUPzxCofAMWpFGq/go-libp2p-peer\"\n)\n\ntype Identity interface {\n\tAddress() ma.Multiaddr\n\tID() peer.ID\n\tPrivateKey() ci.PrivKey\n\tPublicKey() ci.PubKey\n}\n\n\n\nfunc RandIdentity() (Identity, error) {\n\tp, err := RandPeerNetParams()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &identity{*p}, nil\n}\n\n\n\n\ntype identity struct {\n\tPeerNetParams\n}\n\nfunc (p *identity) ID() peer.ID {\n\treturn p.PeerNetParams.ID\n}\n\nfunc (p *identity) Address() ma.Multiaddr {\n\treturn p.Addr\n}\n\nfunc (p *identity) PrivateKey() ci.PrivKey {\n\treturn p.PrivKey\n}\n\nfunc (p *identity) PublicKey() ci.PubKey {\n\treturn p.PubKey\n}\n\nfunc RandIdentityOrFatal(t *testing.T) Identity ", "output": "{\n\tp, err := RandPeerNetParams()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn &identity{*p}\n}"} {"input": "package nerd\n\nimport (\n\t\"context\"\n\t\"syscall\"\n\n\t\"code.cloudfoundry.org/lager\"\n\t\"github.com/containerd/containerd\"\n)\n\ntype BackingProcess struct {\n\tlog lager.Logger\n\tcontext context.Context\n\tcontainerdProcess containerd.Process\n}\n\nfunc NewBackingProcess(log lager.Logger, p containerd.Process, ctx context.Context) BackingProcess {\n\treturn BackingProcess{\n\t\tlog: log,\n\t\tcontext: ctx,\n\t\tcontainerdProcess: p,\n\t}\n}\n\nfunc (p BackingProcess) ID() string {\n\treturn p.containerdProcess.ID()\n}\n\n\n\nfunc (p BackingProcess) Signal(signal syscall.Signal) error {\n\treturn p.containerdProcess.Kill(p.context, signal)\n}\n\nfunc (p BackingProcess) Delete() error {\n\t_, err := p.containerdProcess.Delete(p.context)\n\treturn err\n}\n\nfunc (p BackingProcess) Wait() (int, error) ", "output": "{\n\texitCh, err := p.containerdProcess.Wait(p.context)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\texitStatus := <-exitCh\n\tif exitStatus.Error() != nil {\n\t\treturn 0, exitStatus.Error()\n\t}\n\n\treturn int(exitStatus.ExitCode()), nil\n}"} {"input": "package process\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"log\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\tflushThreshold = 8192\n)\n\n\ntype FileLogger struct {\n\tsync.RWMutex\n\tfilename string\n\tbuffer *bytes.Buffer\n\tencoder *json.Encoder\n}\n\n\nfunc NewLogger(filename string) (*FileLogger, error) {\n\tfl := &FileLogger{filename: filename}\n\tfl.buffer = &bytes.Buffer{}\n\tfl.encoder = json.NewEncoder(fl.buffer)\n\n\tfile, err := os.Create(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer closeFile(file)\n\n\treturn fl, nil\n}\n\n\nfunc (fl *FileLogger) Flush() {\n\tfl.Lock()\n\tfl.doFlush()\n\tfl.Unlock()\n}\n\n\nfunc (fl *FileLogger) OnStdout(line string, time time.Time) {\n\tfl.writeLine(&LogMessage{StdoutKind, time, line})\n}\n\n\nfunc (fl *FileLogger) OnStderr(line string, time time.Time) {\n\tfl.writeLine(&LogMessage{StderrKind, time, line})\n}\n\n\nfunc (fl *FileLogger) Close() {\n\tfl.Flush()\n}\n\nfunc (fl *FileLogger) writeLine(message *LogMessage) {\n\tfl.Lock()\n\terr := fl.encoder.Encode(message)\n\tif err != nil {\n\t\tlog.Printf(\"Error appears on writing data to logs buffer. %s \\n\", err.Error())\n\t}\n\tif flushThreshold < fl.buffer.Len() {\n\t\tfl.doFlush()\n\t}\n\tfl.Unlock()\n}\n\n\n\nfunc closeFile(file *os.File) {\n\tif err := file.Close(); err != nil {\n\t\tlog.Printf(\"Can't close file %s. Error: %s\", file.Name(), err)\n\t}\n}\n\nfunc (fl *FileLogger) doFlush() ", "output": "{\n\tif fl.buffer.Len() > 0 {\n\t\tf, err := os.OpenFile(fl.filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Couldn't open file '%s' for flushing the buffer. %s \\n\", fl.filename, err.Error())\n\t\t} else {\n\t\t\tdefer closeFile(f)\n\t\t\t_, err = fl.buffer.WriteTo(f)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error appears on flushing data to file '%s'. %s \\n\", fl.filename, err.Error())\n\t\t\t}\n\t\t}\n\t}\n}"} {"input": "package test\n\nimport (\n\t\"github.com/stellar/go/support/db\"\n\t\"github.com/stellar/horizon/ledger\"\n)\n\n\nfunc (t *T) CoreRepo() *db.Repo {\n\treturn &db.Repo{\n\t\tDB: t.CoreDB,\n\t\tCtx: t.Ctx,\n\t}\n}\n\n\n\n\n\n\nfunc (t *T) HorizonRepo() *db.Repo {\n\treturn &db.Repo{\n\t\tDB: t.HorizonDB,\n\t\tCtx: t.Ctx,\n\t}\n}\n\n\nfunc (t *T) Scenario(name string) *T {\n\tLoadScenario(name)\n\tt.UpdateLedgerState()\n\treturn t\n}\n\n\nfunc (t *T) ScenarioWithoutHorizon(name string) *T {\n\tLoadScenarioWithoutHorizon(name)\n\tt.UpdateLedgerState()\n\treturn t\n}\n\n\nfunc (t *T) UpdateLedgerState() {\n\tvar next ledger.State\n\n\terr := t.CoreRepo().GetRaw(&next, `\n\t\tSELECT\n\t\t\tCOALESCE(MIN(ledgerseq), 0) as core_elder,\n\t\t\tCOALESCE(MAX(ledgerseq), 0) as core_latest\n\t\tFROM ledgerheaders\n\t`)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = t.HorizonRepo().GetRaw(&next, `\n\t\t\tSELECT\n\t\t\t\tCOALESCE(MIN(sequence), 0) as history_elder,\n\t\t\t\tCOALESCE(MAX(sequence), 0) as history_latest\n\t\t\tFROM history_ledgers\n\t\t`)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tledger.SetState(next)\n\treturn\n}\n\nfunc (t *T) Finish() ", "output": "{\n\tRestoreLogger()\n\tledger.SetState(ledger.State{})\n\n\tif t.LogBuffer.Len() > 0 {\n\t\tt.T.Log(\"\\n\" + t.LogBuffer.String())\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n)\n\n\n\nfunc runTestsCommand() ", "output": "{\n\tgoTest := []string{\"go\", \"test\"}\n\tgoTest = append(goTest, flags.Args()[1:]...)\n\trunCmd(goTest, func(c *exec.Cmd) {\n\t\tc.Env = appendToPathList(os.Environ(), \"GOPATH\", appengineDir)\n\t})\n}"} {"input": "package main\n\ntype Human struct {\n\tname string\n\tage int\n\tphone string\n}\n\ntype Student struct {\n\tHuman\n\tschool string\n\tloan float32\n}\n\ntype Employee struct {\n\tHuman\n\tcompany string\n\tmoney float32\n}\n\n\ntype Men interface {\n\tSayHi()\n\tSing(lyrics string)\n\tGuzzle(beerStein string)\n}\n\ntype YoungChap interface {\n\tSayHi()\n\tSing(lyrics string)\n\tBorrowMoney(amount float32)\n}\n\ntype ElderlyGent interface {\n\tSayHi()\n\tSing(song string)\n\tSpendSalary(amount float32)\n}\n\nfunc (h *Human) SayHi() {\n\tfmt.Printf(\"Hi, I am %s you can call me on %s\\n\", h.name, h.phone)\n}\n\nfunc (h *Human) Sing(lyrics string) {\n\tfmt.Println(\"La la, la la la, la la la la...\", lyrics)\n}\n\nfunc (h *Human) Guzzle(beerStein string) {\n\tfmt.Println(\"Guzzle Guzzle Guzzle...\", beerStein)\n}\n\n\nfunc (e *Employee) SayHi() {\n\tfmt.Printf(\"Hi, I am %s, I work at %s. Call me on %s\\n\", e.name, e.company, e.phone)\n}\n\n\n\nfunc (e *Employee) SpendSalary(amount float32) {\n\te.money -= e.amount\n}\n\nfunc (s *Student) BorrowMoney(amount float32) ", "output": "{\n\ts.loan += amount\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CopyVolumeGroupBackupRequest struct {\n\n\tVolumeGroupBackupId *string `mandatory:\"true\" contributesTo:\"path\" name:\"volumeGroupBackupId\"`\n\n\tCopyVolumeGroupBackupDetails `contributesTo:\"body\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CopyVolumeGroupBackupRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request CopyVolumeGroupBackupRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\n\n\n\nfunc (request CopyVolumeGroupBackupRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CopyVolumeGroupBackupResponse struct {\n\n\tRawResponse *http.Response\n\n\tVolumeGroupBackup `presentIn:\"body\"`\n\n\tEtag *string `presentIn:\"header\" name:\"etag\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CopyVolumeGroupBackupResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response CopyVolumeGroupBackupResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request CopyVolumeGroupBackupRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\n}"} {"input": "package fakes\n\nimport (\n\t\"os/exec\"\n\t\"sync\"\n\n\t\"github.com/cloudfoundry-incubator/genclient\"\n)\n\ntype CommandRunner struct {\n\tRunStub func(cmd *exec.Cmd) error\n\trunMutex sync.RWMutex\n\trunArgsForCall []struct {\n\t\tcmd *exec.Cmd\n\t}\n\trunReturns struct {\n\t\tresult1 error\n\t}\n}\n\nfunc (fake *CommandRunner) Run(cmd *exec.Cmd) error {\n\tfake.runMutex.Lock()\n\tfake.runArgsForCall = append(fake.runArgsForCall, struct {\n\t\tcmd *exec.Cmd\n\t}{cmd})\n\tfake.runMutex.Unlock()\n\tif fake.RunStub != nil {\n\t\treturn fake.RunStub(cmd)\n\t} else {\n\t\treturn fake.runReturns.result1\n\t}\n}\n\n\n\nfunc (fake *CommandRunner) RunArgsForCall(i int) *exec.Cmd {\n\tfake.runMutex.RLock()\n\tdefer fake.runMutex.RUnlock()\n\treturn fake.runArgsForCall[i].cmd\n}\n\nfunc (fake *CommandRunner) RunReturns(result1 error) {\n\tfake.RunStub = nil\n\tfake.runReturns = struct {\n\t\tresult1 error\n\t}{result1}\n}\n\nvar _ genclient.CommandRunnerInterface = new(CommandRunner)\n\nfunc (fake *CommandRunner) RunCallCount() int ", "output": "{\n\tfake.runMutex.RLock()\n\tdefer fake.runMutex.RUnlock()\n\treturn len(fake.runArgsForCall)\n}"} {"input": "package secretbox\n\nimport (\n\t\"crypto/rand\"\n\t\"fmt\"\n\n\t\"golang.org/x/crypto/nacl/secretbox\"\n\n\t\"k8s.io/apiserver/pkg/storage/value\"\n)\n\n\n\n\ntype secretboxTransformer struct {\n\tkey [32]byte\n}\n\nconst nonceSize = 24\n\n\n\n\n\nfunc (t *secretboxTransformer) TransformFromStorage(data []byte, context value.Context) ([]byte, bool, error) {\n\tif len(data) < (secretbox.Overhead + nonceSize) {\n\t\treturn nil, false, fmt.Errorf(\"the stored data was shorter than the required size\")\n\t}\n\tvar nonce [nonceSize]byte\n\tcopy(nonce[:], data[:nonceSize])\n\tdata = data[nonceSize:]\n\tout := make([]byte, 0, len(data)-secretbox.Overhead)\n\tresult, ok := secretbox.Open(out, data, &nonce, &t.key)\n\tif !ok {\n\t\treturn nil, false, fmt.Errorf(\"output array was not large enough for encryption\")\n\t}\n\treturn result, false, nil\n}\n\nfunc (t *secretboxTransformer) TransformToStorage(data []byte, context value.Context) ([]byte, error) {\n\tvar nonce [nonceSize]byte\n\tn, err := rand.Read(nonce[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif n != nonceSize {\n\t\treturn nil, fmt.Errorf(\"unable to read sufficient random bytes\")\n\t}\n\treturn secretbox.Seal(nonce[:], data, &nonce, &t.key), nil\n}\n\nfunc NewSecretboxTransformer(key [32]byte) value.Transformer ", "output": "{\n\treturn &secretboxTransformer{key: key}\n}"} {"input": "package crisp\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\n\n\n\n\ntype Addr struct {\n\tNetwork string\n\tNetAddr string\n}\n\n\n\n\n\n\n\nfunc (a *Addr) String() string {\n\tif a.Network == \"@\" {\n\t\treturn fmt.Sprintf(\"@%s\", a.NetAddr)\n\t}\n\treturn fmt.Sprintf(\"%s\", a.NetAddr)\n}\n\nfunc ParseAddr(s string) *Addr ", "output": "{\n\tif strings.HasPrefix(s, \"@\") {\n\t\treturn &Addr{Network: \"unix\", NetAddr: s[1:]}\n\t}\n\treturn &Addr{Network: \"tcp\", NetAddr: s}\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSAmazonMQBroker_MaintenanceWindow struct {\n\n\tDayOfWeek string `json:\"DayOfWeek,omitempty\"`\n\n\tTimeOfDay string `json:\"TimeOfDay,omitempty\"`\n\n\tTimeZone string `json:\"TimeZone,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) AWSCloudFormationType() string {\n\treturn \"AWS::AmazonMQ::Broker.MaintenanceWindow\"\n}\n\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\n\n\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) Metadata() map[string]interface{} ", "output": "{\n\treturn r._metadata\n}"} {"input": "package command\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"github.com/jpartogi/dosboxgo/console\"\n\t\"github.com/jpartogi/dosboxgo/filesystem\"\n\t\"os\"\n\t\"strings\"\n)\n\ntype Processor struct {\n\tInvoker Invoker\n\tDrive filesystem.Drive\n\tOutputter console.Outputter\n}\n\nfunc NewProc(Invoker Invoker, Drive filesystem.Drive, Outputter console.Outputter) Processor {\n\treturn Processor{Invoker, Drive, Outputter}\n}\n\n\n\nfunc (p *Processor) ProcessInput() ", "output": "{\n\tp.Outputter.Println(\"DOSBox, Scrum.org, Professional Scrum Developer Training\")\n\tp.Outputter.Println(\"Copyright (c) Joshua Partogi. All rights reserved.\")\n\n\tline := \"\"\n\treader := bufio.NewReader(os.Stdin)\n\n\tfor strings.ToLower(line) != \"exit\" {\n\t\tp.Outputter.NewLine()\n\t\tfmt.Print(\"C:\\\\>\")\n\n\t\ttext, _ := reader.ReadString('\\n')\n\t\tline = strings.TrimSpace(text)\n\n\t\tp.Invoker.ExecuteCommand(line)\n\t}\n}"} {"input": "package stream_test\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/synapse-garden/sg-proto/store\"\n\t\"github.com/synapse-garden/sg-proto/stream\"\n\tsgt \"github.com/synapse-garden/sg-proto/testing\"\n\n\t\"github.com/boltdb/bolt\"\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc Test(t *testing.T) { TestingT(t) }\n\ntype StreamSuite struct {\n\tdb *bolt.DB\n\ttmpDir string\n}\n\nvar _ = Suite(&StreamSuite{})\n\n\n\nfunc (s *StreamSuite) TearDownTest(c *C) {\n\tif db := s.db; db != nil {\n\t\tc.Assert(sgt.CleanupDB(db), IsNil)\n\t\tc.Assert(os.Remove(s.tmpDir), IsNil)\n\t}\n}\n\nfunc (s *StreamSuite) SetUpTest(c *C) ", "output": "{\n\tdb, tmpDir, err := sgt.TempDB(\"sg-stream-test\")\n\tc.Assert(err, IsNil)\n\tc.Assert(db.Update(store.Wrap(\n\t\tstore.Migrate(store.VerCurrent),\n\t\tstore.SetupBuckets(stream.StreamBucket),\n\t)), IsNil)\n\ts.db, s.tmpDir = db, tmpDir\n}"} {"input": "package iso20022\n\n\ntype Header12 struct {\n\n\tDownloadTransfer *TrueFalseIndicator `xml:\"DwnldTrf\"`\n\n\tFormatVersion *Max6Text `xml:\"FrmtVrsn\"`\n\n\tExchangeIdentification *Max3NumericText `xml:\"XchgId\"`\n\n\tCreationDateTime *ISODateTime `xml:\"CreDtTm\"`\n\n\tInitiatingParty *GenericIdentification53 `xml:\"InitgPty\"`\n\n\tRecipientParty *GenericIdentification53 `xml:\"RcptPty,omitempty\"`\n}\n\nfunc (h *Header12) SetDownloadTransfer(value string) {\n\th.DownloadTransfer = (*TrueFalseIndicator)(&value)\n}\n\n\n\nfunc (h *Header12) SetExchangeIdentification(value string) {\n\th.ExchangeIdentification = (*Max3NumericText)(&value)\n}\n\nfunc (h *Header12) SetCreationDateTime(value string) {\n\th.CreationDateTime = (*ISODateTime)(&value)\n}\n\nfunc (h *Header12) AddInitiatingParty() *GenericIdentification53 {\n\th.InitiatingParty = new(GenericIdentification53)\n\treturn h.InitiatingParty\n}\n\nfunc (h *Header12) AddRecipientParty() *GenericIdentification53 {\n\th.RecipientParty = new(GenericIdentification53)\n\treturn h.RecipientParty\n}\n\nfunc (h *Header12) SetFormatVersion(value string) ", "output": "{\n\th.FormatVersion = (*Max6Text)(&value)\n}"} {"input": "package encrypt\n\nimport (\n\t\"io/ioutil\"\n)\n\n\ntype KeyProvider interface {\n\tGet(params map[string]interface{}) (string, error)\n}\n\n\ntype FileKeyProvider struct {\n\tpath string\n}\n\n\n\n\n\n\nfunc (f *FileKeyProvider) Get(params map[string]interface{}) (string, error) {\n\tb, err := ioutil.ReadFile(f.path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(b), nil\n}\n\nfunc NewFileKeyProvider(path string) KeyProvider ", "output": "{\n\treturn &FileKeyProvider{\n\t\tpath: path,\n\t}\n}"} {"input": "package apigateway\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype RequestParameterValidation struct {\n\n\tName *string `mandatory:\"true\" json:\"name\"`\n}\n\n\n\nfunc (m RequestParameterValidation) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package gull\n\nimport \"fmt\"\n\ntype ConfigLeaf struct {\n\tPath string\n\tValue string\n}\n\ntype ConfigLeaves struct {\n\tEntries []ConfigLeaf\n}\n\nfunc NewConfigLeaves() (*ConfigLeaves, error) {\n\treturn &ConfigLeaves{\n\t\tEntries: []ConfigLeaf{},\n\t}, nil\n}\n\n\n\nfunc (c *ConfigLeaves) GetValue(path string) (string, error) ", "output": "{\n\tfor _, leaf := range c.Entries {\n\t\tif leaf.Path == path {\n\t\t\treturn leaf.Value, nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"No value found at path [%v]\", path)\n}"} {"input": "package email\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"errors\"\n\t\"io\"\n\t\"net/textproto\"\n)\n\n\n\n\nfunc (m *Message) HasDeliveryStatusMessage() bool {\n\tcontentType, _, err := m.Header.ContentType()\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn contentType == \"message/delivery-status\" && m.SubMessage != nil\n}\n\n\n\n\n\n\n\nfunc (m *Message) DeliveryStatusRecipientDNS() ([]Header, error) {\n\trecipientDNS := make([]Header, 0, 1)\n\tif !m.HasDeliveryStatusMessage() {\n\t\treturn recipientDNS, errors.New(\"Message does not have media content of type message/delivery-status\")\n\t}\n\tvar err error\n\tvar recipientHeaders textproto.MIMEHeader\n\ttp := textproto.NewReader(bufio.NewReader(bytes.NewReader(m.SubMessage.Body)))\n\tfor err != io.EOF {\n\t\trecipientHeaders, err = tp.ReadMIMEHeader()\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn nil, err\n\t\t}\n\t\trecipientDNS = append(recipientDNS, Header(recipientHeaders))\n\t}\n\treturn recipientDNS, nil\n}\n\nfunc (m *Message) DeliveryStatusMessageDNS() (Header, error) ", "output": "{\n\tif !m.HasDeliveryStatusMessage() {\n\t\treturn Header{}, errors.New(\"Message does not have media content of type message/delivery-status\")\n\t}\n\treturn m.SubMessage.Header, nil\n}"} {"input": "package messages\n\ntype LocVelDistTraveledMessage struct {\n\tX float64\n\tY float64\n\tZ float64\n\tXv float64\n\tYv float64\n\tZv float64\n}\n\n\n\nfunc (m LocVelDistTraveledMessage) Type() uint {\n\treturn LocVelDistTraveledMessageType\n}\n\nfunc NewLocVelDistTraveledMessage(data []float32) LocVelDistTraveledMessage ", "output": "{\n\treturn LocVelDistTraveledMessage{\n\t\tY: float64(data[0]),\n\t\tZ: -float64(data[1]),\n\t\tX: -float64(data[2]),\n\t\tYv: float64(data[3]),\n\t\tZv: -float64(data[4]),\n\t\tXv: -float64(data[5]),\n\t}\n}"} {"input": "package lints\n\n\n\n\n\nimport (\n\t\"github.com/zmap/zcrypto/x509\"\n\t\"github.com/zmap/zlint/util\"\n)\n\ntype CertPolicyRequiresPersonalName struct{}\n\nfunc (l *CertPolicyRequiresPersonalName) Initialize() error {\n\treturn nil\n}\n\n\n\nfunc (l *CertPolicyRequiresPersonalName) Execute(cert *x509.Certificate) *LintResult {\n\tvar out LintResult\n\tif util.TypeInName(&cert.Subject, util.OrganizationNameOID) || (util.TypeInName(&cert.Subject, util.GivenNameOID) && util.TypeInName(&cert.Subject, util.SurnameOID)) {\n\t\tout.Status = Pass\n\t} else {\n\t\tout.Status = Error\n\t}\n\treturn &out\n}\n\nfunc init() {\n\tRegisterLint(&Lint{\n\t\tName: \"e_cab_iv_requires_personal_name\",\n\t\tDescription: \"If certificate policy 2.23.140.1.2.3 is included, either organizationName or givenName and surname MUST be included in subject\",\n\t\tCitation: \"BRs: 7.1.6.1\",\n\t\tSource: CABFBaselineRequirements,\n\t\tEffectiveDate: util.CABV131Date,\n\t\tLint: &CertPolicyRequiresPersonalName{},\n\t})\n}\n\nfunc (l *CertPolicyRequiresPersonalName) CheckApplies(cert *x509.Certificate) bool ", "output": "{\n\treturn util.SliceContainsOID(cert.PolicyIdentifiers, util.BRIndividualValidatedOID) && !util.IsCACert(cert)\n}"} {"input": "package world\n\nimport (\n\t\"encoding/gob\"\n\t\"math/big\"\n\t\"reflect\"\n\t\"time\"\n)\n\nvar registeredIdentifierObject = make(map[string]reflect.Type)\nvar registeredObjectIdentifier = make(map[reflect.Type]string)\n\n\n\nfunc getObjectTypeIdentifier(obj ObjectLike) string {\n\tt := reflect.TypeOf(obj)\n\tif t.Kind() == reflect.Ptr {\n\t\tt = t.Elem()\n\t}\n\tidentifier := registeredObjectIdentifier[t]\n\tif identifier == \"\" {\n\t\tpanic(\"unregistered object type: \" + t.Name())\n\t}\n\treturn identifier\n}\n\nfunc getObjectByIdentifier(identifier string) ObjectLike {\n\tt := registeredIdentifierObject[identifier]\n\tif t == nil {\n\t\tpanic(\"unregistered object identifier: \" + identifier)\n\t}\n\treturn reflect.New(t).Interface().(ObjectLike)\n}\n\nfunc init() {\n\tgob.Register(map[string]interface{}{})\n\tgob.Register([]interface{}{})\n\tgob.Register(time.Time{})\n\tgob.Register(&big.Int{})\n}\n\nfunc Register(identifier string, obj ObjectLike) ", "output": "{\n\tif identifier == \"\" {\n\t\tpanic(\"attempt to register an empty identifier\")\n\t}\n\tif obj == nil {\n\t\tpanic(\"attempt to register a nil object type\")\n\t}\n\n\tt := reflect.TypeOf(obj)\n\tif t.Kind() == reflect.Ptr {\n\t\tt = t.Elem()\n\t}\n\n\tif _, ok := registeredIdentifierObject[identifier]; ok {\n\t\tpanic(\"duplicate registration for object identifier \" + identifier)\n\t}\n\tif _, ok := registeredObjectIdentifier[t]; ok {\n\t\tpanic(\"duplicate registration for object type \" + t.Name())\n\t}\n\tregisteredObjectIdentifier[t] = identifier\n\tregisteredIdentifierObject[identifier] = t\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestFind(t *testing.T) ", "output": "{\n\tfor _, tc := range []struct{\n\t\tinput []int\n\t\texpected int\n\t}{\n\t\t{[]int{6,7,8,9,1,2,3,4}, 5},\n\t\t{[]int{-1, -3, 1}, 0},\n\t}{\n\t\tactual := Find(tc.input)\n\t\tif actual != tc.expected {\n\t\t\tt.Errorf(\"expected %d, got %d\", tc.expected, actual)\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n\n\nfunc swap(x *int, y *int) {\n\tvar temp int\n\ttemp = *x;\n\t*x = *y\n\t*y = temp\n}\n\nfunc getSequence() func() int {\n\tvar i int = 0;\n\treturn func() int {\n\t\ti++;\n\t\treturn i\n\t}\n}\n\ntype Circle struct {\n\tx, y, radius float64\n}\n\nfunc(circle Circle) area() float64 {\n\treturn math.Pi * circle.radius * circle.radius \n}\n\nfunc main() {\n\tvar a, b int = 2, 3;\n\tfmt.Printf(\"max value is %d\\n\", max(a,b));\n\n\tfmt.Printf(\"a = %d, b = %d\\n\", a, b);\n\tswap(&a, &b);\n\tfmt.Printf(\"a = %d, b = %d\\n\", a, b);\n\n\txxx := swap\n\txxx(&a, &b)\n\tfmt.Printf(\"a = %d, b = %d\\n\", a, b);\n\n\tnumber := getSequence()\n\tfmt.Printf(\"number is %d\\n\", number())\n\tfmt.Printf(\"number is %d\\n\", number())\n\tfmt.Printf(\"number is %d\\n\", number())\n\tfmt.Printf(\"number is %d\\n\", number())\n\tnumber1 := getSequence()\n\tfmt.Printf(\"number1 is %d\\n\", number1())\n\tfmt.Printf(\"number1 is %d\\n\", number1())\n\tfmt.Printf(\"number1 is %d\\n\", number1())\n\tfmt.Printf(\"number1 is %d\\n\", number1())\n\n\tcircle := Circle{x:0, y:0, radius:5}\n\tfmt.Printf(\"Circle area: %f\\n\", circle.area())\n\n}\n\nfunc max(x int, y int) int ", "output": "{\n\tif (x > y) {\n\t\treturn x\n\t} else {\n\t\treturn y\n\t}\n}"} {"input": "package restic\n\nimport \"syscall\"\n\nfunc (node Node) restoreSymlinkTimestamps(path string, utimes [2]syscall.Timespec) error {\n\treturn nil\n}\n\n\nfunc (s statUnix) mtim() syscall.Timespec { return s.Mtim }\nfunc (s statUnix) ctim() syscall.Timespec { return s.Ctim }\n\nfunc (s statUnix) atim() syscall.Timespec ", "output": "{ return s.Atim }"} {"input": "package libxml2_test\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/lestrrat/go-libxml2\"\n\t\"github.com/lestrrat/go-libxml2/parser\"\n\t\"github.com/lestrrat/go-libxml2/types\"\n\t\"github.com/lestrrat/go-libxml2/xpath\"\n)\n\nfunc ExampleXML() {\n\tres, err := http.Get(\"http://blog.golang.org/feed.atom\")\n\tif err != nil {\n\t\tpanic(\"failed to get blog.golang.org: \" + err.Error())\n\t}\n\n\tp := parser.New()\n\tdoc, err := p.ParseReader(res.Body)\n\tdefer res.Body.Close()\n\n\tif err != nil {\n\t\tpanic(\"failed to parse XML: \" + err.Error())\n\t}\n\tdefer doc.Free()\n\n\tdoc.Walk(func(n types.Node) error {\n\t\tlog.Printf(n.NodeName())\n\t\treturn nil\n\t})\n\n\troot, err := doc.DocumentElement()\n\tif err != nil {\n\t\tlog.Printf(\"Failed to fetch document element: %s\", err)\n\t\treturn\n\t}\n\n\tctx, err := xpath.NewContext(root)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to create xpath context: %s\", err)\n\t\treturn\n\t}\n\tdefer ctx.Free()\n\n\tctx.RegisterNS(\"atom\", \"http://www.w3.org/2005/Atom\")\n\ttitle := xpath.String(ctx.Find(\"/atom:feed/atom:title/text()\"))\n\tlog.Printf(\"feed title = %s\", title)\n}\n\n\n\nfunc ExampleHTML() ", "output": "{\n\tres, err := http.Get(\"http://golang.org\")\n\tif err != nil {\n\t\tpanic(\"failed to get golang.org: \" + err.Error())\n\t}\n\n\tdoc, err := libxml2.ParseHTMLReader(res.Body)\n\tif err != nil {\n\t\tpanic(\"failed to parse HTML: \" + err.Error())\n\t}\n\tdefer doc.Free()\n\n\tdoc.Walk(func(n types.Node) error {\n\t\tlog.Printf(n.NodeName())\n\t\treturn nil\n\t})\n\n\tnodes := xpath.NodeList(doc.Find(`//div[@id=\"menu\"]/a`))\n\tfor i := 0; i < len(nodes); i++ {\n\t\tlog.Printf(\"Found node: %s\", nodes[i].NodeName())\n\t}\n}"} {"input": "package checkers\n\nimport (\n\t\"errors\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com/jkomoros/boardgame\"\n\t\"github.com/jkomoros/boardgame/base\"\n\t\"github.com/jkomoros/boardgame/moves\"\n)\n\n\n\n\ntype gameDelegate struct {\n\tbase.GameDelegate\n}\n\nvar memoizedDelegateName string\n\nfunc (g *gameDelegate) Name() string {\n\n\n\tif memoizedDelegateName == \"\" {\n\t\tpkgPath := reflect.ValueOf(g).Elem().Type().PkgPath()\n\t\tpathPieces := strings.Split(pkgPath, \"/\")\n\t\tmemoizedDelegateName = pathPieces[len(pathPieces)-1]\n\t}\n\treturn memoizedDelegateName\n}\n\nfunc (g *gameDelegate) ConfigureMoves() []boardgame.MoveConfig {\n\n\tauto := moves.NewAutoConfigurer(g)\n\n\treturn moves.Combine(\n\n\t\tmoves.Add(\n\t\t\tauto.MustConfig(new(moves.NoOp),\n\t\t\t\tmoves.WithMoveName(\"Example No Op Move\"),\n\t\t\t\tmoves.WithHelpText(\"This move is an example that is always legal and does nothing. It exists to show how to return moves and make sure 'go test' works from the beginning, but you should remove it.\"),\n\t\t\t),\n\t\t),\n\t)\n\n}\n\n\n\nfunc (g *gameDelegate) PlayerStateConstructor(index boardgame.PlayerIndex) boardgame.ConfigurableSubState {\n\treturn new(playerState)\n}\n\nfunc (g *gameDelegate) DistributeComponentToStarterStack(state boardgame.ImmutableState, c boardgame.Component) (boardgame.ImmutableStack, error) {\n\n\treturn nil, errors.New(\"Not yet implemented\")\n\n}\n\n\n\nfunc NewDelegate() boardgame.GameDelegate {\n\treturn &gameDelegate{}\n}\n\nfunc (g *gameDelegate) GameStateConstructor() boardgame.ConfigurableSubState ", "output": "{\n\treturn new(gameState)\n}"} {"input": "package gnocchi\n\nimport (\n\t\"github.com/gophercloud/gophercloud\"\n)\n\n\n\n\nfunc NewGnocchiV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) {\n\tsc, err := initClientOpts(client, eo, \"metric\")\n\tsc.ResourceBase = sc.Endpoint + \"v1/\"\n\treturn sc, err\n}\n\nfunc initClientOpts(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts, clientType string) (*gophercloud.ServiceClient, error) ", "output": "{\n\tsc := new(gophercloud.ServiceClient)\n\teo.ApplyDefaults(clientType)\n\turl, err := client.EndpointLocator(eo)\n\tif err != nil {\n\t\treturn sc, err\n\t}\n\tsc.ProviderClient = client\n\tsc.Endpoint = url\n\tsc.Type = clientType\n\treturn sc, nil\n}"} {"input": "package analytics\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n\t\"testing\"\n\t\"time\"\n\n\tadaptertest \"istio.io/istio/mixer/pkg/adapter/test\"\n)\n\nfunc TestLegacySelect(t *testing.T) {\n\n\tenv := adaptertest.NewEnv(t)\n\n\topts := Options{\n\t\tLegacyEndpoint: true,\n\t\tBufferPath: \"\",\n\t\tStagingFileLimit: 10,\n\t\tBaseURL: &url.URL{},\n\t\tKey: \"key\",\n\t\tSecret: \"secret\",\n\t\tClient: http.DefaultClient,\n\t\tnow: time.Now,\n\t}\n\n\tm, err := NewManager(env, opts)\n\tm.Close()\n\tif err != nil {\n\t\tt.Fatalf(\"newManager: %s\", err)\n\t}\n\n\tif _, ok := m.(*legacyAnalytics); !ok {\n\t\tt.Errorf(\"want an *legacyAnalytics type, got: %#v\", m)\n\t}\n}\n\n\n\nfunc TestStandardBadOptions(t *testing.T) {\n\n\tenv := adaptertest.NewEnv(t)\n\n\topts := Options{\n\t\tBufferPath: \"/tmp/apigee-ax/buffer/\",\n\t\tStagingFileLimit: 0,\n\t\tBaseURL: &url.URL{},\n\t\tKey: \"\",\n\t\tSecret: \"\",\n\t\tClient: http.DefaultClient,\n\t\tnow: time.Now,\n\t}\n\n\twant := \"all analytics options are required\"\n\tm, err := NewManager(env, opts)\n\tif err == nil || err.Error() != want {\n\t\tt.Errorf(\"want: %s, got: %s\", want, err)\n\t}\n\tif m != nil {\n\t\tt.Errorf(\"should not get manager\")\n\t\tm.Close()\n\t}\n}\n\nfunc TestStandardSelect(t *testing.T) ", "output": "{\n\n\tenv := adaptertest.NewEnv(t)\n\n\topts := Options{\n\t\tBufferPath: \"/tmp/apigee-ax/buffer/\",\n\t\tStagingFileLimit: 10,\n\t\tBaseURL: &url.URL{},\n\t\tKey: \"key\",\n\t\tSecret: \"secret\",\n\t\tClient: http.DefaultClient,\n\t\tnow: time.Now,\n\t\tCollectionInterval: time.Minute,\n\t}\n\n\tm, err := NewManager(env, opts)\n\tif err != nil {\n\t\tt.Fatalf(\"newManager: %s\", err)\n\t}\n\tm.Close()\n\n\tif _, ok := m.(*manager); !ok {\n\t\tt.Errorf(\"want an *manager type, got: %#v\", m)\n\t}\n}"} {"input": "package cli\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/alexyer/ghost/client\"\n)\n\n\n\nfunc ObtainClient(host string, port int) (*client.GhostClient, error) {\n\taddr := fmt.Sprintf(\"%s:%d\", host, port)\n\treturn connect(addr, \"tcp\")\n}\n\n\nfunc ObtainUnixSocketClient(socket string) (*client.GhostClient, error) {\n\treturn connect(socket, \"unix\")\n}\n\n\n\nfunc connect(addr, network string) (*client.GhostClient, error) ", "output": "{\n\tc := client.New(&client.Options{\n\t\tAddr: addr,\n\t\tNetwork: network,\n\t})\n\n\tif _, err := c.Ping(); err != nil {\n\t\treturn nil, errors.New(fmt.Sprintf(\"cli-ghost: cannot obtain connection to %s\", addr))\n\t}\n\n\tlog.Printf(\"Connection to %s is successfull.\", addr)\n\treturn c, nil\n}"} {"input": "package main\n\nimport (\n\tui \"github.com/gizak/termui\"\n\t\"github.com/matt3o12/termui-widgets/hackernews\"\n)\n\n\n\nfunc main() {\n\tpanicIfErr(ui.Init())\n\tdefer ui.Close()\n\tui.UseTheme(\"helloworld\")\n\n\twidth := 100\n\n\ttopStories := hackernews.NewWidget(hackernews.TopStories)\n\ttopStories.Height = 15\n\ttopStories.Width = width\n\n\tmostRecent := hackernews.NewWidget(hackernews.MostRecent)\n\tmostRecent.Height = 20\n\tmostRecent.Width = width\n\tmostRecent.Y = 15\n\n\tdraw := func() {\n\t\tui.Render(mostRecent, topStories)\n\t}\n\n\ttopStories.UpdateEntries(draw)\n\tmostRecent.UpdateEntries(draw)\n\tdraw()\n\n\t<-ui.EventCh()\n}\n\nfunc panicIfErr(err error) ", "output": "{\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}"} {"input": "package badger\n\n\n\n\n\n\n\n\n\ntype ManagedDB struct {\n\t*DB\n}\n\n\n\n\n\n\nfunc OpenManaged(opts Options) (*ManagedDB, error) {\n\topts.managedTxns = true\n\tdb, err := Open(opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ManagedDB{db}, nil\n}\n\n\n\n\n\n\n\n\n\n\nfunc (db *ManagedDB) NewTransactionAt(readTs uint64, update bool) *Txn {\n\ttxn := db.DB.NewTransaction(update)\n\ttxn.readTs = readTs\n\treturn txn\n}\n\n\n\n\n\n\nfunc (txn *Txn) CommitAt(commitTs uint64, callback func(error)) error {\n\tif !txn.db.opt.managedTxns {\n\t\treturn ErrManagedTxn\n\t}\n\ttxn.commitTs = commitTs\n\treturn txn.Commit(callback)\n}\n\n\nfunc (db *ManagedDB) PurgeVersionsBelow(key []byte, ts uint64) error {\n\ttxn := db.NewTransactionAt(ts, false)\n\tdefer txn.Discard()\n\treturn db.purgeVersionsBelow(txn, key, ts)\n}\n\n\n\nfunc (db *ManagedDB) GetSequence(_ []byte, _ uint64) (*Sequence, error) {\n\tpanic(\"Cannot use GetSequence for ManagedDB.\")\n}\n\nfunc (db *ManagedDB) NewTransaction(update bool) ", "output": "{\n\tpanic(\"Cannot use NewTransaction() for ManagedDB. Use NewTransactionAt() instead.\")\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n\t\"os\"\n\t\"regexp\"\n\t\"strconv\"\n\n\t\"./format\"\n\t\"./index\"\n)\n\nconst indexdir = \"info\"\n\n\n\n\ntype Info struct {\n\tMonth string\n\tNum int\n\tLink string\n\tYear string\n\tNews string\n\tSafeTitle string `json:\"safe_title\"`\n\tTranscript string\n\tAlt string\n\tImg string\n\tTitle string\n\tDay string\n}\n\nfunc main() {\n\tif len(os.Args) > 1 {\n\t\tkeyword := os.Args[1]\n\t\tfor i := 1; i < index.MaxIndex; i++ {\n\t\t\tindexFile := indexdir + \"/\" + strconv.Itoa(i)\n\t\t\tvar (\n\t\t\t\tf *os.File\n\t\t\t\terr error\n\t\t\t)\n\t\t\tif f, err = os.Open(indexFile); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvar info Info\n\t\t\tjson.NewDecoder(f).Decode(&info)\n\t\t\tif match, _ := regexp.MatchString(keyword, info.Transcript); match {\n\t\t\t\tif err := format.Print(index.URLPrefix+strconv.Itoa(i), info.Transcript); err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc init() ", "output": "{\n\tif _, err := os.Stat(indexdir); os.IsNotExist(err) {\n\t\tif err := os.Mkdir(indexdir, 0777); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tindex.CreateIndex(indexdir)\n\t}\n}"} {"input": "package vulcand\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/dtan4/paus-gitreceive/receiver/store\"\n)\n\nconst (\n\thttpBackendJSON = \"{\\\"Type\\\": \\\"http\\\"}\"\n)\n\ntype Backend struct {\n\tType string `json:\"Type\"`\n}\n\n\nfunc setBackend(etcd *store.Etcd, projectName string) error {\n\tkey := fmt.Sprintf(\"%s/backends/%s/backend\", vulcandKeyBase, projectName)\n\n\tif err := etcd.Set(key, httpBackendJSON); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\nfunc unsetBackend(etcd *store.Etcd, projectName string) error ", "output": "{\n\tkey := fmt.Sprintf(\"%s/backends/%s/backend\", vulcandKeyBase, projectName)\n\n\tif err := etcd.Delete(key); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package stats\n\nimport (\n\tlog \"code.google.com/p/log4go\"\n\t\"github.com/ekarlso/gomdns/config\"\n\tinflux \"github.com/rcrowley/go-metrics/influxdb\"\n)\n\n\n\nfunc setUpInflux(cfg *config.Configuration) ", "output": "{\n\tif cfg.InfluxUser == \"\" {\n\t\tlog.Debug(\"No InfluxDB user specified, not pushing stats.\")\n\t\treturn\n\t}\n\tlog.Debug(\"Setting up InfluxDB stats push\")\n\tgo influx.Influxdb(NameServerStats, 10e9, &influx.Config{\n\t\tHost: cfg.InfluxHost,\n\t\tDatabase: cfg.InfluxDb,\n\t\tUsername: cfg.InfluxUser,\n\t\tPassword: cfg.InfluxPassword,\n\t})\n}"} {"input": "package assert\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"runtime\"\n)\n\nconst windows = runtime.GOOS == \"windows\"\n\n\n\n\n\ntype MatchPath string\n\nfunc isSlash(c byte) bool { return c == '\\\\' || c == '/' }\n\nfunc (m MatchPath) isAbs(path string) bool {\n\treturn filepath.IsAbs(path) || (windows && len(path) != 0 && isSlash(path[0]))\n}\n\nfunc (m MatchPath) cleanPath(s string) string {\n\tif !windows || !m.isAbs(s) {\n\t\treturn s\n\t}\n\ta, err := filepath.Abs(s)\n\tif err != nil {\n\t\treturn s\n\t}\n\treturn a\n}\n\nfunc (m MatchPath) Match(actual interface{}) (bool, error) {\n\tpath, ok := actual.(string)\n\tif !ok {\n\t\treturn false, fmt.Errorf(\"MatchPath: expects a string got: %T\", actual)\n\t}\n\tif path == string(m) || (filepath.Clean(path) == filepath.Clean(string(m))) {\n\t\treturn true, nil\n\t}\n\treturn m.cleanPath(path) == m.cleanPath(string(m)), nil\n}\n\nfunc (m MatchPath) FailureMessage(actual interface{}) string {\n\tif windows {\n\t\tif s, ok := actual.(string); ok {\n\t\t\treturn fmt.Sprintf(\"Expected\\n\\t%v\\n\\t%v (clean)\\nto match file\\n\\t%v\\n\\t%v (clean)\",\n\t\t\t\tactual, m.cleanPath(s), m, m.cleanPath(string(m)))\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"Expected\\n\\t%v\\nto match file\\n\\t%v\", actual, m)\n}\n\n\n\nfunc (m MatchPath) NegatedFailureMessage(actual interface{}) string ", "output": "{\n\tif windows {\n\t\tif s, ok := actual.(string); ok {\n\t\t\treturn fmt.Sprintf(\"Expected\\n\\t%v\\n\\t%v (clean)\\nnot to match file\\n\\t%v\\n\\t%v (clean)\",\n\t\t\t\tactual, m.cleanPath(s), m, m.cleanPath(string(m)))\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"Expected\\n\\t%v\\nnot to match file\\n\\t%v\", actual, m)\n}"} {"input": "package field\n\nimport (\n\t\"sync\"\n\n\t\"github.com/elemchat/elemchat/wizard\"\n)\n\ntype Field struct {\n\tsync.Mutex\n\tWizards map[*wizard.Wizard]struct{}\n\trecv chan wizard.Message\n\tclosed bool\n}\n\ntype HandleFunc func(wizard.Message)\n\n\n\n\nfunc (f *Field) WithLock(fn func(*Field)) {\n\tf.Lock()\n\tfn(f)\n\tf.Unlock()\n}\n\nfunc (f *Field) Close() {\n\tf.WithLock(func(f *Field) {\n\t\tif f.closed {\n\t\t\treturn\n\t\t}\n\n\t\tgo func() {\n\t\t\tfor _ = range f.recv {\n\t\t\t}\n\t\t}()\n\n\t\tfor w, _ := range f.Wizards {\n\t\t\tw.Close(true)\n\t\t\tdelete(f.Wizards, w)\n\t\t}\n\t\tclose(f.recv)\n\t\tf.closed = true\n\t})\n}\n\nfunc (f *Field) Enter(fn func(recv chan<- wizard.Message) *wizard.Wizard) {\n\tf.WithLock(func(f *Field) {\n\t\tif f.closed {\n\t\t\treturn\n\t\t}\n\n\t\tw := fn(f.recv)\n\t\tif w != nil {\n\t\t\tf.Wizards[w] = struct{}{}\n\t\t}\n\t})\n}\n\nfunc (f *Field) loop(handle HandleFunc) {\n\tif handle == nil {\n\t\tf.Close()\n\t\treturn\n\t}\n\tfor message := range f.recv {\n\t\tif message.Msg() == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\thandle(message)\n\t}\n}\n\nfunc New(handle HandleFunc) *Field ", "output": "{\n\tf := &Field{\n\t\tMutex: sync.Mutex{},\n\t\tWizards: make(map[*wizard.Wizard]struct{}),\n\t\trecv: make(chan wizard.Message),\n\t\tclosed: false,\n\t}\n\n\tgo f.loop(handle)\n\treturn f\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/astaxie/beego/context\"\n\t\"github.com/yangji168/omsystem/hauth/hcache\"\n\t\"github.com/yangji168/omsystem/utils/hret\"\n)\n\n\n\nfunc init() {\n\thcache.Register(\"AsofdateIndexPage\", \"./views/login.tpl\")\n}\n\nfunc IndexPage(ctx *context.Context) ", "output": "{\n\trst, err := hcache.GetStaticFile(\"AsofdateIndexPage\")\n\tif err != nil {\n\t\thret.WriteHttpErrMsgs(ctx.ResponseWriter, 404, \"页面不存在\")\n\t\treturn\n\t}\n\tctx.ResponseWriter.Write(rst)\n}"} {"input": "package router\n\n\n\n\nimport (\n\t\"github.com/weaveworks/mesh\"\n)\n\n\n\ntype AWSVPCConnection struct {\n\testablishedChan chan struct{}\n\terrorChan chan error\n}\n\nfunc (conn *AWSVPCConnection) Confirm() {\n\tclose(conn.establishedChan)\n}\n\nfunc (conn *AWSVPCConnection) EstablishedChannel() <-chan struct{} {\n\treturn conn.establishedChan\n}\n\nfunc (conn *AWSVPCConnection) ErrorChannel() <-chan error {\n\treturn conn.errorChan\n}\n\nfunc (conn *AWSVPCConnection) Stop() {}\n\nfunc (conn *AWSVPCConnection) ControlMessage(tag byte, msg []byte) {\n}\n\nfunc (conn *AWSVPCConnection) DisplayName() string {\n\treturn \"awsvpc\"\n}\n\n\n\nfunc (conn *AWSVPCConnection) Forward(key ForwardPacketKey) FlowOp {\n\treturn DiscardingFlowOp{}\n}\n\ntype AWSVPC struct{}\n\nfunc NewAWSVPC() AWSVPC {\n\treturn AWSVPC{}\n}\n\n\n\nfunc (vpc AWSVPC) AddFeaturesTo(features map[string]string) {}\n\nfunc (vpc AWSVPC) PrepareConnection(params mesh.OverlayConnectionParams) (mesh.OverlayConnection, error) {\n\tconn := &AWSVPCConnection{\n\t\testablishedChan: make(chan struct{}),\n\t\terrorChan: make(chan error, 1),\n\t}\n\treturn conn, nil\n}\n\nfunc (vpc AWSVPC) Diagnostics() interface{} {\n\treturn nil\n}\n\n\n\nfunc (vpc AWSVPC) InvalidateRoutes() {}\n\nfunc (vpc AWSVPC) InvalidateShortIDs() {}\n\n\n\nfunc (vpc AWSVPC) StartConsumingPackets(localPeer *mesh.Peer, peers *mesh.Peers, consumer OverlayConsumer) error ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n)\n\n\ntype Tree struct {\n\tLeft *Tree\n\tValue int\n\tRight *Tree\n}\n\n\n\nfunc Walk(t *Tree, ch chan int) {\n\tif t == nil {\n\t\treturn\n\t}\n\tWalk(t.Left, ch)\n\tch <- t.Value\n\tWalk(t.Right, ch)\n}\n\n\n\nfunc Walker(t *Tree) <-chan int {\n\tch := make(chan int)\n\tgo func() {\n\t\tWalk(t, ch)\n\t\tclose(ch)\n\t}()\n\treturn ch\n}\n\n\n\n\nfunc Compare(t1, t2 *Tree) bool {\n\tc1, c2 := Walker(t1), Walker(t2)\n\tfor {\n\t\tv1, ok1 := <-c1\n\t\tv2, ok2 := <-c2\n\t\tif !ok1 || !ok2 {\n\t\t\treturn ok1 == ok2\n\t\t}\n\t\tif v1 != v2 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn false\n}\n\n\n\nfunc New(n, k int) *Tree {\n\tvar t *Tree\n\tfor _, v := range rand.Perm(n) {\n\t\tt = insert(t, (1+v)*k)\n\t}\n\treturn t\n}\n\n\n\nfunc main() {\n\tt1 := New(100, 1)\n\tfmt.Println(Compare(t1, New(100, 1)), \"Same Contents\")\n\tfmt.Println(Compare(t1, New(99, 1)), \"Differing Sizes\")\n\tfmt.Println(Compare(t1, New(100, 2)), \"Differing Values\")\n\tfmt.Println(Compare(t1, New(101, 2)), \"Dissimilar\")\n}\n\nfunc insert(t *Tree, v int) *Tree ", "output": "{\n\tif t == nil {\n\t\treturn &Tree{nil, v, nil}\n\t}\n\tif v < t.Value {\n\t\tt.Left = insert(t.Left, v)\n\t\treturn t\n\t}\n\tt.Right = insert(t.Right, v)\n\treturn t\n}"} {"input": "package geth\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/etherite/go-etherite/core\"\n\t\"github.com/etherite/go-etherite/p2p/discv5\"\n\t\"github.com/etherite/go-etherite/params\"\n)\n\n\n\nfunc MainnetGenesis() string {\n\treturn \"\"\n}\n\n\nfunc TestnetGenesis() string {\n\tenc, err := json.Marshal(core.DefaultTestnetGenesisBlock())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(enc)\n}\n\n\n\n\n\n\nfunc FoundationBootnodes() *Enodes {\n\tnodes := &Enodes{nodes: make([]*discv5.Node, len(params.DiscoveryV5Bootnodes))}\n\tfor i, url := range params.DiscoveryV5Bootnodes {\n\t\tnodes.nodes[i] = discv5.MustParseNode(url)\n\t}\n\treturn nodes\n}\n\nfunc RinkebyGenesis() string ", "output": "{\n\tenc, err := json.Marshal(core.DefaultRinkebyGenesisBlock())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(enc)\n}"} {"input": "package main\n\nimport \"strings\"\n\ntype code_section interface {\n\tCode() bool\n}\n\ntype para string\n\n\n\ntype code string\n\nfunc (code) Code() bool {\n\treturn true\n}\n\ntype Article struct {\n\tTitle string\n\tIntro []para\n\tGoCode, ReflectCode []code_section\n\tUses, Tags []string\n\tslug string\n}\n\nfunc (a *Article) Slug() string {\n\tif a.slug == \"\" {\n\t\ta.slug = strings.ToLower(strings.Replace(a.Title, \" \", \"-\", -1))\n\t}\n\treturn a.slug\n}\n\ntype Articles []*Article\n\nfunc (a *Articles) Add(ao *Article) {\n\t*a = append(*a, ao)\n}\n\nfunc (a Articles) Len() int {\n\treturn len(a)\n}\n\nfunc (a Articles) Swap(i, j int) {\n\ta[j], a[i] = a[i], a[j]\n}\n\nfunc (a Articles) Less(i, j int) bool {\n\treturn a[i].Title < a[j].Title\n}\n\nfunc (para) Code() bool ", "output": "{\n\treturn false\n}"} {"input": "package main\n\nimport \"fmt\"\nimport \"net\"\n\n\n\nfunc main() {\n\tfmt.Println(\"Start server.....\")\n\tlisten, err := net.Listen(\"tcp\", \"127.0.0.1:50000\")\n\tif err != nil {\n\t\tfmt.Println(\"Listen fail \", err)\n\t\treturn\n\t}\n\n\tfor {\n\t\tconn, err := listen.Accept()\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Accept error \", err)\n\t\t\treturn\n\t\t}\n\n\t\tgo process(conn)\n\n\t}\n\n}\n\nfunc process(conn net.Conn) ", "output": "{\n\tdefer conn.Close()\n\n\tfor {\n\t\tbuf := make([]byte, 512)\n\t\t_, err := conn.Read(buf)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"read err\", err)\n\t\t\treturn\n\t\t}\n\t\tfmt.Println(\"read:\", string(buf))\n\t}\n}"} {"input": "package v1\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/goharbor/harbor/src/pkg/reg/adapter/harbor/base\"\n\t\"github.com/goharbor/harbor/src/pkg/reg/model\"\n\trepomodel \"github.com/goharbor/harbor/src/pkg/repository/model\"\n)\n\ntype client struct {\n\t*base.Client\n}\n\n\n\nfunc (c *client) listArtifacts(repository string) ([]*model.Artifact, error) {\n\turl := fmt.Sprintf(\"%s/repositories/%s/tags\", c.BasePath(), repository)\n\ttags := []*struct {\n\t\tName string `json:\"name\"`\n\t\tLabels []*struct {\n\t\t\tName string `json:\"name\"`\n\t\t}\n\t}{}\n\tif err := c.C.Get(url, &tags); err != nil {\n\t\treturn nil, err\n\t}\n\tvar artifacts []*model.Artifact\n\tfor _, tag := range tags {\n\t\tartifact := &model.Artifact{\n\t\t\tType: string(model.ResourceTypeImage),\n\t\t\tTags: []string{tag.Name},\n\t\t}\n\t\tfor _, label := range tag.Labels {\n\t\t\tartifact.Labels = append(artifact.Labels, label.Name)\n\t\t}\n\t\tartifacts = append(artifacts, artifact)\n\t}\n\treturn artifacts, nil\n}\n\nfunc (c *client) deleteManifest(repository, reference string) error {\n\turl := fmt.Sprintf(\"%s/repositories/%s/tags/%s\", c.BasePath(), repository, reference)\n\treturn c.C.Delete(url)\n}\n\nfunc (c *client) listRepositories(project *base.Project) ([]*model.Repository, error) ", "output": "{\n\trepositories := []*repomodel.RepoRecord{}\n\turl := fmt.Sprintf(\"%s/repositories?project_id=%d\", c.BasePath(), project.ID)\n\tif err := c.C.GetAndIteratePagination(url, &repositories); err != nil {\n\t\treturn nil, err\n\t}\n\tvar repos []*model.Repository\n\tfor _, repository := range repositories {\n\t\trepos = append(repos, &model.Repository{\n\t\t\tName: repository.Name,\n\t\t\tMetadata: project.Metadata,\n\t\t})\n\t}\n\treturn repos, nil\n}"} {"input": "package v1\n\nimport (\n\tv1 \"k8s.io/api/networking/v1\"\n\t\"k8s.io/client-go/deprecated/scheme\"\n\trest \"k8s.io/client-go/rest\"\n)\n\ntype NetworkingV1Interface interface {\n\tRESTClient() rest.Interface\n\tNetworkPoliciesGetter\n}\n\n\ntype NetworkingV1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *NetworkingV1Client) NetworkPolicies(namespace string) NetworkPolicyInterface {\n\treturn newNetworkPolicies(c, namespace)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*NetworkingV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &NetworkingV1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *NetworkingV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\n\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\nfunc (c *NetworkingV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc New(c rest.Interface) *NetworkingV1Client ", "output": "{\n\treturn &NetworkingV1Client{c}\n}"} {"input": "package driver\n\nimport (\n\t\"github.com/Azure/azure-docker-extension/pkg/executil\"\n)\n\ntype ubuntuBaseDriver struct{}\n\nfunc (u ubuntuBaseDriver) InstallDocker() error {\n\treturn executil.ExecPipe(\"/bin/sh\", \"-c\", \"wget -qO- https://get.docker.com/ | sh\")\n}\n\n\n\nfunc (u ubuntuBaseDriver) DockerComposeDir() string { return \"/usr/local/bin\" }\n\nfunc (u ubuntuBaseDriver) UninstallDocker() error ", "output": "{\n\tif err := executil.ExecPipe(\"apt-get\", \"-qqy\", \"purge\", \"docker-engine\"); err != nil {\n\t\treturn err\n\t}\n\treturn executil.ExecPipe(\"apt-get\", \"-qqy\", \"autoremove\")\n}"} {"input": "package errors \n\nimport (\n\t\"strconv\"\n)\n\n\n\ntype StructuralError string\n\nfunc (s StructuralError) Error() string {\n\treturn \"openpgp: invalid data: \" + string(s)\n}\n\n\n\ntype UnsupportedError string\n\nfunc (s UnsupportedError) Error() string {\n\treturn \"openpgp: unsupported feature: \" + string(s)\n}\n\n\n\ntype InvalidArgumentError string\n\nfunc (i InvalidArgumentError) Error() string {\n\treturn \"openpgp: invalid argument: \" + string(i)\n}\n\n\n\ntype SignatureError string\n\nfunc (b SignatureError) Error() string {\n\treturn \"openpgp: invalid signature: \" + string(b)\n}\n\ntype keyIncorrectError int\n\nfunc (ki keyIncorrectError) Error() string {\n\treturn \"openpgp: incorrect key\"\n}\n\nvar ErrKeyIncorrect error = keyIncorrectError(0)\n\ntype unknownIssuerError int\n\n\n\nvar ErrUnknownIssuer error = unknownIssuerError(0)\n\ntype keyRevokedError int\n\nfunc (keyRevokedError) Error() string {\n\treturn \"openpgp: signature made by revoked key\"\n}\n\nvar ErrKeyRevoked error = keyRevokedError(0)\n\ntype UnknownPacketTypeError uint8\n\nfunc (upte UnknownPacketTypeError) Error() string {\n\treturn \"openpgp: unknown packet type: \" + strconv.Itoa(int(upte))\n}\n\nfunc (unknownIssuerError) Error() string ", "output": "{\n\treturn \"openpgp: signature made by unknown entity\"\n}"} {"input": "package v1alpha1\n\nimport (\n\tcorev1 \"k8s.io/api/core/v1\"\n)\n\n\n\ntype ListBuilder struct {\n\tlist *PodList\n\tfilters predicateList\n}\n\n\nfunc NewListBuilder() *ListBuilder {\n\treturn &ListBuilder{list: &PodList{items: []*Pod{}}}\n}\n\n\nfunc ListBuilderForAPIList(pods *corev1.PodList) *ListBuilder {\n\tb := &ListBuilder{list: &PodList{}}\n\tif pods == nil {\n\t\treturn b\n\t}\n\tfor _, p := range pods.Items {\n\t\tp := p\n\t\tb.list.items = append(b.list.items, &Pod{object: &p})\n\t}\n\treturn b\n}\n\n\n\n\n\n\n\nfunc (b *ListBuilder) List() *PodList {\n\tif b.filters == nil || len(b.filters) == 0 {\n\t\treturn b.list\n\t}\n\tfiltered := &PodList{}\n\tfor _, pod := range b.list.items {\n\t\tif b.filters.all(pod) {\n\t\t\tfiltered.items = append(filtered.items, pod)\n\t\t}\n\t}\n\treturn filtered\n}\n\n\n\nfunc (b *ListBuilder) WithFilter(pred ...Predicate) *ListBuilder {\n\tb.filters = append(b.filters, pred...)\n\treturn b\n}\n\nfunc ListBuilderForObjectList(pods ...*Pod) *ListBuilder ", "output": "{\n\tb := &ListBuilder{list: &PodList{}}\n\tif pods == nil {\n\t\treturn b\n\t}\n\tfor _, p := range pods {\n\t\tp := p\n\t\tb.list.items = append(b.list.items, p)\n\t}\n\treturn b\n}"} {"input": "package event\n\nimport (\n\t\"io/ioutil\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com/alvalor/alvalor-go/network\"\n\t\"github.com/alvalor/alvalor-go/node/handlers/message\"\n\t\"github.com/alvalor/alvalor-go/types\"\n\t\"github.com/rs/zerolog\"\n\t\"github.com/stretchr/testify/mock\"\n)\n\n\n\nfunc TestProcessReceivedSuccess(t *testing.T) ", "output": "{\n\n\thash := types.Hash{0x1}\n\taddress := \"192.0.2.1\"\n\n\twg := &sync.WaitGroup{}\n\tmsg := &message.GetTx{Hash: hash}\n\tevent := network.Received{Address: address, Message: msg}\n\n\tnet := &NetworkMock{}\n\theaders := &HeadersMock{}\n\tpeers := &PeersMock{}\n\tmessage := &MessageMock{}\n\n\thandler := &Handler{\n\t\tlog: zerolog.New(ioutil.Discard),\n\t\tnet: net,\n\t\theaders: headers,\n\t\tpeers: peers,\n\t\tmessage: message,\n\t}\n\n\tmessage.On(\"Process\", mock.Anything, mock.Anything, mock.Anything)\n\n\thandler.Process(wg, event)\n\twg.Wait()\n\n\tif message.AssertNumberOfCalls(t, \"Process\", 1) {\n\t\tmessage.AssertCalled(t, \"Process\", wg, address, msg)\n\t}\n}"} {"input": "package todoist\n\nimport \"fmt\"\n\ntype IntBool bool\n\nfunc (i IntBool) Bool() bool {\n\tif i {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}\n\nfunc (i IntBool) MarshalJSON() ([]byte, error) {\n\tif i {\n\t\treturn []byte(\"1\"), nil\n\t} else {\n\t\treturn []byte(\"0\"), nil\n\t}\n}\n\nfunc (i *IntBool) UnmarshalJSON(b []byte) (err error) {\n\tswitch string(b) {\n\tcase \"1\":\n\t\t*i = true\n\tcase \"0\":\n\t\t*i = false\n\tdefault:\n\t\treturn fmt.Errorf(\"Could not unmarshal into intbool: %s\", string(b))\n\t}\n\treturn nil\n}\n\ntype ColorStringer interface {\n\tString() string\n\tColorString() string\n}\n\ntype NoColorString struct {\n\ts string\n}\n\n\n\nfunc (n NoColorString) String() string {\n\treturn n.s\n}\n\nfunc (n NoColorString) ColorString() string {\n\treturn n.s\n}\n\nfunc NewNoColorString(s string) NoColorString ", "output": "{\n\treturn NoColorString{s}\n}"} {"input": "package s0095\n\nimport \"github.com/peterstace/project-euler/number\"\n\nfunc Answer() interface{} {\n\tconst limit = 1e6 + 1\n\n\tsumProperDivisors := generateSumProperDivisors(limit)\n\t_ = sumProperDivisors\n\n\tvar maxLength int\n\tvar smallestMember int\n\n\tfor i := 2; i < limit; i++ {\n\t\tchainLen, smallestInChain, ok := findChain(i, sumProperDivisors)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tif chainLen > maxLength {\n\t\t\tmaxLength = chainLen\n\t\t\tsmallestMember = smallestInChain\n\t\t}\n\t}\n\n\treturn smallestMember\n}\n\n\n\nfunc findChain(x int, sumProperDivisors []int) (chainLength, smallestInChain int, ok bool) {\n\tnums := make(map[int]struct{})\n\tfor {\n\t\tnums[x] = struct{}{}\n\t\tx = sumProperDivisors[x]\n\t\tif x >= len(sumProperDivisors) {\n\t\t\treturn 0, 0, false\n\t\t}\n\t\tif _, ok := nums[x]; ok {\n\t\t\tbreak\n\t\t}\n\t}\n\tvar count int\n\tmin := x\n\tstart := x\n\tfor {\n\t\tx = sumProperDivisors[x]\n\t\tcount++\n\t\tif x < min {\n\t\t\tmin = x\n\t\t}\n\t\tif x == start {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn count, min, true\n}\n\nfunc generateSumProperDivisors(n int) []int ", "output": "{\n\ts := number.PrimeFactorisationSieve(n)\n\td := make([]int, n)\n\tfor i := 1; i < len(s); i++ {\n\t\td[i] = s[i].SumDivisors() - i\n\t}\n\treturn d\n}"} {"input": "package v1beta1\n\nimport (\n\tv1beta1 \"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\ntype CustomResourceDefinitionLister interface {\n\tList(selector labels.Selector) (ret []*v1beta1.CustomResourceDefinition, err error)\n\tGet(name string) (*v1beta1.CustomResourceDefinition, error)\n\tCustomResourceDefinitionListerExpansion\n}\n\n\ntype customResourceDefinitionLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewCustomResourceDefinitionLister(indexer cache.Indexer) CustomResourceDefinitionLister {\n\treturn &customResourceDefinitionLister{indexer: indexer}\n}\n\n\n\n\n\nfunc (s *customResourceDefinitionLister) Get(name string) (*v1beta1.CustomResourceDefinition, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"customresourcedefinition\"), name)\n\t}\n\treturn obj.(*v1beta1.CustomResourceDefinition), nil\n}\n\nfunc (s *customResourceDefinitionLister) List(selector labels.Selector) (ret []*v1beta1.CustomResourceDefinition, err error) ", "output": "{\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.CustomResourceDefinition))\n\t})\n\treturn ret, err\n}"} {"input": "package eventbreakpoints\n\n\n\nimport (\n\t\"context\"\n\n\t\"github.com/chromedp/cdproto/cdp\"\n)\n\n\n\ntype SetInstrumentationBreakpointParams struct {\n\tEventName string `json:\"eventName\"` \n}\n\n\n\n\n\n\n\nfunc SetInstrumentationBreakpoint(eventName string) *SetInstrumentationBreakpointParams {\n\treturn &SetInstrumentationBreakpointParams{\n\t\tEventName: eventName,\n\t}\n}\n\n\n\n\n\n\ntype RemoveInstrumentationBreakpointParams struct {\n\tEventName string `json:\"eventName\"` \n}\n\n\n\n\n\n\n\n\nfunc RemoveInstrumentationBreakpoint(eventName string) *RemoveInstrumentationBreakpointParams {\n\treturn &RemoveInstrumentationBreakpointParams{\n\t\tEventName: eventName,\n\t}\n}\n\n\nfunc (p *RemoveInstrumentationBreakpointParams) Do(ctx context.Context) (err error) {\n\treturn cdp.Execute(ctx, CommandRemoveInstrumentationBreakpoint, p, nil)\n}\n\n\nconst (\n\tCommandSetInstrumentationBreakpoint = \"EventBreakpoints.setInstrumentationBreakpoint\"\n\tCommandRemoveInstrumentationBreakpoint = \"EventBreakpoints.removeInstrumentationBreakpoint\"\n)\n\nfunc (p *SetInstrumentationBreakpointParams) Do(ctx context.Context) (err error) ", "output": "{\n\treturn cdp.Execute(ctx, CommandSetInstrumentationBreakpoint, p, nil)\n}"} {"input": "package cases\n\nimport (\n\t\"io/ioutil\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc testFilesFor(t testing.TB, dirname string, includes, ignores []string) []string {\n\tfiles, err := ioutil.ReadDir(dirname)\n\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\ttestFiles := make([]string, 0)\n\n\tfor _, file := range files {\n\n\t\tif file.IsDir() {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !strings.HasSuffix(file.Name(), \".json\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !isIncludedTestCase(file.Name(), includes, ignores) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !isTestCaseAllowed(file.Name()) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !file.IsDir() {\n\t\t\ttestFiles = append(testFiles, filepath.Join(dirname, file.Name()))\n\t\t}\n\n\t}\n\n\treturn testFiles\n}\n\n\n\nfunc rgxForMatcher(s string) *regexp.Regexp {\n\treturn regexp.MustCompile(\"(?i)\" + regexp.QuoteMeta(s))\n}\n\nfunc isIncludedTestCase(s string, includes, ignores []string) bool ", "output": "{\n\n\tfor _, ignore := range ignores {\n\t\trgx := rgxForMatcher(ignore)\n\n\t\tif rgx.MatchString(s) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tfor _, include := range includes {\n\t\trgx := rgxForMatcher(include)\n\n\t\tif !rgx.MatchString(s) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n\n}"} {"input": "package gziphandler\n\nimport (\n\t\"bytes\"\n\t\"compress/gzip\"\n\t\"io\"\n\t\"net/http\"\n\t\"strings\"\n)\n\ntype gzipResponseWriter struct {\n\tio.Writer\n\thttp.ResponseWriter\n}\n\n\n\nfunc NewGZipHandler(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif !strings.Contains(r.Header.Get(\"Accept-Encoding\"), \"gzip\") {\n\t\t\th.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\t\tw.Header().Set(\"Content-Encoding\", \"gzip\")\n\t\tgz := gzip.NewWriter(w)\n\t\tdefer gz.Close()\n\t\th.ServeHTTP(&gzipResponseWriter{Writer: gz, ResponseWriter: w}, r)\n\t})\n}\n\nfunc GzipContent(gzbuff *bytes.Buffer, uncompressedContent []byte) (err error) {\n\tgz := gzip.NewWriter(gzbuff)\n\t_, err = gz.Write(uncompressedContent)\n\tgz.Close() \n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (m *gzipResponseWriter) Write(b []byte) (int, error) ", "output": "{\n\treturn m.Writer.Write(b)\n}"} {"input": "package assert\n\nimport (\n\t\"testing\"\n)\n\nfunc IntEquals(t *testing.T, actual int, expected int) {\n\tif actual != expected {\n\t\tt.Fatalf(\"%#v != %#v\", actual, expected)\n\t}\n}\n\n\n\nfunc StringEquals(t *testing.T, actual string, expected string) {\n\tif actual != expected {\n\t\tt.Fatalf(\"%#v != %#v\", actual, expected)\n\t}\n}\n\nfunc IntListEquals(t *testing.T, actualList []int, expectedList []int) {\n\tIntEquals(t, len(actualList), len(expectedList))\n\tfor i, expected := range expectedList {\n\t\tIntEquals(t, actualList[i], expected)\n\t}\n}\n\nfunc IntListListEquals(t *testing.T, actualList [][]int, expectedList [][]int) {\n\tif len(actualList) != len(expectedList) {\n\t\tt.Fatalf(\"%#v != %#v\", actualList, expectedList)\n\t}\n\tfor i, expected := range expectedList {\n\t\tIntListEquals(t, actualList[i], expected)\n\t}\n}\n\nfunc Float32Equals(t *testing.T, actual float32, expected float32) ", "output": "{\n\tif actual != expected {\n\t\tt.Fatalf(\"%#v != %#v\", actual, expected)\n\t}\n}"} {"input": "package node\n\nimport (\n\t\"fmt\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/docker/docker/api/types\"\n\t\"github.com/docker/docker/cli\"\n\t\"github.com/docker/docker/cli/command\"\n\t\"github.com/spf13/cobra\"\n)\n\ntype removeOptions struct {\n\tforce bool\n}\n\n\n\nfunc runRemove(dockerCli *command.DockerCli, args []string, opts removeOptions) error {\n\tclient := dockerCli.Client()\n\tctx := context.Background()\n\tfor _, nodeID := range args {\n\t\terr := client.NodeRemove(ctx, nodeID, types.NodeRemoveOptions{Force: opts.force})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Fprintf(dockerCli.Out(), \"%s\\n\", nodeID)\n\t}\n\treturn nil\n}\n\nfunc newRemoveCommand(dockerCli *command.DockerCli) *cobra.Command ", "output": "{\n\topts := removeOptions{}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"rm [OPTIONS] NODE [NODE...]\",\n\t\tAliases: []string{\"remove\"},\n\t\tShort: \"Remove one or more nodes from the swarm\",\n\t\tArgs: cli.RequiresMinArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn runRemove(dockerCli, args, opts)\n\t\t},\n\t}\n\tflags := cmd.Flags()\n\tflags.BoolVar(&opts.force, \"force\", false, \"Force remove an active node\")\n\treturn cmd\n}"} {"input": "package http\n\nimport (\n\t\"net/http\"\n\t\"net/http/cookiejar\"\n\t\"net/url\"\n\t\"sync\"\n\n\tc \"github.com/d0ngw/go/common\"\n)\n\n\ntype RetrivedCookieJar struct {\n\tjar *cookiejar.Jar\n\turlCookies map[string][]*http.Cookie\n\tmu sync.Mutex\n}\n\n\nfunc NewRetrivedCookieJar(o *cookiejar.Options) *RetrivedCookieJar {\n\tjar, _ := cookiejar.New(o)\n\treturn &RetrivedCookieJar{\n\t\tjar: jar,\n\t\turlCookies: map[string][]*http.Cookie{},\n\t}\n}\n\n\nfunc (p *RetrivedCookieJar) SetCookies(u *url.URL, cookies []*http.Cookie) {\n\tp.jar.SetCookies(u, cookies)\n\tcookieURL := u.String()\n\tif u != nil && cookies != nil {\n\t\tp.mu.Lock()\n\t\tp.urlCookies[cookieURL] = append(p.urlCookies[cookieURL], cookies...)\n\t\tp.mu.Unlock()\n\t}\n}\n\n\nfunc (p *RetrivedCookieJar) Cookies(u *url.URL) []*http.Cookie {\n\treturn p.jar.Cookies(u)\n}\n\n\n\n\n\nfunc (p *RetrivedCookieJar) SetURLAndCookies(all map[string][]*http.Cookie) error {\n\tif all == nil {\n\t\treturn nil\n\t}\n\n\tfor u, cookies := range all {\n\t\tif cookies == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tcookieURL, err := url.Parse(u)\n\t\tif err != nil {\n\t\t\tc.Errorf(\"parse %s fail,err:%s\", u, err)\n\t\t\tcontinue\n\t\t}\n\t\tp.SetCookies(cookieURL, cookies)\n\t}\n\n\treturn nil\n}\n\nfunc (p *RetrivedCookieJar) URLAndCookies() map[string][]*http.Cookie ", "output": "{\n\tall := map[string][]*http.Cookie{}\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tfor k, v := range p.urlCookies {\n\t\tall[k] = v\n\t}\n\treturn all\n}"} {"input": "package golax\n\nimport \"net/http\"\n\n\n\ntype Context struct {\n\tRequest *http.Request\n\tResponse *ExtendedWriter\n\tParameter string\n\tParameters map[string]string\n\tLastError *ContextError\n\tScope map[string]interface{}\n\tPathHandlers string\n\tafters []Handler\n\tdeepInterceptors []*Interceptor\n}\n\n\n\ntype ContextError struct {\n\tStatusCode int `json:\"status_code\"`\n\tErrorCode int `json:\"error_code\"`\n\tDescription string `json:\"description_code\"`\n}\n\n\nfunc NewContext() *Context {\n\treturn &Context{\n\t\tLastError: nil,\n\t\tParameters: map[string]string{},\n\t\tScope: map[string]interface{}{},\n\t\tafters: []Handler{},\n\t\tdeepInterceptors: []*Interceptor{},\n\t}\n}\n\nfunc (c *Context) Error(s int, d string) *ContextError {\n\tc.Response.WriteHeader(s)\n\te := &ContextError{\n\t\tStatusCode: s,\n\t\tDescription: d,\n\t}\n\tc.LastError = e\n\treturn e\n}\n\n\nfunc (c *Context) Set(k string, v interface{}) {\n\tc.Scope[k] = v\n}\n\n\n\n\nfunc (c *Context) Get(k string) (interface{}, bool) ", "output": "{\n\ta, b := c.Scope[k]\n\treturn a, b\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n)\n\nconst (\n\tsemanticAlphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-\"\n\n\tsemanticBuildAlphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-.\"\n)\n\n\n\nconst (\n\tAppName string = \"dcrdata\"\n\tAppMajor uint = 6\n\tAppMinor uint = 1\n\tAppPatch uint = 0\n)\n\n\nvar (\n\tappPreRelease = \"pre\"\n\n\tappBuild = \"dev\"\n)\n\n\n\n\n\n\n\nfunc normalizeSemString(str, alphabet string) string {\n\tvar result bytes.Buffer\n\tfor _, r := range str {\n\t\tif strings.ContainsRune(alphabet, r) {\n\t\t\tresult.WriteRune(r)\n\t\t}\n\t}\n\treturn result.String()\n}\n\n\n\n\n\nfunc normalizePreRelString(str string) string {\n\treturn normalizeSemString(str, semanticAlphabet)\n}\n\n\n\n\n\nfunc normalizeBuildString(str string) string {\n\treturn normalizeSemString(str, semanticBuildAlphabet)\n}\n\nfunc Version() string ", "output": "{\n\tversion := fmt.Sprintf(\"%d.%d.%d\", AppMajor, AppMinor, AppPatch)\n\n\tpreRelease := normalizePreRelString(appPreRelease)\n\tif preRelease != \"\" {\n\t\tversion = fmt.Sprintf(\"%s-%s\", version, preRelease)\n\t}\n\n\tbuild := normalizeBuildString(appBuild)\n\tif build != \"\" {\n\t\tversion = fmt.Sprintf(\"%s+%s\", version, build)\n\t}\n\n\treturn version\n}"} {"input": "package elements\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestRegistryAddId(t *testing.T) {\n\tr := NewRegistry()\n\tc := NewComponent(\"cloud\", \"foo\", \"\")\n\n\tr.Add(c)\n\tc1 := Get(r, \"foo\")\n\tassert.Equal(t, c, c1)\n}\n\nfunc TestRegistryAddAlias(t *testing.T) {\n\tr := NewRegistry()\n\tc := NewComponent(\"cloud\", \"foo\", \"bar\")\n\n\tr.Add(c)\n\tc1 := Get(r, \"bar\")\n\tassert.Equal(t, c, c1)\n\n\tc2 := Get(r, \"foo\")\n\tassert.Nil(t, c2)\n}\n\n\n\nfunc TestErrors(t *testing.T) ", "output": "{\n\tr := NewRegistry()\n\tc := NewComponent(\"cloud\", \"\", \"\")\n\n\terr := r.Add(nil)\n\tassert.Equal(t, errors.New(\"Nil given\"), err)\n\n\terr = r.Add(c)\n\tassert.Equal(t, errors.New(\"Neither alias nor identifier set\"), err)\n\n\tc1 := NewComponent(\"cloud\", \"foo\", \"bar\")\n\terr = r.Add(c1)\n\tassert.Equal(t, nil, err)\n\n\terr = r.Add(c1)\n\tassert.Equal(t, errors.New(\"Alias bar already exists\"), err)\n\n\tc2 := NewComponent(\"cloud\", \"foo\", \"\")\n\terr = r.Add(c2)\n\tassert.Equal(t, nil, err)\n\n\terr = r.Add(c2)\n\tassert.Equal(t, errors.New(\"Identifier foo already exists\"), err)\n}"} {"input": "package nwo\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n)\n\ntype Command interface {\n\tArgs() []string\n\tSessionName() string\n}\n\ntype Enver interface {\n\tEnv() []string\n}\n\ntype WorkingDirer interface {\n\tWorkingDir() string\n}\n\nfunc ConnectsToOrderer(c Command) bool {\n\tfor _, arg := range c.Args() {\n\t\tif arg == \"--orderer\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\nfunc NewCommand(path string, command Command) *exec.Cmd {\n\tcmd := exec.Command(path, command.Args()...)\n\tcmd.Env = os.Environ()\n\tif ce, ok := command.(Enver); ok {\n\t\tcmd.Env = append(cmd.Env, ce.Env()...)\n\t}\n\tif wd, ok := command.(WorkingDirer); ok {\n\t\tcmd.Dir = wd.WorkingDir()\n\t}\n\treturn cmd\n}\n\nfunc ClientAuthEnabled(c Command) bool ", "output": "{\n\tfor _, arg := range c.Args() {\n\t\tif arg == \"--clientauth\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package gridq\n\ntype byColRow []*WriteResponse\n\nfunc (p byColRow) Len() int { return len(p) }\nfunc (p byColRow) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p byColRow) Less(i, j int) bool {\n\tif p[i].Col < p[j].Col {\n\t\treturn true\n\t} else if p[i].Col > p[j].Col {\n\t\treturn false\n\t} else {\n\t\treturn p[i].Row < p[j].Row\n\t}\n}\n\ntype byRowTimestamp []*ReadResponse\n\nfunc (p byRowTimestamp) Len() int { return len(p) }\nfunc (p byRowTimestamp) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p byRowTimestamp) Less(i, j int) bool {\n\tif p[i].Row < p[j].Row {\n\t\treturn true\n\t} else if p[i].Row > p[j].Row {\n\t\treturn false\n\t} else {\n\t\treturn p[i].State.Timestamp > p[j].State.Timestamp\n\t}\n}\n\ntype byTimestamp []*ReadResponse\n\nfunc (p byTimestamp) Len() int { return len(p) }\nfunc (p byTimestamp) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\n\n\nfunc (p byTimestamp) Less(i, j int) bool ", "output": "{ return p[i].State.Timestamp < p[j].State.Timestamp }"} {"input": "package types\n\nimport (\n\t\"testing\"\n)\n\nfunc TestHstoreNew(t *testing.T) {\n\ttext := `\"name\"=>\"test\", \"ext\"=>\"\", \"size\"=>\"34508\", \"nov\"=>NULL`\n\n\tvar h = make(Hstore)\n\terr := h.Scan(text)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tt.Log(h)\n\n\tvalid_s := \"34508\"\n\n\tif h[\"size\"] != valid_s {\n\t\tt.Fatalf(\"unexpected result:\\n+ %v\\n- %v\", h[\"size\"], valid_s)\n\t}\n}\n\ntype testPerson struct {\n\tName string\n\tAge uint16\n}\n\n\n\nfunc TestStructToHstore(t *testing.T) ", "output": "{\n\ti := testPerson{\"test name\", uint16(23)}\n\th := StructToHstore(i)\n\n\tt.Log(h)\n\n\tif h[\"name\"] != i.Name {\n\t\tt.Fatalf(\"unexpected result:\\n+ %v\\n- %v\", h[\"name\"], i.Name)\n\t}\n\tif h[\"age\"] != i.Age {\n\t\tt.Fatalf(\"unexpected result:\\n+ %v\\n- %v\", h[\"age\"], i.Age)\n\t}\n}"} {"input": "package main\n\nfunc f1(i int) {\n\tfor j := i - 1; j >= 0; j-- { \n\t}\n}\n\nfunc f2(i int, s string) {\n\tfor j := i + 1; j < len(s); j-- { \n\t}\n}\n\n\n\nfunc f4(lower int, a []int) {\n\tfor i := lower - 1; i >= 0; i-- { \n\t\ta[i] = 0\n\t}\n}\n\nfunc f5(upper int, a []int) {\n\tfor i := upper + 1; i < len(a); i-- { \n\t\ta[i] = 0\n\t}\n}\n\nfunc f6(upper uint, a []int) {\n\tfor i := upper + 1; i < uint(len(a)); i-- { \n\t\ta[i] = 0\n\t}\n}\n\nfunc f7(a []int) {\n\tfor i := uint(len(a)) - 1; i < uint(len(a)); i-- { \n\t\ta[i] = 0\n\t}\n}\n\nfunc main() {}\n\nfunc f3(s string) ", "output": "{\n\tfor i, l := 0, len(s); i > l; i++ { \n\t}\n}"} {"input": "package main\n\nimport \"testing\"\n\n\n\nfunc BenchmarkP041B(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tp041B()\n\t}\n}\n\nfunc ExampleP041() {\n\tmain()\n\n}\n\nfunc BenchmarkP041A(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tp041A()\n\t}\n}"} {"input": "package masking\n\nimport (\n\t\"bytes\"\n\t\"github.com/cossacklabs/acra/decryptor/base\"\n\t\"github.com/cossacklabs/acra/encryptor\"\n\t\"github.com/cossacklabs/acra/logging\"\n)\n\n\ntype Processor struct{ decryptor base.ExtendedDataProcessor }\n\n\n\n\n\nfunc (processor *Processor) Process(data []byte, context *base.DataProcessorContext) ([]byte, error) {\n\tlogger := logging.GetLoggerFromContext(context.Context).WithField(\"processor\", \"masking\")\n\tlogger.Debugln(\"Processing masking\")\n\tsetting, ok := encryptor.EncryptionSettingFromContext(context.Context)\n\tif ok && setting.GetMaskingPattern() != \"\" {\n\t\tlogger.Debugln(\"Has pattern\")\n\t\tnewData, err := processor.decryptor.Process(data, context)\n\t\tif err != nil || bytes.Equal(newData, data) {\n\t\t\tlogger.Debugln(\"Mask data\")\n\t\t\treturn []byte(setting.GetMaskingPattern()), nil\n\t\t}\n\t\tlogger.Debugln(\"Return decrypted\")\n\t\treturn newData, nil\n\t}\n\treturn processor.decryptor.Process(data, context)\n}\n\nfunc NewProcessor(decryptor base.ExtendedDataProcessor) (*Processor, error) ", "output": "{\n\treturn &Processor{decryptor: decryptor}, nil\n}"} {"input": "package s3\n\nimport (\n\t\"github.com/djbarber/ipfs-hack/Godeps/_workspace/src/github.com/crowdmob/goamz/aws\"\n)\n\nvar originalStrategy = attempts\n\nfunc SetAttemptStrategy(s *aws.AttemptStrategy) {\n\tif s == nil {\n\t\tattempts = originalStrategy\n\t} else {\n\t\tattempts = *s\n\t}\n}\n\n\n\nfunc SetListPartsMax(n int) {\n\tlistPartsMax = n\n}\n\nfunc SetListMultiMax(n int) {\n\tlistMultiMax = n\n}\n\nfunc Sign(auth aws.Auth, method, path string, params, headers map[string][]string) ", "output": "{\n\tsign(auth, method, path, params, headers)\n}"} {"input": "package esicache\n\nimport (\n\t\"context\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/corestoreio/errors\"\n)\n\n\n\n\ntype Cacher interface {\n\tSet(key string, value []byte, expiration time.Duration) error\n\tGet(key string) ([]byte, error)\n}\n\n\n\nfunc NewCacher(url string) (Cacher, error) {\n\n\treturn nil, nil\n}\n\n\ntype Caches []Cacher\n\n\n\n\n\nfunc (c Caches) Get(key string) ([]byte, error) {\n\treturn nil, nil\n}\n\n\nvar MainRegistry = ®istry{\n\tcaches: make(map[string]Caches),\n}\n\ntype registry struct {\n\tmu sync.RWMutex\n\tcaches map[string]Caches\n}\n\nfunc (r *registry) Get(ctx context.Context, scope, alias, key string) error {\n\treturn errors.New(\"TODO IMPLEMENT\")\n}\n\n\n\n\nfunc (r *registry) Register(scope, url string) error {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\n\tc, err := NewCacher(url)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"[esikv] NewCacher URL %q\", url)\n\t}\n\n\tif _, ok := r.caches[scope]; !ok {\n\t\tr.caches[scope] = make(Caches, 0, 2)\n\t}\n\tr.caches[scope] = append(r.caches[scope], c)\n\n\treturn nil\n}\n\n\nfunc (r *registry) Len(scope string) int {\n\tr.mu.RLock()\n\tdefer r.mu.RUnlock()\n\treturn len(r.caches[scope])\n}\n\n\nfunc (r *registry) Clear() {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\tr.caches = make(map[string]Caches)\n}\n\nfunc (c Caches) Set(key string, value []byte, expiration time.Duration) error ", "output": "{\n\treturn nil\n}"} {"input": "package common\n\nimport (\n\t\"bytes\"\n\n\t\"k8s.io/kubernetes/pkg/api\"\n)\n\n\ntype Endpoint struct {\n\tHost string `json:\"host\"`\n\n\tPorts []ServicePort `json:\"ports\"`\n}\n\n\n\n\n\n\nfunc GetInternalEndpoint(serviceName, namespace string, ports []api.ServicePort) Endpoint {\n\tname := serviceName\n\n\tif namespace != api.NamespaceDefault && len(namespace) > 0 && len(serviceName) > 0 {\n\t\tbufferName := bytes.NewBufferString(name)\n\t\tbufferName.WriteString(\".\")\n\t\tbufferName.WriteString(namespace)\n\t\tname = bufferName.String()\n\t}\n\n\treturn Endpoint{\n\t\tHost: name,\n\t\tPorts: GetServicePorts(ports),\n\t}\n}\n\n\nfunc getExternalEndpoint(ingress api.LoadBalancerIngress, ports []api.ServicePort) Endpoint {\n\tvar host string\n\tif ingress.Hostname != \"\" {\n\t\thost = ingress.Hostname\n\t} else {\n\t\thost = ingress.IP\n\t}\n\treturn Endpoint{\n\t\tHost: host,\n\t\tPorts: GetServicePorts(ports),\n\t}\n}\n\n\nfunc GetNodeByName(nodes []api.Node, nodeName string) *api.Node {\n\tfor _, node := range nodes {\n\t\tif node.ObjectMeta.Name == nodeName {\n\t\t\treturn &node\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc GetExternalEndpoints(service *api.Service) []Endpoint ", "output": "{\n\tvar externalEndpoints []Endpoint\n\tif service.Spec.Type == api.ServiceTypeLoadBalancer {\n\t\tfor _, ingress := range service.Status.LoadBalancer.Ingress {\n\t\t\texternalEndpoints = append(externalEndpoints, getExternalEndpoint(ingress, service.Spec.Ports))\n\t\t}\n\t}\n\n\tfor _, ip := range service.Spec.ExternalIPs {\n\t\texternalEndpoints = append(externalEndpoints, Endpoint{\n\t\t\tHost: ip,\n\t\t\tPorts: GetServicePorts(service.Spec.Ports),\n\t\t})\n\t}\n\n\treturn externalEndpoints\n}"} {"input": "package check\n\n\ntype GoFmt struct {\n\tDir string\n\tFilenames []string\n}\n\n\nfunc (g GoFmt) Name() string {\n\treturn \"gofmt\"\n}\n\n\nfunc (g GoFmt) Weight() float64 {\n\treturn .35\n}\n\n\n\n\n\nfunc (g GoFmt) Description() string {\n\treturn `Gofmt formats Go programs. We run gofmt -s on your code, where -s is for the \"simplify\" command`\n}\n\nfunc (g GoFmt) Percentage() (float64, []FileSummary, error) ", "output": "{\n\treturn GoTool(g.Dir, g.Filenames, []string{\"gofmt\", \"-s\", \"-l\"})\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\n\n\nfunc main() {\n\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tfor i := 1; i <= 10; i++ {\n\t\tprintNumber(i, r)\n\t}\n\tfmt.Scanln()\n}\n\nfunc printNumber(number int, randomGenerator *rand.Rand) ", "output": "{\n\ttimeToWait := time.Duration((randomGenerator.Int() % 3000) + 1000)\n\ttime.Sleep(timeToWait * time.Millisecond)\n\tfmt.Printf(\"%3d\\tWaited %d ms\\n\", number, timeToWait)\n}"} {"input": "package mutate\n\nimport (\n\tv1 \"github.com/google/go-containerregistry/pkg/v1\"\n\t\"github.com/google/go-containerregistry/pkg/v1/empty\"\n\t\"github.com/google/go-containerregistry/pkg/v1/mutate\"\n\t\"github.com/sigstore/cosign/pkg/oci\"\n)\n\n\n\n\n\n\n\nfunc ReplaceSignatures(base oci.Signatures) (oci.Signatures, error) {\n\tsigs, err := base.Get()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tadds := make([]mutate.Addendum, 0, len(sigs))\n\tfor _, sig := range sigs {\n\t\tann, err := sig.Annotations()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tadds = append(adds, mutate.Addendum{\n\t\t\tLayer: sig,\n\t\t\tAnnotations: ann,\n\t\t})\n\t}\n\timg, err := mutate.Append(empty.Image, adds...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &sigAppender{\n\t\tImage: img,\n\t\tbase: base,\n\t\tsigs: sigs,\n\t}, nil\n}\n\ntype sigAppender struct {\n\tv1.Image\n\tbase oci.Signatures\n\tsigs []oci.Signature\n}\n\nvar _ oci.Signatures = (*sigAppender)(nil)\n\n\nfunc (sa *sigAppender) Get() ([]oci.Signature, error) {\n\tsl, err := sa.base.Get()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn append(sl, sa.sigs...), nil\n}\n\nfunc AppendSignatures(base oci.Signatures, sigs ...oci.Signature) (oci.Signatures, error) ", "output": "{\n\tadds := make([]mutate.Addendum, 0, len(sigs))\n\tfor _, sig := range sigs {\n\t\tann, err := sig.Annotations()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tadds = append(adds, mutate.Addendum{\n\t\t\tLayer: sig,\n\t\t\tAnnotations: ann,\n\t\t})\n\t}\n\timg, err := mutate.Append(base, adds...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &sigAppender{\n\t\tImage: img,\n\t\tbase: base,\n\t\tsigs: sigs,\n\t}, nil\n}"} {"input": "package file\n\nimport (\n\t\"os/exec\"\n\t\"io/ioutil\"\n\t\"os\"\n)\n\n\n\nfunc ExecWithEnv(cmd string, args []string, env []string) (string, string, error) {\n\tcommand := exec.Command(cmd, args...)\n\tcommand.Env = env\n\n\tcmdOut, _ := command.StdoutPipe()\n\tcmdErr, _ := command.StderrPipe()\n\n\terr := command.Start()\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\tstdOutput, err := ioutil.ReadAll(cmdOut)\n\terrOutput, err := ioutil.ReadAll(cmdErr)\n\n\treturn string(stdOutput), string(errOutput), err\n}\n\nfunc Exec(cmd string, args ...string) (string, string, error) ", "output": "{\n\treturn ExecWithEnv(cmd, args, os.Environ())\n}"} {"input": "package geetplaban\n\nimport \"sync/atomic\"\n\ntype NextIdGetter struct {\n\tnext_id *uint32\n}\n\n\n\nfunc (next *NextIdGetter) NextId() uint {\n\tnext_id := atomic.AddUint32(next.next_id, 1)\n\treturn uint(next_id)\n}\n\nfunc NewNextIdGettr(initial_value uint32) *NextIdGetter ", "output": "{\n\tx := new(uint32)\n\t*x = initial_value\n\n\treturn &NextIdGetter{x}\n}"} {"input": "package veritas_models\n\nimport (\n\t\"sort\"\n\t\"strconv\"\n\n\t\"github.com/cloudfoundry-incubator/bbs/models\"\n)\n\ntype VeritasLRP struct {\n\tProcessGuid string\n\tDesiredLRP *models.DesiredLRP\n\tActualLRPGroupsByIndex map[string]*models.ActualLRPGroup\n}\n\n\n\ntype ByNumericalValue []string\n\nfunc (a ByNumericalValue) Len() int { return len(a) }\nfunc (a ByNumericalValue) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a ByNumericalValue) Less(i, j int) bool {\n\tai, _ := strconv.Atoi(a[i])\n\taj, _ := strconv.Atoi(a[j])\n\n\treturn ai < aj\n}\n\nfunc (l *VeritasLRP) OrderedActualLRPIndices() []string ", "output": "{\n\tindicesAsStrings := []string{}\n\tfor index := range l.ActualLRPGroupsByIndex {\n\t\tindicesAsStrings = append(indicesAsStrings, index)\n\t}\n\n\tsort.Sort(ByNumericalValue(indicesAsStrings))\n\treturn indicesAsStrings\n}"} {"input": "package streaming\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype DeleteStreamPoolRequest struct {\n\n\tStreamPoolId *string `mandatory:\"true\" contributesTo:\"path\" name:\"streamPoolId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteStreamPoolRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\n\n\n\nfunc (request DeleteStreamPoolRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request DeleteStreamPoolRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteStreamPoolResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response DeleteStreamPoolResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response DeleteStreamPoolResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request DeleteStreamPoolRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}"} {"input": "package helpers\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"runtime\"\n)\n\nfunc GetFixturePath(name string) string {\n\t_, filename, _, _ := runtime.Caller(0)\n\n\tfixturePath := path.Join(path.Dir(filename), \"..\", \"fixtures\", name)\n\n\t_, err := os.Stat(fixturePath)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn fixturePath\n}\n\nfunc ReadFixtureBytes(name string) []byte {\n\tpath := GetFixturePath(name)\n\tcontents, err := ioutil.ReadFile(path)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn contents\n}\n\n\n\nfunc ReadFixtureString(name string) string ", "output": "{\n\treturn string(ReadFixtureBytes(name))\n}"} {"input": "package metrics\n\nimport \"github.com/PagerDuty/godspeed\"\n\nvar Metric Metrics = BlackHole{}\n\ntype Metrics interface {\n\tCount(stat string, count float64, tags []string) error\n\tSet(stat string, value float64, tags []string) error\n}\n\ntype BlackHole struct{}\n\nfunc (b BlackHole) Count(stat string, count float64, tags []string) error {\n\treturn nil\n}\n\n\n\ntype GodSpeed struct {\n\tIP string\n\tPort int\n\tNameSpace string\n}\n\nfunc (b *GodSpeed) newConn() (*godspeed.Godspeed, error) {\n\tgs, err := godspeed.New(b.IP, b.Port, false)\n\tif err != nil {\n\t\treturn gs, err\n\t}\n\tgs.Namespace = b.NameSpace\n\n\treturn gs, err\n}\n\nfunc (b *GodSpeed) Count(stat string, count float64, tags []string) error {\n\tc, err := b.newConn()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer c.Conn.Close()\n\treturn c.Count(stat, count, tags)\n}\n\nfunc (b *GodSpeed) Set(stat string, value float64, tags []string) error {\n\tc, err := b.newConn()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer c.Conn.Close()\n\treturn c.Set(stat, value, tags)\n}\n\nfunc (b BlackHole) Set(stat string, value float64, tags []string) error ", "output": "{\n\treturn nil\n}"} {"input": "package gospell\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n)\n\ntype Match struct {\n\tWord []rune\n\tDistance int\n\tWeight int\n}\n\ntype Matches []Match\n\nfunc (m1 Match) Equal(m2 Match) bool {\n\treturn string(m1.Word) == string(m2.Word) &&\n\t\tm1.Distance == m2.Distance && m1.Weight == m2.Weight\n}\n\nfunc (m Match) String() string {\n\treturn fmt.Sprintf(\"{%v %d %d}\", string(m.Word), m.Distance, m.Weight)\n}\n\nfunc (s Matches) Len() int { return len(s) }\nfunc (s Matches) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\n\nfunc (s Matches) Strings() []string {\n\tstrings := make([]string, len(s))\n\tsort.Sort(ByDistance{s})\n\tfor i, r := range s {\n\t\tstrings[i] = string(r.Word)\n\t}\n\n\treturn strings\n}\n\ntype ByDistance struct {\n\tMatches\n}\n\n\n\nfunc (m *Match) update(r rune, distance, weight int) Match {\n\tm2 := Match{}\n\tif r != 0 {\n\t\tm2.Word = []rune{r}\n\t\tm2.Word = append(m2.Word, m.Word...)\n\t} else {\n\t\tm2.Word = m.Word[:]\n\t}\n\tm2.Distance = m.Distance + distance\n\tm2.Weight = m.Weight + weight\n\treturn m2\n}\n\nfunc (s ByDistance) Less(i, j int) bool ", "output": "{\n\td1 := s.Matches[i].Distance\n\td2 := s.Matches[j].Distance\n\tif d1 == d2 {\n\t\treturn string(s.Matches[i].Word) < string(s.Matches[j].Word)\n\t}\n\treturn d1 < d2\n}"} {"input": "package gc\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\n\nfunc lookup(refs map[string][]string) func(id string) []string {\n\treturn func(ref string) []string {\n\t\treturn refs[ref]\n\t}\n}\n\nfunc TestTricolorBasic(t *testing.T) ", "output": "{\n\troots := []string{\"A\", \"C\"}\n\tall := []string{\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\"}\n\trefs := map[string][]string{\n\t\t\"A\": {\"B\"},\n\t\t\"B\": {\"A\"},\n\t\t\"C\": {\"D\", \"F\", \"B\"},\n\t\t\"E\": {\"F\", \"G\"},\n\t}\n\n\tunreachable := Tricolor(roots, all, lookup(refs))\n\texpected := []string{\"E\", \"G\"}\n\n\tif !reflect.DeepEqual(unreachable, expected) {\n\t\tt.Fatalf(\"incorrect unreachable set: %v != %v\", unreachable, expected)\n\t}\n}"} {"input": "package behaviors\n\n\n\n\n\nimport (\n\t\"github.com/tideland/golib/cells\"\n\t\"github.com/tideland/golib/logger\"\n)\n\n\n\n\n\n\ntype CallbackFunc func(topic string, payload cells.Payload) error\n\n\n\ntype callbackBehavior struct {\n\tctx cells.Context\n\tcallbackFuncs []CallbackFunc\n}\n\n\n\n\nfunc NewCallbackBehavior(cbfs ...CallbackFunc) cells.Behavior {\n\tif len(cbfs) == 0 {\n\t\tlogger.Errorf(\"callback created without callback functions\")\n\t}\n\treturn &callbackBehavior{nil, cbfs}\n}\n\n\n\n\n\nfunc (b *callbackBehavior) Terminate() error {\n\treturn nil\n}\n\n\nfunc (b *callbackBehavior) ProcessEvent(event cells.Event) error {\n\tfor _, callbackFunc := range b.callbackFuncs {\n\t\tif err := callbackFunc(event.Topic(), event.Payload()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (b *callbackBehavior) Recover(err interface{}) error {\n\treturn nil\n}\n\nfunc (b *callbackBehavior) Init(ctx cells.Context) error ", "output": "{\n\tb.ctx = ctx\n\treturn nil\n}"} {"input": "package oci\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/phoenix-io/phoenix-mon/plugins\"\n\tps \"github.com/shirou/gopsutil/process\"\n\t\"io/ioutil\"\n)\n\ntype OCI struct {\n\tprocess []plugin.Process\n\tcount\tint\n}\n\ntype PState struct {\n\tID string `json:\"id\"`\n\tPid int `json:\"init_process_pid\"`\n}\n\nfunc init() {\n\tplugin.Register(\"oci\", &plugin.RegisteredPlugin{New: NewPlugin})\n}\n\nfunc NewPlugin(pluginName string) (plugin.Plugin, error) {\n\treturn &OCI{}, nil\n}\n\n\n\nfunc (p *OCI) GetProcessStat(process plugin.Process) (plugin.Process, error) {\n\tres, err := ps.NewProcess(int32(process.Pid))\n\tif err != nil {\n\t\tfmt.Println(\"Unable to Create Process Object\")\n\t}\n\tmemInfo, err := res.MemoryInfo()\n\tif err != nil {\n\t\treturn process, fmt.Errorf(\"geting ppid error %v\", err)\n\n\t}\n\tprocess.Memory = memInfo.RSS\n\treturn process, nil\n}\n\nfunc (p *OCI) GetProcessList() ([]plugin.Process, error) ", "output": "{\n\n\tvar state PState\n\tcontainers, _ := ioutil.ReadDir(\"/run/oci/\")\n\tfor _, c := range containers {\n\t\tdata, err := ioutil.ReadFile(\"/run/oci/\" + c.Name() + \"/state.json\")\n\t\tif err != nil {\n\t\t\treturn p.process, fmt.Errorf(\"Error in reading file\")\n\t\t}\n\n\t\tjson.Unmarshal(data, &state)\n\t\tname := fmt.Sprintf(\"%s %d\",state.ID,p.count)\n\t\tp.count++\n\t\tp.process = append(p.process, plugin.Process{Pid: state.Pid, Name: name})\n\t}\n\n\treturn p.process, nil\n}"} {"input": "package desk\n\nimport (\n \"github.com/stianeikeland/go-rpio\"\n)\n\ntype Direction uint8\n\nvar (\n upPin rpio.Pin\n downPin rpio.Pin\n)\n\nconst (\n Down Direction = iota\n Up\n)\n\nfunc Move(dir Direction) {\n Stop()\n if (dir == Up) {\n upPin.High()\n } else {\n downPin.High()\n }\n}\n\nfunc Stop() {\n upPin.Low()\n downPin.Low()\n}\n\n\n\nfunc Close() {\n rpio.Close()\n}\n\nfunc Init(up int, down int) (err error) ", "output": "{\n err = rpio.Open()\n\n if (err != nil) {\n return\n }\n\n upPin = rpio.Pin(up)\n upPin.Output()\n upPin.Low()\n\n downPin = rpio.Pin(down)\n downPin.Output()\n downPin.Low()\n\n return nil\n}"} {"input": "package timer\n\nimport (\n\t\"time\"\n)\n\ntype typeAction int\n\nconst (\n\tCLOSE typeAction = iota\n\tRESET\n\tFORCE\n)\n\n\n\ntype Timer struct {\n\tinterval time.Duration\n\tmsg, resp chan typeAction\n}\n\n\n\n\nfunc NewTimer(interval time.Duration) *Timer {\n\treturn &Timer{\n\t\tinterval: interval,\n\t\tmsg: make(chan typeAction, 1),\n\t\tresp: make(chan typeAction, 1),\n\t}\n}\n\n\n\n\nfunc (self *Timer) Next() bool {\n\tfor {\n\t\tvar ch <-chan time.Time\n\t\tif self.interval <= 0 {\n\t\t\tch = nil\n\t\t} else {\n\t\t\tch = time.After(self.interval)\n\t\t}\n\t\tselect {\n\t\tcase action := <-self.msg:\n\t\t\tswitch action {\n\t\t\tcase CLOSE:\n\t\t\t\tself.resp <- CLOSE\n\t\t\t\treturn false\n\t\t\tcase FORCE:\n\t\t\t\treturn true\n\t\t\t}\n\t\tcase <-ch:\n\t\t\treturn true\n\t\t}\n\t}\n\tpanic(\"unreachable\")\n}\n\n\n\nfunc (self *Timer) SetInterval(ns time.Duration) {\n\tself.interval = ns\n\tself.msg <- RESET\n}\n\n\n\n\n\n\nfunc (self *Timer) TriggerAfter(ns time.Duration) {\n\tgo func() {\n\t\t<-time.After(ns)\n\t\tself.Trigger()\n\t}()\n}\n\n\n\n\nfunc (self *Timer) Close() {\n\tself.msg <- CLOSE\n\t<-self.resp\n}\n\nfunc (self *Timer) Trigger() ", "output": "{\n\tself.msg <- FORCE\n}"} {"input": "package realtime\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/gorilla/websocket\"\n)\n\ntype objectVersions map[key]int64 \n\ntype User struct {\n\tmut sync.Mutex \n\tConnected bool\n\tID string\n\tuptime time.Time\n\tconn *websocket.Conn\n\tversions objectVersions\n\tpending []*update\n}\n\n\n\nfunc (u *User) sendPending() ", "output": "{\n\tu.mut.Lock()\n\tif len(u.pending) > 0 {\n\t\tu.conn.WriteJSON(u.pending)\n\t\tu.pending = nil\n\t}\n\tu.mut.Unlock()\n}"} {"input": "package glu\n\nvar _Perspective func(fovy, aspect, near, far float64)\nvar _LookAt func(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ float64)\n\nfunc RegisterPerspective(fn func(fovy, aspect, near, far float64)) {\n\t_Perspective = fn\n}\n\nfunc RegisterLookAt(fn func(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ float64)) {\n\t_LookAt = fn\n}\n\n\n\nfunc LookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ float64) {\n\tif _LookAt == nil {\n\t\tpanic(\"Please register a LookAt with glu.RegisterLookAt\")\n\t}\n\n\t_LookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ)\n}\n\nfunc Perspective(fovy, aspect, near, far float64) ", "output": "{\n\tif _Perspective == nil {\n\t\tpanic(\"Please register a Perspective with glu.RegisterPespective\")\n\t}\n\n\t_Perspective(fovy, aspect, near, far)\n}"} {"input": "package media\n\nimport \"github.com/Azure/azure-sdk-for-go/version\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc Version() string {\n\treturn version.Number\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn \"Azure-SDK-For-Go/\" + version.Number + \" media/2018-06-01-preview\"\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\nfunc theme(value string) (string, http.HandlerFunc) {\n\tif filepath.Ext(value) == \".css\" {\n\t\tcssPath, err := filepath.Abs(value)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error finding custom theme: %s: %s. Falling back to: %s.\", value, err.Error(), DefaultTheme)\n\t\t\treturn themePath(DefaultTheme), nil\n\t\t}\n\n\t\tif stat, err := os.Stat(cssPath); err == nil && !stat.IsDir() {\n\t\t\thandler := func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\thttp.ServeFile(w, r, cssPath)\n\t\t\t}\n\t\t\treturn themePath(\"custom\"), handler\n\t\t}\n\n\t\tlog.Printf(\"Error finding custom theme: %s. Falling back to: %s.\", value, DefaultTheme)\n\t\treturn themePath(DefaultTheme), nil\n\t}\n\n\tlocalPath := themeAssetPath(value)\n\t_, err := Asset(localPath)\n\tif err != nil {\n\t\tlog.Printf(\"Invalid theme selected: %s. Falling back to: %s.\", value, DefaultTheme)\n\t\treturn themePath(DefaultTheme), nil\n\t}\n\n\treturn themePath(value), nil\n}\n\nfunc themePath(value string) string {\n\treturn fmt.Sprintf(\"/assets/themes/%s.css\", value)\n}\n\n\n\nfunc themeAssetPath(value string) string ", "output": "{\n\treturn fmt.Sprintf(\"assets/themes/%s.css\", value)\n}"} {"input": "package platform\n\nimport (\n\t\"runtime\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\nvar (\n\tArchitecture string\n\tOSType string\n)\n\n\n\nfunc init() ", "output": "{\n\tvar err error\n\tArchitecture, err = runtimeArchitecture()\n\tif err != nil {\n\t\tlogrus.Errorf(\"Could not read system architecture info: %v\", err)\n\t}\n\tOSType = runtime.GOOS\n}"} {"input": "package auth0\n\nimport (\n\t\"github.com/GoogleCloudPlatform/terraformer/terraformutils\"\n\t\"gopkg.in/auth0.v5/management\"\n)\n\nvar (\n\tClientAllowEmptyValues = []string{}\n)\n\ntype ClientGenerator struct {\n\tAuth0Service\n}\n\nfunc (g ClientGenerator) createResources(clients []*management.Client) []terraformutils.Resource {\n\tresources := []terraformutils.Resource{}\n\tfor _, client := range clients {\n\t\tresourceName := *client.ClientID\n\t\tresources = append(resources, terraformutils.NewSimpleResource(\n\t\t\tresourceName,\n\t\t\tresourceName+\"_\"+*client.Name,\n\t\t\t\"auth0_client\",\n\t\t\t\"auth0\",\n\t\t\tClientAllowEmptyValues,\n\t\t))\n\t}\n\treturn resources\n}\n\n\n\nfunc (g *ClientGenerator) InitResources() error ", "output": "{\n\tm := g.generateClient()\n\tlist := []*management.Client{}\n\n\tvar page int\n\tfor {\n\t\tl, err := m.Client.List(management.Page(page))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlist = append(list, l.Clients...)\n\t\tif !l.HasNext() {\n\t\t\tbreak\n\t\t}\n\t\tpage++\n\t}\n\n\tg.Resources = g.createResources(list)\n\treturn nil\n}"} {"input": "package dory\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n)\n\nconst (\n\tmemAvailablePrefix = \"MemAvailable:\"\n)\n\nfunc getMemAvailable() int64 {\n\tr, err := os.Open(\"/proc/meminfo\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer r.Close()\n\n\tmemAvailable := int64(0)\n\tbufr := bufio.NewReader(r)\n\tfor {\n\t\tline, err := bufr.ReadString('\\n')\n\t\tif strings.HasPrefix(line, memAvailablePrefix) {\n\t\t\tremain := strings.TrimSpace(line[len(memAvailablePrefix):])\n\t\t\tvar units string\n\t\t\t_, err = fmt.Sscanf(remain, \"%d %s\", &memAvailable, &units)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tif units == \"kB\" {\n\t\t\t\tmemAvailable *= 1024\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn memAvailable\n}\n\n\n\n\n\n\n\nfunc AvailableMemory(minFree int64, maxUtilisation float64) MemFunc ", "output": "{\n\treturn func(usage int64) int64 {\n\t\treturn int64(float64(getMemAvailable())*maxUtilisation) + usage - minFree\n\t}\n}"} {"input": "package keymutex\n\nimport (\n\t\"hash/fnv\"\n\t\"runtime\"\n\t\"sync\"\n)\n\n\n\n\n\n\nfunc NewHashed(n int) KeyMutex {\n\tif n <= 0 {\n\t\tn = runtime.NumCPU()\n\t}\n\treturn &hashedKeyMutex{\n\t\tmutexes: make([]sync.Mutex, n),\n\t}\n}\n\ntype hashedKeyMutex struct {\n\tmutexes []sync.Mutex\n}\n\n\nfunc (km *hashedKeyMutex) LockKey(id string) {\n\tkm.mutexes[km.hash(id)%len(km.mutexes)].Lock()\n}\n\n\nfunc (km *hashedKeyMutex) UnlockKey(id string) error {\n\tkm.mutexes[km.hash(id)%len(km.mutexes)].Unlock()\n\treturn nil\n}\n\n\n\nfunc (km *hashedKeyMutex) hash(id string) int ", "output": "{\n\th := fnv.New32a()\n\th.Write([]byte(id))\n\treturn int(h.Sum32())\n}"} {"input": "package auth\n\nimport (\n\t\"errors\"\n\t\"sync\"\n)\n\ntype Users struct {\n\tsync.RWMutex\n\n\tList []*User\n\n\tlastID int64\n}\n\n\n\nfunc (u *Users) Create(user *User) {\n\tu.Lock()\n\tdefer u.Unlock()\n\n\tu.lastID++\n\tuser.ID = u.lastID\n\n\tu.List = append(u.List, user)\n}\n\nfunc (r *Users) Remove(id int64) {\n\tr.Lock()\n\tdefer r.Unlock()\n\n\tfor key, item := range r.List {\n\t\tif item.ID == id {\n\n\t\t\tcopy(r.List[key:], r.List[key+1:])\n\t\t\tr.List[len(r.List)-1] = nil\n\t\t\tr.List = r.List[:len(r.List)-1]\n\n\t\t}\n\t}\n}\n\nfunc (r *Users) Flush() {\n\tr.Lock()\n\tdefer r.Unlock()\n\n\tr.List = []*User{}\n}\n\nfunc (u *Users) Get(id int64) (*User, error) ", "output": "{\n\tu.RLock()\n\tdefer u.RUnlock()\n\n\tfor _, user := range u.List {\n\t\tif user.ID == id {\n\t\t\treturn user, nil\n\t\t}\n\t}\n\treturn nil, errors.New(\"User not found\")\n}"} {"input": "package framework\n\nimport \"github.com/onsi/gomega\"\n\n\nfunc ExpectEqual(actual interface{}, extra interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.Equal(extra), explain...)\n}\n\n\n\n\n\nfunc ExpectError(err error, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, err).To(gomega.HaveOccurred(), explain...)\n}\n\n\nfunc ExpectNoError(err error, explain ...interface{}) {\n\tExpectNoErrorWithOffset(1, err, explain...)\n}\n\n\n\nfunc ExpectNoErrorWithOffset(offset int, err error, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1+offset, err).NotTo(gomega.HaveOccurred(), explain...)\n}\n\n\nfunc ExpectConsistOf(actual interface{}, extra interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.ConsistOf(extra), explain...)\n}\n\n\nfunc ExpectHaveKey(actual interface{}, key interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.HaveKey(key), explain...)\n}\n\n\nfunc ExpectEmpty(actual interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.BeEmpty(), explain...)\n}\n\nfunc ExpectNotEqual(actual interface{}, extra interface{}, explain ...interface{}) ", "output": "{\n\tgomega.ExpectWithOffset(1, actual).NotTo(gomega.Equal(extra), explain...)\n}"} {"input": "package zip\n\nimport (\n\t\"archive/zip\"\n\t\"io\"\n\t\"os\"\n)\n\n\ntype Reader struct {\n\tzip.Reader\n\tunread []*zip.File\n\trc io.ReadCloser\n}\n\n\n\nfunc NewReader(r io.ReaderAt, size int64) (*Reader, error) {\n\tzr, err := zip.NewReader(r, size)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Reader{Reader: *zr}, nil\n}\n\n\n\n\nfunc (r *Reader) Read(p []byte) (n int, err error) {\n\treturn r.rc.Read(p)\n}\n\n\nfunc (r *Reader) Files() []*zip.File {\n\treturn r.File\n}\n\n\ntype Writer struct {\n\tzip.Writer\n\tw io.Writer\n}\n\n\nfunc NewWriter(w io.Writer) *Writer {\n\treturn &Writer{Writer: *zip.NewWriter(w)}\n}\n\n\n\nfunc (w *Writer) NextFile(name string, fi os.FileInfo) error {\n\tif name == \"\" {\n\t\tname = fi.Name()\n\t}\n\thdr, err := zip.FileInfoHeader(fi)\n\tif err != nil {\n\t\treturn err\n\t}\n\thdr.Name = name\n\tw.w, err = w.CreateHeader(hdr)\n\treturn err\n}\n\nfunc (w *Writer) Write(p []byte) (n int, err error) {\n\treturn w.w.Write(p)\n}\n\nfunc (r *Reader) NextFile() (name string, err error) ", "output": "{\n\tif r.unread == nil {\n\t\tr.unread = r.Files()[:]\n\t}\n\n\tif r.rc != nil {\n\t\tr.rc.Close() \n\t}\n\n\tif len(r.unread) == 0 {\n\t\treturn \"\", io.EOF\n\t}\n\n\tf := r.unread[0]\n\tname, r.unread = f.Name, r.unread[1:]\n\tr.rc, err = f.Open()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn name, nil\n}"} {"input": "package web\n\nimport (\n\t\"github.com/cleverua/tuna-timer-api/models\"\n)\n\n\ntype ResponseBody struct {\n\tAppInfo map[string]string `json:\"app_info\"`\n\tResponseStatus *ResponseStatus\t `json:\"response_status\"`\n\tResponseData map[string]string `json:\"data\"`\n}\n\nfunc NewResponseBody(info map[string]string) *ResponseBody{\n\treturn &ResponseBody{\n\t\tResponseStatus: &ResponseStatus{ Status: statusOK },\n\t\tAppInfo: info,\n\t}\n}\n\ntype ResponseStatus struct {\n\tStatus\t\t string `json:\"status\"`\n\tDeveloperMessage string `json:\"developer_message\"`\n\tUserMessage\t string `json:\"user_message\"`\n}\n\n\ntype JWTResponse struct {\n\t*ResponseBody\n\tResponseData JwtToken `json:\"data\"`\n}\n\n\n\n\ntype TimerResponse struct {\n\t*ResponseBody\n\tResponseData models.Timer\t`json:\"data\"`\n}\n\nfunc NewTimerResponse(info map[string]string) *TimerResponse {\n\treturn &TimerResponse{\n\t\tResponseBody: NewResponseBody(info),\n\t}\n}\n\n\ntype TimersResponse struct {\n\t*ResponseBody\n\tResponseData []*models.Timer `json:\"data\"`\n}\n\nfunc NewTimersResponse(info map[string]string) *TimersResponse {\n\treturn &TimersResponse{\n\t\tResponseBody: NewResponseBody(info),\n\t}\n}\n\n\ntype ProjectsResponse struct {\n\t*ResponseBody\n\tResponseData []*models.Project `json:\"data\"`\n}\n\nfunc NewProjectsResponse(info map[string]string) *ProjectsResponse {\n\treturn &ProjectsResponse{\n\t\tResponseBody: NewResponseBody(info),\n\t}\n}\n\n\ntype UserStatisticsResponse struct {\n\t*ResponseBody\n\tResponseData []*models.UserStatisticsAggregation `json:\"data\"`\n}\n\nfunc NewUserStatisticsResponse(info map[string]string) *UserStatisticsResponse {\n\treturn &UserStatisticsResponse{\n\t\tResponseBody: NewResponseBody(info),\n\t}\n}\n\nfunc NewJWTResponse(info map[string]string) *JWTResponse ", "output": "{\n\treturn &JWTResponse{\n\t\tResponseData: JwtToken{},\n\t\tResponseBody: NewResponseBody(info),\n\t}\n}"} {"input": "package api\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\n\ntype Response struct {\n\tResult string `json:\"result\"`\n\tErrorType string `json:\"error_type\"`\n\tMessage string `json:\"message\"`\n\tInfo Info\n\tBody []byte\n}\n\n\ntype Info struct {\n\tSitename string `json:\"sitename\"`\n\tHits int32 `json:\"hits\"`\n\tCreatedAt string `json:\"created_at\"`\n\tLastUpdated string `json:\"last_updated\"`\n\tDomain string `json:\"domain\"`\n\tTags []string `json:\"tags\"`\n}\n\n\nfunc (r *Response) PopulateFromHTTPResponse(res *http.Response) error {\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\terr = json.Unmarshal(body, &r)\n\n\tr.Body = body\n\n\treturn err\n}\n\n\n\n\nfunc (r *Response) Print() ", "output": "{\n\tfmt.Println(\"Result: \", r.Result)\n\n\tif r.ErrorType != \"\" {\n\t\tfmt.Println(\"ErrorType:\", r.ErrorType)\n\t}\n\n\tfmt.Println(\"Message: \", r.Message)\n}"} {"input": "package model\n\nimport \"time\"\n\ntype folder struct {\n\tstateTracker\n\tscan folderscan\n\tmodel *Model\n\tstop chan struct{}\n}\n\nfunc (f *folder) IndexUpdated() {\n}\n\nfunc (f *folder) DelayScan(next time.Duration) {\n\tf.scan.Delay(next)\n}\n\nfunc (f *folder) Scan(subdirs []string) error {\n\treturn f.scan.Scan(subdirs)\n}\nfunc (f *folder) Stop() {\n\tclose(f.stop)\n}\n\nfunc (f *folder) Jobs() ([]string, []string) {\n\treturn nil, nil\n}\n\nfunc (f *folder) BringToFront(string) {}\n\n\n\nfunc (f *folder) scanSubdirsIfHealthy(subDirs []string) error ", "output": "{\n\tif err := f.model.CheckFolderHealth(f.folderID); err != nil {\n\t\tl.Infoln(\"Skipping folder\", f.folderID, \"scan due to folder error:\", err)\n\t\treturn err\n\t}\n\tl.Debugln(f, \"Scanning subdirectories\")\n\tif err := f.model.internalScanFolderSubdirs(f.folderID, subDirs); err != nil {\n\t\tf.setError(err)\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package native\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\n\t\"github.com/docker/docker/pkg/reexec\"\n\t\"github.com/docker/libcontainer\"\n)\n\nfunc init() {\n\treexec.Register(DriverName, initializer)\n}\n\nfunc fatal(err error) {\n\tif lerr, ok := err.(libcontainer.Error); ok {\n\t\tlerr.Detail(os.Stderr)\n\t\tos.Exit(1)\n\t}\n\n\tfmt.Fprintln(os.Stderr, err)\n\tos.Exit(1)\n}\n\n\n\nfunc writeError(err error) {\n\tfmt.Fprint(os.Stderr, err)\n\tos.Exit(1)\n}\n\nfunc initializer() ", "output": "{\n\truntime.GOMAXPROCS(1)\n\truntime.LockOSThread()\n\tfactory, err := libcontainer.New(\"\")\n\tif err != nil {\n\t\tfatal(err)\n\t}\n\tif err := factory.StartInitialization(); err != nil {\n\t\tfatal(err)\n\t}\n\n\tpanic(\"unreachable\")\n}"} {"input": "package problems\n\nimport \"fmt\"\n\nfunc partitionDfs(data []byte, i int, buf *[]string, out *[][]string) {\n\tif i == len(data) {\n\t\tm := make([]string, len(*buf))\n\t\tcopy(m, *buf)\n\t\t*out = append(*out, m)\n\t\treturn\n\t}\n\n\tvar isPalindrome func (data []byte, s int, e int) bool\n\tisPalindrome = func (data []byte, s int, e int) bool {\n\t\ti, j := s, e\n\t\tfor i < j {\n\t\t\tif data[i] != data[j] {\n\t\t\t\treturn false\n\t\t\t} else {\n\t\t\t\ti++\n\t\t\t\tj--\n\t\t\t}\n\t\t}\n\n\t\treturn true\n\t}\n\n\tfor k := i; k < len(data); k++ {\n\t\tif isPalindrome(data, i, k) {\n\t\t\t*buf = append(*buf, string(data[i:k + 1]))\n\t\t\tpartitionDfs(data, k + 1, buf, out)\n\t\t\t*buf = (*buf)[:len(*buf) - 1]\n\t\t}\n\t}\n}\n\n\n\nfunc Partition() {\n\tfmt.Printf(\"<131> \")\n\tfmt.Println(partition(\"aabc\"))\n}\n\nfunc partition(s string) [][]string ", "output": "{\n\tvar buf []string\n\tvar out [][]string\n\n\tpartitionDfs([]byte(s), 0, &buf, &out)\n\n\treturn out\n}"} {"input": "package main\n\nimport \"fmt\"\n\ntype ListNode struct {\n\tVal int\n\tNext *ListNode\n}\n\n\n\n\nfunc main() {\n\tfmt.Println(\"vim-go\")\n}\n\nfunc deleteDuplicates(head *ListNode) *ListNode ", "output": "{\n\tptr := &head\n\n\tfor *ptr != nil {\n\t\tnext := &((*ptr).Next)\n\t\tval := (*ptr).Val\n\t\tif (*next) != nil && val == (*next).Val {\n\t\t\tfor (*ptr) != nil && (*ptr).Val == val {\n\t\t\t\tnext := (*ptr).Next\n\t\t\t\t*ptr = next\n\t\t\t}\n\t\t} else {\n\t\t\tptr = next\n\t\t}\n\t}\n\n\treturn head\n}"} {"input": "package main\n\nimport (\n\t\"code.google.com/p/go.net/websocket\"\n\t\"log\"\n \"strconv\"\n)\n\nconst bufferSize = 100\n\nvar maxId uint64 = 0\n\ntype Client struct {\n\tid uint64\n\tws *websocket.Conn\n\trace *Race\n\tch chan *Message\n}\n\nfunc NewClient(ws *websocket.Conn, race *Race) *Client {\n\tmaxId++\n\tch := make(chan *Message, bufferSize)\n\treturn &Client{maxId, ws, race, ch}\n}\n\nfunc (c *Client) Conn() *websocket.Conn {\n\treturn c.ws\n}\n\nfunc (c *Client) Write(msg *Message) {\n\tselect {\n\tcase c.ch <- msg:\n\tdefault:\n\t\tc.race.Del(c)\n\t\tlog.Println(\"Client\", c.id, \"disconnected\")\n\t}\n}\n\nfunc (c *Client) Listen() {\n\tgo c.listenWrite()\n\tc.listenRead()\n}\n\n\n\nfunc (c *Client) listenRead() {\n\tfor {\n\t\tselect {\n\t\tdefault:\n\t\t\tvar msg Message\n\t\t\tif err := websocket.JSON.Receive(c.ws, &msg);err!=nil{\n if err.Error()==\"EOF\"{\n c.race.Del(c)\n return\n }\n log.Println(\"Unhandled error:\",err)\n return\n }\n\t\t\tlog.Println(c.id, \"got:\", msg)\n\n if msg.Type==\"word\"{\n i,err:=strconv.Atoi(msg.Body)\n if err!=nil{\n log.Println(err)\n continue\n }\n if i>c.race.best{\n c.race.best=i\n c.race.sendAll(&Message{\"best\",msg.Body,c.id})\n }\n }\n\t\t}\n\t}\n}\n\nfunc (c *Client) listenWrite() ", "output": "{\n\tfor {\n\t\tselect {\n\t\tcase msg := <-c.ch:\n\t\t\twebsocket.JSON.Send(c.ws, msg)\n\t\t\tlog.Println(\"Sending to\", c.id, \":\", msg)\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t_ \"github.com/go-training/training/example16-init-func/bar\"\n\t_ \"github.com/go-training/training/example16-init-func/foo\"\n)\n\nvar global = convert()\n\n\n\nfunc init() {\n\tglobal = 0\n}\n\nfunc main() {\n\tfmt.Println(\"global is\", global)\n}\n\nfunc convert() int ", "output": "{\n\treturn 100\n}"} {"input": "package iso20022\n\n\ntype Tax13 struct {\n\n\tType *TaxType9Code `xml:\"Tp\"`\n\n\tOtherTaxType *Max35Text `xml:\"OthrTaxTp\"`\n\n\tAmount *CurrencyAndAmount `xml:\"Amt\"`\n\n\tRate *PercentageRate `xml:\"Rate\"`\n}\n\n\n\nfunc (t *Tax13) SetOtherTaxType(value string) {\n\tt.OtherTaxType = (*Max35Text)(&value)\n}\n\nfunc (t *Tax13) SetAmount(value, currency string) {\n\tt.Amount = NewCurrencyAndAmount(value, currency)\n}\n\nfunc (t *Tax13) SetRate(value string) {\n\tt.Rate = (*PercentageRate)(&value)\n}\n\nfunc (t *Tax13) SetType(value string) ", "output": "{\n\tt.Type = (*TaxType9Code)(&value)\n}"} {"input": "package techcore\n\nimport \"github.com/nsf/termbox-go\"\n\ntype Color int\n\nconst (\n\tColorBlack Color = 1 << iota\n\tColorBlue\n\tColorCyan\n\tColorGreen\n\tColorMagenta\n\tColorRed\n\tColorWhite\n\tColorYellow\n\tColorAlpha\n)\n\n\n\nfunc (c Color) GetTermboxColor() termbox.Attribute ", "output": "{\n\tswitch c {\n\tcase ColorBlack:\n\t\treturn termbox.ColorBlack\n\tcase ColorBlue:\n\t\treturn termbox.ColorBlue\n\tcase ColorCyan:\n\t\treturn termbox.ColorCyan\n\tcase ColorGreen:\n\t\treturn termbox.ColorGreen\n\tcase ColorMagenta:\n\t\treturn termbox.ColorMagenta\n\tcase ColorRed:\n\t\treturn termbox.ColorRed\n\tcase ColorWhite:\n\t\treturn termbox.ColorWhite\n\tcase ColorYellow:\n\t\treturn termbox.ColorYellow\n\tcase ColorAlpha:\n\t\treturn termbox.ColorDefault\n\tdefault:\n\t\treturn termbox.ColorDefault\n\t}\n}"} {"input": "package dockertools\n\nimport (\n\t\"k8s.io/kubernetes/pkg/client/record\"\n\tkubecontainer \"k8s.io/kubernetes/pkg/kubelet/container\"\n\t\"k8s.io/kubernetes/pkg/kubelet/network\"\n\t\"k8s.io/kubernetes/pkg/kubelet/prober\"\n\tkubeletTypes \"k8s.io/kubernetes/pkg/kubelet/types\"\n)\n\n\n\nfunc NewFakeDockerManager(\n\tclient DockerInterface,\n\trecorder record.EventRecorder,\n\treadinessManager *kubecontainer.ReadinessManager,\n\tcontainerRefManager *kubecontainer.RefManager,\n\tpodInfraContainerImage string,\n\tqps float32,\n\tburst int,\n\tcontainerLogsDir string,\n\tosInterface kubecontainer.OSInterface,\n\tnetworkPlugin network.NetworkPlugin,\n\tgenerator kubecontainer.RunContainerOptionsGenerator,\n\thttpClient kubeletTypes.HttpGetter,\n\truntimeHooks kubecontainer.RuntimeHooks) *DockerManager ", "output": "{\n\n\tdm := NewDockerManager(client, recorder, readinessManager, containerRefManager, podInfraContainerImage, qps,\n\t\tburst, containerLogsDir, osInterface, networkPlugin, generator, httpClient, runtimeHooks, &NativeExecHandler{})\n\tdm.puller = &FakeDockerPuller{}\n\tdm.prober = prober.New(nil, readinessManager, containerRefManager, recorder)\n\treturn dm\n}"} {"input": "package threadsafe\n\n\n\nimport (\n\t\"sync\"\n\n\ttc \"github.com/apache/incubator-trafficcontrol/lib/go-tc\"\n)\n\n\nfunc CopyTrafficMonitorConfigMap(a *tc.TrafficMonitorConfigMap) tc.TrafficMonitorConfigMap {\n\tb := tc.TrafficMonitorConfigMap{}\n\tb.TrafficServer = map[string]tc.TrafficServer{}\n\tb.CacheGroup = map[string]tc.TMCacheGroup{}\n\tb.Config = map[string]interface{}{}\n\tb.TrafficMonitor = map[string]tc.TrafficMonitor{}\n\tb.DeliveryService = map[string]tc.TMDeliveryService{}\n\tb.Profile = map[string]tc.TMProfile{}\n\tfor k, v := range a.TrafficServer {\n\t\tb.TrafficServer[k] = v\n\t}\n\tfor k, v := range a.CacheGroup {\n\t\tb.CacheGroup[k] = v\n\t}\n\tfor k, v := range a.Config {\n\t\tb.Config[k] = v\n\t}\n\tfor k, v := range a.TrafficMonitor {\n\t\tb.TrafficMonitor[k] = v\n\t}\n\tfor k, v := range a.DeliveryService {\n\t\tb.DeliveryService[k] = v\n\t}\n\tfor k, v := range a.Profile {\n\t\tb.Profile[k] = v\n\t}\n\treturn b\n}\n\n\ntype TrafficMonitorConfigMap struct {\n\tmonitorConfig *tc.TrafficMonitorConfigMap\n\tm *sync.RWMutex\n}\n\n\nfunc NewTrafficMonitorConfigMap() TrafficMonitorConfigMap {\n\treturn TrafficMonitorConfigMap{monitorConfig: &tc.TrafficMonitorConfigMap{}, m: &sync.RWMutex{}}\n}\n\n\n\n\n\nfunc (t *TrafficMonitorConfigMap) Set(c tc.TrafficMonitorConfigMap) {\n\tt.m.Lock()\n\t*t.monitorConfig = c\n\tt.m.Unlock()\n}\n\nfunc (t *TrafficMonitorConfigMap) Get() tc.TrafficMonitorConfigMap ", "output": "{\n\tt.m.RLock()\n\tdefer t.m.RUnlock()\n\treturn *t.monitorConfig\n}"} {"input": "package transport\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\tma \"gx/ipfs/QmSWLfmj5frN9xVLMMN846dMDriy5wN5jeghUm7aTW3DAG/go-multiaddr\"\n\tmanet \"gx/ipfs/QmVCNGTyD4EkvNYaAp253uMQ9Rjsjy2oGMvcdJJUoVRfja/go-multiaddr-net\"\n\tmafmt \"gx/ipfs/QmYjJnSTfXWhYL2cV1xFphPqjqowJqH7ZKLA1As8QrPHbn/mafmt\"\n)\n\ntype FallbackDialer struct {\n\tmadialer manet.Dialer\n}\n\nfunc (fbd *FallbackDialer) Matches(a ma.Multiaddr) bool {\n\treturn mafmt.TCP.Matches(a)\n}\n\nfunc (fbd *FallbackDialer) Dial(a ma.Multiaddr) (Conn, error) {\n\treturn fbd.DialContext(context.Background(), a)\n}\n\n\n\nfunc (fbd *FallbackDialer) tcpDial(ctx context.Context, raddr ma.Multiaddr) (Conn, error) {\n\tvar c manet.Conn\n\tvar err error\n\tc, err = fbd.madialer.DialContext(ctx, raddr)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &ConnWrap{\n\t\tConn: c,\n\t}, nil\n}\n\nvar _ Dialer = (*FallbackDialer)(nil)\n\nfunc (fbd *FallbackDialer) DialContext(ctx context.Context, a ma.Multiaddr) (Conn, error) ", "output": "{\n\tif mafmt.TCP.Matches(a) {\n\t\treturn fbd.tcpDial(ctx, a)\n\t}\n\treturn nil, fmt.Errorf(\"cannot dial %s with fallback dialer\", a)\n}"} {"input": "package parser\n\n\ntype Sequence struct {\n\tContent []Statement\n\tParent *Sequence \n}\n\n\nfunc (s Sequence) String() (string, error) {\n\tvar content string\n\n\tif s.Parent != nil {\n\n\t\tlength := len(s.Content)\n\t\tif length > 0 {\n\t\t\trepr, err := s.Content[0].String()\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\tcontent += repr\n\t\t}\n\n\t\tfor i := 1; i < length; i++ {\n\t\t\trepr, err := s.Content[i].String()\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\tcontent += \";\" + repr\n\t\t}\n\n\t\tcontent = \"\\\"\" + content + \"\\\"\"\n\t} else {\n\n\t\tfor _, statement := range s.Content {\n\t\t\trepr, err := statement.String()\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\tcontent += repr + \"\\n\"\n\t\t}\n\t}\n\n\treturn content, nil\n}\n\n\n\n\nfunc (s *Sequence) Last() *Statement {\n\tif len(s.Content) == 0 {\n\t\treturn nil\n\t}\n\n\treturn &s.Content[len(s.Content)-1]\n}\n\n\nfunc (s *Sequence) Add(command string) *Statement {\n\ts.Content = append(s.Content, Statement{Command: command})\n\n\treturn &s.Content[len(s.Content)-1]\n}\n\nfunc (s Sequence) Undo() (string, error) ", "output": "{\n\tvar content string\n\n\tlength := len(s.Content)\n\tif length > 0 {\n\t\trepr, err := s.Content[0].Undo()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tcontent += repr\n\t}\n\n\tfor i := 1; i < length; i++ {\n\t\trepr, err := s.Content[i].Undo()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tcontent += \";\" + repr\n\t}\n\n\tcontent = \"\\\"\" + content + \"\\\"\"\n\n\treturn content, nil\n}"} {"input": "package logsearcher\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\ntype invalidFilenameFormatErr string\n\nfunc (e invalidFilenameFormatErr) Error() string {\n\treturn string(e)\n}\n\nfunc ListFolders(dir string, ch chan string) {\n\tif !strings.HasSuffix(dir, \"/\") {\n\t\tdir = dir + \"/\"\n\t}\n\tdirLength := len(dir)\n\n\tvar previousErr error\n\n\tfilepath.Walk(dir, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\tpreviousErr = err\n\t\t\tclose(ch)\n\t\t\treturn err\n\t\t}\n\t\tif info.IsDir() {\n\t\t\tch <- path[dirLength:]\n\t\t}\n\t\treturn nil\n\t})\n\tif previousErr == nil {\n\t\tclose(ch)\n\t}\n}\n\n\n\nfunc ListFiles(dir string, ch chan string) error ", "output": "{\n\tif !strings.HasSuffix(dir, \"/\") {\n\t\tdir = dir + \"/\"\n\t}\n\tdirLength := len(dir)\n\n\tvar previousErr error\n\n\tfilepath.Walk(dir, func(path string, info os.FileInfo, err error) error {\n\t\tif previousErr != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err != nil {\n\t\t\tpreviousErr = err\n\t\t\tclose(ch)\n\t\t\treturn err\n\t\t}\n\t\tif !info.IsDir() {\n\t\t\tif !strings.HasPrefix(path, dir) {\n\t\t\t\tclose(ch)\n\t\t\t\treturn invalidFilenameFormatErr(fmt.Sprintf(\"Expected file %v to start with %v\", path, dir))\n\t\t\t}\n\t\t\tch <- path[dirLength:]\n\t\t}\n\t\treturn nil\n\t})\n\tif previousErr == nil {\n\t\tclose(ch)\n\t}\n\treturn previousErr\n}"} {"input": "package daemon\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\tbgp \"github.com/gopher-net/gopher-net/third-party/github.com/gobgp/packet\"\n)\n\nfunc NewRibEntry() RibEntry {\n\trib := RibEntry{\n\t\tNextHop: nil,\n\t\tNetworkSegment: 0,\n\t\tDestIpPrefix: nil,\n\t\tLength: 0,\n\t\tGateway: nil,\n\t}\n\treturn rib\n}\n\n\ntype RibEntry struct {\n\tNextHop net.IP\n\tNetworkSegment int\n\tDestIpPrefix net.IP\n\tLength int\n\tGateway net.IP\n\tInterface net.IP\n\tMetric int\n}\n\n\ntype RoutingTable struct {\n\tRib []RibEntry\n}\n\n\n\n\n\nfunc (r *RoutingTable) Print() string {\n\tresult := fmt.Sprintf(\"%+v\\n\", r.Rib)\n\treturn result\n}\n\nfunc Ipv4PrefixConcat(p *bgp.NLRInfo) string {\n\treturn fmt.Sprintf(\"%v/%v\", p.Prefix.String(), p.Length)\n}\n\nfunc (r *RoutingTable) Add(entry *RibEntry) ", "output": "{\n\tr.Rib = append(r.Rib, *entry)\n}"} {"input": "package treemap\n\nimport (\n\t\"github.com/emirpasic/gods/containers\"\n\trbt \"github.com/emirpasic/gods/trees/redblacktree\"\n)\n\nfunc assertIteratorImplementation() {\n\tvar _ containers.ReverseIteratorWithKey = (*Iterator)(nil)\n}\n\n\ntype Iterator struct {\n\titerator rbt.Iterator\n}\n\n\nfunc (m *Map) Iterator() Iterator {\n\treturn Iterator{iterator: m.tree.Iterator()}\n}\n\n\n\n\n\nfunc (iterator *Iterator) Next() bool {\n\treturn iterator.iterator.Next()\n}\n\n\n\n\nfunc (iterator *Iterator) Prev() bool {\n\treturn iterator.iterator.Prev()\n}\n\n\n\nfunc (iterator *Iterator) Value() interface{} {\n\treturn iterator.iterator.Value()\n}\n\n\n\nfunc (iterator *Iterator) Key() interface{} {\n\treturn iterator.iterator.Key()\n}\n\n\n\n\n\n\n\nfunc (iterator *Iterator) End() {\n\titerator.iterator.End()\n}\n\n\n\n\nfunc (iterator *Iterator) First() bool {\n\treturn iterator.iterator.First()\n}\n\n\n\n\nfunc (iterator *Iterator) Last() bool {\n\treturn iterator.iterator.Last()\n}\n\nfunc (iterator *Iterator) Begin() ", "output": "{\n\titerator.iterator.Begin()\n}"} {"input": "package transport\n\nimport (\n\t\"syscall\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\n\n\nfunc setReuseAddress(network, address string, conn syscall.RawConn) error {\n\treturn conn.Control(func(fd uintptr) {\n\t\tsyscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, unix.SO_REUSEADDR, 1)\n\t})\n}\n\nfunc setReusePort(network, address string, conn syscall.RawConn) error ", "output": "{\n\treturn conn.Control(func(fd uintptr) {\n\t\tsyscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, unix.SO_REUSEPORT, 1)\n\t})\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-chi/chi\"\n)\n\ntype todosResource struct{}\n\n\n\n\nfunc (rs todosResource) List(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todos list of stuff..\"))\n}\n\nfunc (rs todosResource) Create(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todos create\"))\n}\n\nfunc (rs todosResource) Get(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todo get\"))\n}\n\nfunc (rs todosResource) Update(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todo update\"))\n}\n\nfunc (rs todosResource) Delete(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todo delete\"))\n}\n\nfunc (rs todosResource) Sync(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"todo sync\"))\n}\n\nfunc (rs todosResource) Routes() chi.Router ", "output": "{\n\tr := chi.NewRouter()\n\n\tr.Get(\"/\", rs.List) \n\tr.Post(\"/\", rs.Create) \n\tr.Put(\"/\", rs.Delete)\n\n\tr.Route(\"/{id}\", func(r chi.Router) {\n\t\tr.Get(\"/\", rs.Get) \n\t\tr.Put(\"/\", rs.Update) \n\t\tr.Delete(\"/\", rs.Delete) \n\t\tr.Get(\"/sync\", rs.Sync)\n\t})\n\n\treturn r\n}"} {"input": "package models\n\nimport (\n\t\"time\"\n\n\t\"github.com/toolkits/logger\"\n\n\t\"github.com/coraldane/ops-meta/db\"\n)\n\ntype RelAgentGroup struct {\n\tId int64\n\tGmtCreate time.Time `orm:\"auto_now_add;type(datetime)\"`\n\tGmtModified time.Time `orm:\"auto_now_add;type(datetime)\"`\n\tAgentId int64 `form:\"agentId\"`\n\tHostGroupId int64 `form:\"hostGroupId\"`\n}\n\nfunc (this *RelAgentGroup) TableUnique() [][]string {\n\treturn [][]string{\n\t\t[]string{\"AgentId\", \"HostGroupId\"},\n\t}\n}\n\nfunc (this *RelAgentGroup) Insert() (int64, error) {\n\tthis.GmtModified = time.Now()\n\n\tif 0 < this.Id {\n\t\treturn db.NewOrm().Update(this)\n\t} else {\n\t\tthis.GmtCreate = time.Now()\n\t\treturn db.NewOrm().Insert(this)\n\t}\n}\n\nfunc (this *RelAgentGroup) DeleteByPK() (int64, error) {\n\tresult, err := this.DeleteByCond()\n\treturn result, err\n}\n\n\n\nfunc QueryRelAgentGroupList(agentId int64) ([]RelAgentGroupDto, error) {\n\tvar rows []RelAgentGroupDto\n\t_, err := db.NewOrm().Raw(\"select t.id, t.gmt_create,t.gmt_modified, t.host_group_id, a.group_name from t_rel_agent_group t, t_host_group a where t.agent_id=? and t.host_group_id=a.id\", agentId).QueryRows(&rows)\n\tif nil != err {\n\t\tlogger.Errorln(\"QueryRelAgentGroupList error\", err)\n\t}\n\treturn rows, err\n}\n\nfunc (this *RelAgentGroup) DeleteByCond() (int64, error) ", "output": "{\n\tquery := db.NewOrm().QueryTable(RelAgentGroup{})\n\tif 0 < this.Id {\n\t\tquery = query.Filter(\"Id\", this.Id)\n\t}\n\tif 0 < this.HostGroupId {\n\t\tquery = query.Filter(\"HostGroupId\", this.HostGroupId)\n\t}\n\tif 0 < this.AgentId {\n\t\tquery = query.Filter(\"AgentId\", this.AgentId)\n\t}\n\treturn query.Delete()\n}"} {"input": "package util\n\nimport (\n\t\"compress/bzip2\"\n\t\"io\"\n\t\"os\"\n)\n\n\n\n\n\n\n\nfunc Bunzip2File(dst, src string) error {\n\tin, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer in.Close()\n\n\tout, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = Bunzip2(out, in)\n\tif err != nil {\n\t\tos.Remove(dst)\n\t}\n\treturn err\n}\n\nfunc Bunzip2(dst io.Writer, src io.Reader) (written int64, err error) ", "output": "{\n\tbzr := bzip2.NewReader(src)\n\treturn io.Copy(dst, bzr)\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/insionng/vodka\"\n\t\"github.com/insionng/vodka/engine/standard\"\n)\n\ntype (\n\tStats struct {\n\t\tUptime time.Time `json:\"uptime\"`\n\t\tRequestCount uint64 `json:\"requestCount\"`\n\t\tStatuses map[string]int `json:\"statuses\"`\n\t\tmutex sync.RWMutex\n\t}\n)\n\nfunc NewStats() *Stats {\n\treturn &Stats{\n\t\tUptime: time.Now(),\n\t\tStatuses: make(map[string]int),\n\t}\n}\n\n\n\n\n\nfunc (s *Stats) Handle(c vodka.Context) error {\n\ts.mutex.RLock()\n\tdefer s.mutex.RUnlock()\n\treturn c.JSON(http.StatusOK, s)\n}\n\n\nfunc ServerHeader(next vodka.HandlerFunc) vodka.HandlerFunc {\n\treturn func(c vodka.Context) error {\n\t\tc.Response().Header().Set(vodka.HeaderServer, \"Vodka/2.0\")\n\t\treturn next(c)\n\t}\n}\n\nfunc main() {\n\te := vodka.New()\n\n\te.SetDebug(true)\n\n\ts := NewStats()\n\te.Use(s.Process)\n\te.GET(\"/stats\", s.Handle) \n\n\te.Use(ServerHeader)\n\n\te.GET(\"/\", func(c vodka.Context) error {\n\t\treturn c.String(http.StatusOK, \"Hello, World!\")\n\t})\n\n\te.Run(standard.New(\":1323\"))\n}\n\nfunc (s *Stats) Process(next vodka.HandlerFunc) vodka.HandlerFunc ", "output": "{\n\treturn func(c vodka.Context) error {\n\t\tif err := next(c); err != nil {\n\t\t\tc.Error(err)\n\t\t}\n\t\ts.mutex.Lock()\n\t\tdefer s.mutex.Unlock()\n\t\ts.RequestCount++\n\t\tstatus := strconv.Itoa(c.Response().Status())\n\t\ts.Statuses[status]++\n\t\treturn nil\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"strings\"\n)\n\nvar (\n\tScore = map[string]int{\n\t\t\"A\": 1,\n\t\t\"B\": 2,\n\t\t\"C\": 3,\n\t\t\"D\": 4,\n\t\t\"E\": 5,\n\t\t\"F\": 6,\n\t\t\"G\": 7,\n\t\t\"H\": 8,\n\t\t\"I\": 9,\n\t\t\"J\": 10,\n\t\t\"K\": 11,\n\t\t\"L\": 12,\n\t\t\"M\": 13,\n\t\t\"N\": 14,\n\t\t\"O\": 15,\n\t\t\"P\": 16,\n\t\t\"Q\": 17,\n\t\t\"R\": 18,\n\t\t\"S\": 19,\n\t\t\"T\": 20,\n\t\t\"U\": 21,\n\t\t\"V\": 22,\n\t\t\"W\": 23,\n\t\t\"X\": 24,\n\t\t\"Y\": 25,\n\t\t\"Z\": 26,\n\t}\n)\n\nfunc WordScore(name string) int {\n\tsum := 0\n\tfor _, char := range name {\n\t\tsum += Score[string(char)]\n\t}\n\treturn sum\n}\n\n\n\nfunc main() {\n\tdata, err := ioutil.ReadFile(\"words.txt\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tstringData := string(data)\n\tstrippedString := strings.Replace(stringData, \"\\\"\", \"\", -1)\n\twords := strings.Split(strippedString, \",\")\n\n\ttris := TriangleNumbersUnder(192)\n\n\ttriWords := 0\n\tfor _, word := range words {\n\t\tif tris[WordScore(word)] == true {\n\t\t\ttriWords += 1\n\t\t}\n\t}\n\n\tfmt.Println(triWords)\n}\n\nfunc TriangleNumbersUnder(n int) map[int]bool ", "output": "{\n\ttris := map[int]bool{}\n\tfor i := 0; i <= n; i++ {\n\t\ttris[i] = false\n\t}\n\n\ti := 1\n\tfor {\n\t\tt := int(float64(i) / 2.0 * (float64(i) + 1.0))\n\t\tif t > n {\n\t\t\tbreak\n\t\t}\n\t\ttris[t] = true\n\t\ti += 1\n\t}\n\n\treturn tris\n}"} {"input": "package thrift\n\nimport \"io\"\n\ntype RichTransport struct {\n\tTTransport\n}\n\n\nfunc NewTRichTransport(trans TTransport) *RichTransport {\n\treturn &RichTransport{trans}\n}\n\nfunc (r *RichTransport) ReadByte() (c byte, err error) {\n\treturn readByte(r.TTransport)\n}\n\n\n\nfunc (r *RichTransport) WriteString(s string) (n int, err error) {\n\treturn r.Write([]byte(s))\n}\n\nfunc (r *RichTransport) RemainingBytes() (num_bytes uint64) {\n\treturn r.TTransport.RemainingBytes()\n}\n\nfunc readByte(r io.Reader) (c byte, err error) {\n\tv := [1]byte{0}\n\tn, err := r.Read(v[0:1])\n\tif n > 0 && (err == nil || err == io.EOF) {\n\t\treturn v[0], nil\n\t}\n\tif n > 0 && err != nil {\n\t\treturn v[0], err\n\t}\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn v[0], nil\n}\n\nfunc writeByte(w io.Writer, c byte) error {\n\tv := [1]byte{c}\n\t_, err := w.Write(v[0:1])\n\treturn err\n}\n\nfunc (r *RichTransport) WriteByte(c byte) error ", "output": "{\n\treturn writeByte(r.TTransport, c)\n}"} {"input": "package pmgo\n\nimport mgo \"gopkg.in/mgo.v2\"\n\ntype IterManager interface {\n\tAll(result interface{}) error\n\tClose() error\n\tDone() bool\n\tErr() error\n\tFor(result interface{}, f func() error) (err error)\n\tNext(result interface{}) bool\n\tTimeout() bool\n}\n\ntype Iter struct {\n\titer *mgo.Iter\n}\n\nfunc NewIter(iter *mgo.Iter) IterManager {\n\treturn &Iter{iter}\n}\n\nfunc (i *Iter) All(result interface{}) error {\n\treturn i.iter.All(result)\n}\n\nfunc (i *Iter) Close() error {\n\treturn i.iter.Close()\n}\n\nfunc (i *Iter) Done() bool {\n\treturn i.iter.Done()\n}\n\nfunc (i *Iter) Err() error {\n\treturn i.iter.Err()\n}\n\nfunc (i *Iter) For(result interface{}, f func() error) (err error) {\n\treturn i.iter.For(result, f)\n}\n\nfunc (i *Iter) Next(result interface{}) bool {\n\treturn i.iter.Next(result)\n}\n\n\n\nfunc (i *Iter) Timeout() bool ", "output": "{\n\treturn i.iter.Timeout()\n}"} {"input": "package testutil\n\nimport (\n\t\"archive/zip\"\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"strings\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\nfunc CreateZip(contents map[string]string) *bytes.Buffer {\n\tvar result bytes.Buffer\n\tzipWriter := zip.NewWriter(&result)\n\tdefer zipWriter.Close()\n\tfor filename, fileContents := range contents {\n\t\tentryWriter, e := zipWriter.Create(filename)\n\t\tExpect(e).NotTo(HaveOccurred())\n\t\tentryWriter.Write([]byte(fileContents))\n\n\t}\n\te := zipWriter.Close()\n\tExpect(e).NotTo(HaveOccurred())\n\treturn &result\n}\n\n\n\nfunc VerifyZipFileEntry(reader *zip.Reader, expectedFilename string, expectedContent string) ", "output": "{\n\tvar foundEntries []string\n\tfor _, entry := range reader.File {\n\t\tif entry.Name == expectedFilename {\n\t\t\tcontent, e := entry.Open()\n\t\t\tExpect(e).NotTo(HaveOccurred())\n\t\t\tExpect(ioutil.ReadAll(content)).To(MatchRegexp(expectedContent), \"for filename \"+expectedFilename)\n\t\t\treturn\n\t\t}\n\t\tfoundEntries = append(foundEntries, entry.Name)\n\t}\n\tFail(\"Did not find entry with name \" + expectedFilename + \". Found only: \" + strings.Join(foundEntries, \", \"))\n}"} {"input": "package suggest\n\nimport (\n\t\"github.com/google/btree\"\n\t\"sync\"\n)\n\n\ntype Suggester interface {\n\tSuggest(max int, q string) (result []string)\n}\n\n\ntype Adder interface {\n\tAdd(s string)\n}\n\n\n\ntype Engine struct {\n\tincomingCh chan string\n\tawaitCh chan bool\n\tlock sync.RWMutex\n\tsuggestions *btree.BTree\n}\n\n\nfunc NewEngine() *Engine {\n\treturn newEngine()\n}\n\n\n\n\n\n\n\n\n\nfunc (e *Engine) Await() {\n\te.await()\n}\n\n\nfunc (e *Engine) Suggest(max int, q string) (result []string) {\n\treturn e.suggest(max, q)\n}\n\n\n\nfunc NewSuggester(suggestions ...string) Suggester {\n\treturn newSuggester(suggestions)\n}\n\nfunc (e *Engine) Add(s string) ", "output": "{\n\te.add(s)\n}"} {"input": "package cdsclient\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com/ovh/cds/sdk\"\n)\n\n\n\nfunc (c *client) PollVCSEvents(uuid string, workflowID int64, vcsServer string, timestamp int64) (events sdk.RepositoryEvents, interval time.Duration, err error) ", "output": "{\n\turl := fmt.Sprintf(\"/hook/%s/workflow/%d/vcsevent/%s\", uuid, workflowID, vcsServer)\n\theader, _, errGet := c.GetJSONWithHeaders(url, &events, SetHeader(\"X-CDS-Last-Execution\", fmt.Sprint(timestamp)))\n\tif errGet != nil {\n\t\treturn events, interval, errGet\n\t}\n\n\tif header.Get(\"X-CDS-Poll-Interval\") != \"\" {\n\t\tf, errParse := strconv.ParseFloat(header.Get(\"X-CDS-Poll-Interval\"), 64)\n\t\tif errParse == nil {\n\t\t\tinterval = time.Duration(f) * time.Second\n\t\t}\n\t}\n\n\treturn events, interval, nil\n}"} {"input": "package sidekick\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\ntype stringSlice []string\n\nfunc (ss stringSlice) String() string { return strings.Join(ss, \",\") }\nfunc (ss *stringSlice) Set(s string) error { *ss = append(*ss, s); return nil }\n\nvar (\n\tDebug bool\n\n\tskips stringSlice\n\tcases stringSlice\n)\n\n\n\n\n\n\nfunc SkipCase(c interface{}) bool {\n\tfor _, item := range skips {\n\t\tif item == fmt.Sprint(c) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tfor _, item := range cases {\n\t\tif item == fmt.Sprint(c) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif len(cases) > 0 {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc init() ", "output": "{\n\tflag.Var(&skips, \"skip\", \"skip test case\")\n\tflag.Var(&cases, \"case\", \"run test case\")\n\tflag.BoolVar(&Debug, \"debug\", false, \"enter debug mode\")\n\n\tlog.SetFlags(log.Lshortfile | log.LstdFlags)\n}"} {"input": "package godo\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\t\"time\"\n)\n\nconst billingHistoryBasePath = \"v2/customers/my/billing_history\"\n\n\n\n\ntype BillingHistoryService interface {\n\tList(context.Context, *ListOptions) (*BillingHistory, *Response, error)\n}\n\n\n\ntype BillingHistoryServiceOp struct {\n\tclient *Client\n}\n\nvar _ BillingHistoryService = &BillingHistoryServiceOp{}\n\n\ntype BillingHistory struct {\n\tBillingHistory []BillingHistoryEntry `json:\"billing_history\"`\n\tLinks *Links `json:\"links\"`\n\tMeta *Meta `json:\"meta\"`\n}\n\n\ntype BillingHistoryEntry struct {\n\tDescription string `json:\"description\"`\n\tAmount string `json:\"amount\"`\n\tInvoiceID *string `json:\"invoice_id\"`\n\tInvoiceUUID *string `json:\"invoice_uuid\"`\n\tDate time.Time `json:\"date\"`\n\tType string `json:\"type\"`\n}\n\nfunc (b BillingHistory) String() string {\n\treturn Stringify(b)\n}\n\n\n\n\nfunc (s *BillingHistoryServiceOp) List(ctx context.Context, opt *ListOptions) (*BillingHistory, *Response, error) ", "output": "{\n\tpath, err := addOptions(billingHistoryBasePath, opt)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq, err := s.client.NewRequest(ctx, http.MethodGet, path, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\troot := new(BillingHistory)\n\tresp, err := s.client.Do(ctx, req, root)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\tif l := root.Links; l != nil {\n\t\tresp.Links = l\n\t}\n\tif m := root.Meta; m != nil {\n\t\tresp.Meta = m\n\t}\n\n\treturn root, resp, err\n}"} {"input": "package stripe\n\nimport (\n\t\"encoding/json\"\n\t\"testing\"\n\n\tassert \"github.com/stretchr/testify/require\"\n)\n\n\n\nfunc TestEphemeralKey_UnmarshalJSON(t *testing.T) ", "output": "{\n\tinvalidJSON := []byte(\"{\\\"foo\\\":5}\")\n\tkey := &EphemeralKey{}\n\n\terr := json.Unmarshal(invalidJSON, key)\n\tassert.NoError(t, err)\n\tassert.Empty(t, key.ID)\n\tassert.Equal(t, invalidJSON, key.RawJSON)\n}"} {"input": "package rpc\n\nimport (\n\t\"github.com/mitchellh/packer/packer\"\n\t\"log\"\n\t\"net/rpc\"\n)\n\n\n\ntype hook struct {\n\tclient *rpc.Client\n\tmux *muxBroker\n}\n\n\n\ntype HookServer struct {\n\thook packer.Hook\n\tmux *muxBroker\n}\n\ntype HookRunArgs struct {\n\tName string\n\tData interface{}\n\tStreamId uint32\n}\n\nfunc (h *hook) Run(name string, ui packer.Ui, comm packer.Communicator, data interface{}) error {\n\tnextId := h.mux.NextId()\n\tserver := newServerWithMux(h.mux, nextId)\n\tserver.RegisterCommunicator(comm)\n\tserver.RegisterUi(ui)\n\tgo server.Serve()\n\n\targs := HookRunArgs{\n\t\tName: name,\n\t\tData: data,\n\t\tStreamId: nextId,\n\t}\n\n\treturn h.client.Call(\"Hook.Run\", &args, new(interface{}))\n}\n\n\n\nfunc (h *HookServer) Run(args *HookRunArgs, reply *interface{}) error {\n\tclient, err := newClientWithMux(h.mux, args.StreamId)\n\tif err != nil {\n\t\treturn NewBasicError(err)\n\t}\n\tdefer client.Close()\n\n\tif err := h.hook.Run(args.Name, client.Ui(), client.Communicator(), args.Data); err != nil {\n\t\treturn NewBasicError(err)\n\t}\n\n\t*reply = nil\n\treturn nil\n}\n\nfunc (h *HookServer) Cancel(args *interface{}, reply *interface{}) error {\n\th.hook.Cancel()\n\treturn nil\n}\n\nfunc (h *hook) Cancel() ", "output": "{\n\terr := h.client.Call(\"Hook.Cancel\", new(interface{}), new(interface{}))\n\tif err != nil {\n\t\tlog.Printf(\"Hook.Cancel error: %s\", err)\n\t}\n}"} {"input": "package main\n\nimport (\n \"flag\"\n \"net/http\"\n \"time\"\n\n \"go-websiteskeleton/app/common\"\n \"go-websiteskeleton/app/home\"\n \"go-websiteskeleton/app/user\"\n \"go-websiteskeleton/app/contact\"\n \"go-websiteskeleton/app/blog\"\n\n \"github.com/golang/glog\"\n \"github.com/gorilla/mux\"\n)\n\nfunc main() {\n flag.Parse()\n defer glog.Flush()\n\n router := mux.NewRouter()\n http.Handle(\"/\", httpInterceptor(router))\n\n router.HandleFunc(\"/\", home.GetHomePage).Methods(\"GET\")\n router.HandleFunc(\"/users{_:/?}\", user.GetHomePage).Methods(\"GET\")\n\n router.HandleFunc(\"/user/view/{id:[0-9]+}\", user.GetViewPage).Methods(\"GET\")\n router.HandleFunc(\"/user/{id:[0-9]+}\", user.GetViewPage).Methods(\"GET\")\n\n router.HandleFunc(\"/contact\", contact.GetHomePage).Methods(\"GET\")\n router.HandleFunc(\"/contact\", contact.SubmitContactForm).Methods(\"POST\")\n\n router.HandleFunc(\"/blog/{title:[a-z0-9-]+}\", blog.GetViewPage).Methods(\"GET\")\n\n fileServer := http.StripPrefix(\"/dist/\", http.FileServer(http.Dir(\"web/dist\")))\n http.Handle(\"/dist/\", fileServer)\n\n http.ListenAndServe(\":8181\", nil)\n}\n\n\n\nfunc httpInterceptor(router http.Handler) http.Handler ", "output": "{\n return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n startTime := time.Now()\n\n router.ServeHTTP(w, req)\n\n finishTime := time.Now()\n elapsedTime := finishTime.Sub(startTime)\n\n switch req.Method {\n case \"GET\":\n \n \n common.LogAccess(w, req, elapsedTime)\n case \"POST\":\n \n }\n\n })\n}"} {"input": "package match\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\nfunc Match(t *testing.T, value interface{}) *Matcher {\n\treturn &Matcher{\n\t\tt: t,\n\t\tvalue: value,\n\t}\n}\n\n\nfunc IsNil(t *testing.T, value interface{}) *Matcher {\n\treturn Match(t, value).IsNil()\n}\n\n\nfunc IsNotNil(t *testing.T, value interface{}) *Matcher {\n\treturn Match(t, value).IsNotNil()\n}\n\n\nfunc Equals(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).Equals(other)\n}\n\n\nfunc NotEquals(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).NotEquals(other)\n}\n\n\nfunc LessThan(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).LessThan(other)\n}\n\n\nfunc GreaterThan(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).GreaterThan(other)\n}\n\n\nfunc Contains(t *testing.T, value, other interface{}) *Matcher {\n\treturn Match(t, value).Contains(other)\n}\n\n\nfunc Matches(t *testing.T, value interface{}, pattern string) *Matcher {\n\treturn Match(t, value).Matches(pattern)\n}\n\n\n\n\nfunc KindOf(t *testing.T, value interface{}, kind reflect.Kind) *Matcher ", "output": "{\n\treturn Match(t, value).KindOf(kind)\n}"} {"input": "package ocgrpc\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"go.opencensus.io/tag\"\n\t\"google.golang.org/grpc/grpclog\"\n\t\"google.golang.org/grpc/stats\"\n)\n\n\n\n\n\nfunc (h *ClientHandler) statsTagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context ", "output": "{\n\tstartTime := time.Now()\n\tif info == nil {\n\t\tif grpclog.V(2) {\n\t\t\tgrpclog.Info(\"clientHandler.TagRPC called with nil info.\")\n\t\t}\n\t\treturn ctx\n\t}\n\n\td := &rpcData{\n\t\tstartTime: startTime,\n\t\tmethod: info.FullMethodName,\n\t}\n\tts := tag.FromContext(ctx)\n\tif ts != nil {\n\t\tencoded := tag.Encode(ts)\n\t\tctx = stats.SetTags(ctx, encoded)\n\t}\n\n\treturn context.WithValue(ctx, rpcDataKey, d)\n}"} {"input": "package control\n\nimport (\n\t\"context\"\n\t\"sync\"\n)\n\nvar (\n\tBuildSessionConfigs = buildSessionConfigs\n\tComputeDiff = computeDiff\n\tNewPathPolForEnteringAS = newPathPolForEnteringAS\n\tNewPrefixWatcher = newPrefixWatcher\n\n\tCopyPathPolicy = copyPathPolicy\n\tBuildRoutingChains = buildRoutingChains\n)\n\ntype ConjunctionPathPol = conjuctionPathPol\ntype Diff = diff\n\nfunc (w *GatewayWatcher) RunOnce(ctx context.Context) {\n\tw.run(ctx)\n}\n\n\n\nfunc (w *prefixWatcher) resetRunMarker() {\n\tw.runMarkerLock.Lock()\n\tdefer w.runMarkerLock.Unlock()\n\tw.runMarker = false\n}\n\nfunc (w *GatewayWatcher) RunAllPrefixWatchersOnceForTest(ctx context.Context) ", "output": "{\n\tvar wg sync.WaitGroup\n\tfor _, wi := range w.currentWatchers {\n\t\twi := wi\n\t\twi.prefixWatcher.resetRunMarker()\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\twi.prefixWatcher.Run(ctx)\n\t\t}()\n\t}\n\twg.Wait()\n}"} {"input": "package record\n\nimport (\n\t\"testing\"\n\n\tch \"github.com/BatchLabs/charlatan\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestNewCSVRecordWithoutHeader(t *testing.T) {\n\tc := NewCSVRecord([]string{\"a\", \"b\", \"c\"})\n\trequire.NotNil(t, c)\n\tassert.Nil(t, c.header)\n}\n\nfunc TestFindNameWithoutHeader(t *testing.T) {\n\tc := NewCSVRecord([]string{\"a\", \"b\", \"c\"})\n\trequire.NotNil(t, c)\n\n\t_, err := c.Find(ch.NewField(\"foo\"))\n\tassert.NotNil(t, err)\n}\n\nfunc TestFindColumnIndex(t *testing.T) {\n\tc := NewCSVRecord([]string{\"a\", \"b\", \"c\"})\n\trequire.NotNil(t, c)\n\n\t_, err := c.Find(ch.NewField(\"$-1\"))\n\tassert.NotNil(t, err)\n\n\t_, err = c.Find(ch.NewField(\"$42\"))\n\tassert.NotNil(t, err)\n\n\tv, err := c.Find(ch.NewField(\"$1\"))\n\tassert.Nil(t, err)\n\tassert.True(t, v.IsString())\n\tassert.Equal(t, \"b\", v.AsString())\n}\n\n\n\nfunc TestFindStar(t *testing.T) {\n\tc := NewCSVRecord([]string{\"x\", \"y\", \"z\"})\n\trequire.NotNil(t, c)\n\n\tv, err := c.Find(ch.NewField(\"*\"))\n\tassert.Nil(t, err)\n\tassert.True(t, v.IsString())\n\tassert.Equal(t, \"[x y z]\", v.AsString())\n}\n\nfunc TestFindColumnName(t *testing.T) ", "output": "{\n\tc := NewCSVRecordWithHeader([]string{\"a\", \"b\", \"c\"}, []string{\"id\", \"x\", \"y\"})\n\trequire.NotNil(t, c)\n\n\t_, err := c.Find(ch.NewField(\"yo\"))\n\tassert.NotNil(t, err)\n\n\t_, err = c.Find(ch.NewField(\"xy\"))\n\tassert.NotNil(t, err)\n\n\tv, err := c.Find(ch.NewField(\"y\"))\n\tassert.Nil(t, err)\n\tassert.Equal(t, \"c\", v.AsString())\n}"} {"input": "package container\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\ntype ContainerGCPolicy struct {\n\tMinAge time.Duration\n\n\tMaxPerPodContainer int\n\n\tMaxContainers int\n}\n\n\n\n\ntype ContainerGC interface {\n\tGarbageCollect(allSourcesReady bool) error\n}\n\n\ntype realContainerGC struct {\n\truntime Runtime\n\n\tpolicy ContainerGCPolicy\n}\n\n\nfunc NewContainerGC(runtime Runtime, policy ContainerGCPolicy) (ContainerGC, error) {\n\tif policy.MinAge < 0 {\n\t\treturn nil, fmt.Errorf(\"invalid minimum garbage collection age: %v\", policy.MinAge)\n\t}\n\n\treturn &realContainerGC{\n\t\truntime: runtime,\n\t\tpolicy: policy,\n\t}, nil\n}\n\n\n\nfunc (cgc *realContainerGC) GarbageCollect(allSourcesReady bool) error ", "output": "{\n\treturn cgc.runtime.GarbageCollect(cgc.policy, allSourcesReady)\n}"} {"input": "package jwt\n\nimport (\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n)\n\n\n\n\n\n\ntype Token struct {\n\tExpiryDate int64\n\tRawToken string\n}\n\n\n\nconst expirationSkew = 30\n\n\nfunc (t *Token) Expired() bool {\n\treturn time.Now().Unix()+expirationSkew > t.ExpiryDate\n}\n\n\n\nfunc (t *Token) GetAuthenticationHeaderValue() string {\n\treturn fmt.Sprintf(\"Bearer %s\", t.RawToken)\n}\n\n\nfunc (t *Token) String() string {\n\treturn t.RawToken\n}\n\n\ntype tokenPayload struct {\n\tExpirationTime int64 `json:\"exp\"`\n}\n\n\n\n\n\n\n\nfunc New(token string) (Token, error) ", "output": "{\n\tif len(token) == 0 {\n\t\treturn Token{}, errors.New(\"no token given, a token should be set\")\n\t}\n\n\ttokenParts := strings.Split(token, \".\")\n\tif len(tokenParts) != 3 {\n\t\treturn Token{}, fmt.Errorf(\"invalid token '%s' given, token should exist at least of 3 parts\", token)\n\t}\n\n\tjsonBody, err := base64.RawStdEncoding.DecodeString(tokenParts[1])\n\tif err != nil {\n\t\treturn Token{}, errors.New(\"could not decode token, invalid base64\")\n\t}\n\n\tvar tokenRequest tokenPayload\n\terr = json.Unmarshal(jsonBody, &tokenRequest)\n\tif err != nil {\n\t\treturn Token{}, errors.New(\"could not read token body, invalid json\")\n\t}\n\n\treturn Token{\n\t\tRawToken: token,\n\t\tExpiryDate: tokenRequest.ExpirationTime,\n\t}, nil\n}"} {"input": "package core\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype RemoveNetworkSecurityGroupSecurityRulesRequest struct {\n\n\tNetworkSecurityGroupId *string `mandatory:\"true\" contributesTo:\"path\" name:\"networkSecurityGroupId\"`\n\n\tRemoveNetworkSecurityGroupSecurityRulesDetails `contributesTo:\"body\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request RemoveNetworkSecurityGroupSecurityRulesRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request RemoveNetworkSecurityGroupSecurityRulesRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\n\n\n\nfunc (request RemoveNetworkSecurityGroupSecurityRulesRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype RemoveNetworkSecurityGroupSecurityRulesResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response RemoveNetworkSecurityGroupSecurityRulesResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response RemoveNetworkSecurityGroupSecurityRulesResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request RemoveNetworkSecurityGroupSecurityRulesRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\n}"} {"input": "package utils\n\nimport (\n \"github.com/BurntSushi/toml\"\n \"io/ioutil\"\n \"net\"\n \"sync\"\n \"strings\"\n\n log \"github.com/cihub/seelog\"\n)\n\nvar (\n config *Configuration\n configLock = new(sync.RWMutex)\n)\n\nfunc ReadConfigFromFile(configfile string) {\n config_file, err := ioutil.ReadFile(configfile)\n if err != nil {\n panic(err.Error())\n }\n tempConf := new(Configuration)\n _, err = toml.Decode(string(config_file), &tempConf)\n if err != nil {\n panic(err.Error())\n }\n configLock.Lock()\n config = tempConf\n configLock.Unlock()\n}\n\n\n\nfunc GetLocalIp() string {\n addrs, err := net.InterfaceAddrs()\n if err != nil {\n log.Criticalf(\"No network interfaces found, %s\", err.Error())\n }\n \n var ips []string\n for _, a := range addrs {\n if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {\n if ipnet.IP.To4() != nil {\n ips = append(ips, ipnet.IP.String())\n }\n }\n }\n return strings.Join(ips, \",\")\n}\n\nfunc GetConfig() *Configuration ", "output": "{\n configLock.RLock()\n defer configLock.RUnlock()\n return config\n}"} {"input": "package test\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\t\"runtime\"\n\t\"path/filepath\"\n\t_ \"github.com/dvwallin/gopress/routers\"\n\n\t\"github.com/astaxie/beego\"\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\nfunc init() {\n\t_, file, _, _ := runtime.Caller(1)\n\tapppath, _ := filepath.Abs(filepath.Dir(filepath.Join(file, \"..\" + string(filepath.Separator))))\n\tbeego.TestBeegoInit(apppath)\n}\n\n\n\n\n\nfunc TestMain(t *testing.T) ", "output": "{\n\tr, _ := http.NewRequest(\"GET\", \"/\", nil)\n\tw := httptest.NewRecorder()\n\tbeego.BeeApp.Handlers.ServeHTTP(w, r)\n\n\tbeego.Trace(\"testing\", \"TestMain\", \"Code[%d]\\n%s\", w.Code, w.Body.String())\n\n\tConvey(\"Subject: Test Station Endpoint\\n\", t, func() {\n\t Convey(\"Status Code Should Be 200\", func() {\n\t So(w.Code, ShouldEqual, 200)\n\t })\n\t Convey(\"The Result Should Not Be Empty\", func() {\n\t So(w.Body.Len(), ShouldBeGreaterThan, 0)\n\t })\n\t})\n}"} {"input": "package gspt\n\nimport (\n\t\"bytes\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"encoding/binary\"\n\t\"encoding/hex\"\n\n\t\"crypto/md5\"\n\t\"os/exec\"\n)\n\nfunc randomMD5() string {\n\tstr := md5.New()\n\trandom := new(bytes.Buffer)\n\n\tbinary.Write(random, binary.LittleEndian, time.Now().UTC().UnixNano())\n\n\tstr.Write(random.Bytes())\n\n\treturn hex.EncodeToString(str.Sum(nil))\n}\n\n\n\nfunc TestSetProcTitleFast(t *testing.T) {\n\tif HaveSetProcTitleFast == HaveNone {\n\t\tt.SkipNow()\n\t}\n\n\ttitle := randomMD5()\n\n\tSetProcTitleFast(title)\n\n\tout, err := exec.Command(\"/bin/ps\", \"ax\").Output()\n\tif err != nil {\n\t\tt.SkipNow()\n\t} else if !strings.Contains(string(out), title) {\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestSetProcTitle(t *testing.T) ", "output": "{\n\tif HaveSetProcTitle == HaveNone {\n\t\tt.SkipNow()\n\t}\n\n\ttitle := randomMD5()\n\n\tSetProcTitle(title)\n\n\tout, err := exec.Command(\"/bin/ps\", \"ax\").Output()\n\tif err != nil {\n\t\tt.SkipNow()\n\t} else if !strings.Contains(string(out), title) {\n\t\tt.FailNow()\n\t}\n}"} {"input": "package gq\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nvar count int\n\ntype WorkerTest struct {\n\tDelay time.Duration\n}\n\nfunc (w WorkerTest) Work() {\n\tcount++\n}\n\nfunc (w WorkerTest) Data() string {\n\treturn \"\"\n}\n\n\n\nfunc (w WorkerTest) Preprocess() string {\n\treturn \"\"\n}\n\nfunc (w WorkerTest) Postprocess() string {\n\treturn \"\"\n}\n\nfunc nullLogger(...interface{}) {}\n\nfunc init() {\n\tLogger(nullLogger)\n\tStartDispatcher(10)\n\tfor i := 0; i < 10; i++ {\n\t\twork := WorkerTest{Delay: 0 * time.Second}\n\t\tWorkQueue <- work\n\t}\n\ttime.Sleep(1 * time.Second)\n}\n\nfunc TestIncrement(t *testing.T) {\n\tif count != 10 {\n\t\tt.Errorf(\"expected count to be 10, got %d\\n\", count)\n\t}\n}\n\nfunc (w WorkerTest) DelayTime() time.Duration ", "output": "{\n\treturn w.Delay\n}"} {"input": "package servers_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/murdinc/crusher/servers\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestNewServer(t *testing.T) ", "output": "{\n\tserver := servers.New(\"testserver\", \"127.0.0.1\", \"wcrusher\", \"hello_world\", false)\n\tassert.Equal(t, \"127.0.0.1\", server.Host)\n\tassert.Equal(t, \"testserver\", server.Name)\n\tassert.Equal(t, \"hello_world\", server.Spec)\n\tassert.Equal(t, \"wcrusher\", server.Username)\n\n\tassert.False(t, server.PassAuth)\n}"} {"input": "package ldapserver\n\ntype CompareRequest struct {\n\tentry LDAPDN\n\tava AttributeValueAssertion\n}\n\nfunc (r *CompareRequest) GetEntry() LDAPDN {\n\treturn r.entry\n}\n\nfunc (r *CompareRequest) GetAttributeValueAssertion() *AttributeValueAssertion {\n\treturn &r.ava\n}\n\ntype CompareResponse struct {\n\tldapResult\n}\n\n\n\nfunc NewCompareResponse(resultCode int) *CompareResponse ", "output": "{\n\tr := &CompareResponse{}\n\tr.ResultCode = resultCode\n\treturn r\n}"} {"input": "package content\nimport (\n\t\"go2o/src/core/domain/interface/content\"\n\t\"time\"\n)\n\nvar _ content.IPage = new(Page)\ntype Page struct{\n\t_contentRep content.IContentRep\n\t_partnerId int\n\t_value *content.ValuePage\n}\n\nfunc NewPage(partnerId int, rep content.IContentRep,v *content.ValuePage) content.IPage {\n\treturn &Page{\n\t\t_contentRep: rep,\n\t\t_partnerId: partnerId,\n\t\t_value:v,\n\t}\n}\n\n\n\nfunc (this *Page) GetDomainId() int{\n\treturn this._value.Id\n}\n\n\nfunc (this *Page) GetValue()*content.ValuePage{\n\treturn this._value\n}\n\n\nfunc (this *Page) SetValue(v *content.ValuePage)error{\n\tv.Id = this.GetDomainId()\n\tthis._value = v\n\treturn nil\n}\n\n\n\n\nfunc (this *Page) Save()(int,error)", "output": "{\n\tthis._value.UpdateTime = time.Now().Unix()\n\treturn this._contentRep.SavePage(this._partnerId,this._value)\n}"} {"input": "package internalversion\n\nimport (\n\tapiextensions \"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\ntype CustomResourceDefinitionLister interface {\n\tList(selector labels.Selector) (ret []*apiextensions.CustomResourceDefinition, err error)\n\tGet(name string) (*apiextensions.CustomResourceDefinition, error)\n\tCustomResourceDefinitionListerExpansion\n}\n\n\ntype customResourceDefinitionLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewCustomResourceDefinitionLister(indexer cache.Indexer) CustomResourceDefinitionLister {\n\treturn &customResourceDefinitionLister{indexer: indexer}\n}\n\n\nfunc (s *customResourceDefinitionLister) List(selector labels.Selector) (ret []*apiextensions.CustomResourceDefinition, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*apiextensions.CustomResourceDefinition))\n\t})\n\treturn ret, err\n}\n\n\n\n\nfunc (s *customResourceDefinitionLister) Get(name string) (*apiextensions.CustomResourceDefinition, error) ", "output": "{\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(apiextensions.Resource(\"customresourcedefinition\"), name)\n\t}\n\treturn obj.(*apiextensions.CustomResourceDefinition), nil\n}"} {"input": "package handlers\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/graze/golang-service/log\"\n\tuuid \"github.com/satori/go.uuid\"\n)\n\n\ntype logContextHandler struct {\n\tlogger log.FieldLogger\n\thandler http.Handler\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc LoggingContextHandler(logger log.FieldLogger, h http.Handler) http.Handler {\n\treturn logContextHandler{logger.With(log.KV{}), h}\n}\n\nfunc (h logContextHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) ", "output": "{\n\turl := *req.URL\n\tip := \"\"\n\tif userIP, err := getUserIP(req); err == nil {\n\t\tip = userIP.String()\n\t}\n\tctx := h.logger.Ctx(req.Context()).With(log.KV{\n\t\t\"transaction\": uuid.NewV4().String(),\n\t\t\"http.method\": req.Method,\n\t\t\"http.protocol\": req.Proto,\n\t\t\"http.uri\": parseURI(req, url),\n\t\t\"http.path\": uriPath(req, url),\n\t\t\"http.host\": req.Host,\n\t\t\"http.user\": ip,\n\t\t\"http.ref\": req.Referer(),\n\t\t\"http.user-agent\": req.Header.Get(\"User-Agent\"),\n\t}).NewContext(req.Context())\n\th.handler.ServeHTTP(w, req.WithContext(ctx))\n}"} {"input": "package buckettree\n\nimport (\n\t\"github.com/golang/protobuf/proto\"\n\t\"github.com/hyperledger/fabric/core/ledger/util\"\n\topenchainUtil \"github.com/hyperledger/fabric/core/util\"\n)\n\ntype bucketHashCalculator struct {\n\tbucketKey *bucketKey\n\tcurrentChaincodeID string\n\tdataNodes []*dataNode\n\thashingData []byte\n}\n\nfunc newBucketHashCalculator(bucketKey *bucketKey) *bucketHashCalculator {\n\treturn &bucketHashCalculator{bucketKey, \"\", nil, nil}\n}\n\n\nfunc (c *bucketHashCalculator) addNextNode(dataNode *dataNode) {\n\tchaincodeID, _ := dataNode.getKeyElements()\n\tif chaincodeID != c.currentChaincodeID {\n\t\tc.appendCurrentChaincodeData()\n\t\tc.currentChaincodeID = chaincodeID\n\t\tc.dataNodes = nil\n\t}\n\tc.dataNodes = append(c.dataNodes, dataNode)\n}\n\nfunc (c *bucketHashCalculator) computeCryptoHash() []byte {\n\tif c.currentChaincodeID != \"\" {\n\t\tc.appendCurrentChaincodeData()\n\t\tc.currentChaincodeID = \"\"\n\t\tc.dataNodes = nil\n\t}\n\tlogger.Debug(\"Hashable content for bucket [%s]: length=%d, contentInStringForm=[%s]\", c.bucketKey, len(c.hashingData), string(c.hashingData))\n\tif util.IsNil(c.hashingData) {\n\t\treturn nil\n\t}\n\treturn openchainUtil.ComputeCryptoHash(c.hashingData)\n}\n\n\n\nfunc (c *bucketHashCalculator) appendSizeAndData(b []byte) {\n\tc.appendSize(len(b))\n\tc.hashingData = append(c.hashingData, b...)\n}\n\nfunc (c *bucketHashCalculator) appendSize(size int) {\n\tc.hashingData = append(c.hashingData, proto.EncodeVarint(uint64(size))...)\n}\n\nfunc (c *bucketHashCalculator) appendCurrentChaincodeData() ", "output": "{\n\tif c.currentChaincodeID == \"\" {\n\t\treturn\n\t}\n\tc.appendSizeAndData([]byte(c.currentChaincodeID))\n\tc.appendSize(len(c.dataNodes))\n\tfor _, dataNode := range c.dataNodes {\n\t\t_, key := dataNode.getKeyElements()\n\t\tvalue := dataNode.getValue()\n\t\tc.appendSizeAndData([]byte(key))\n\t\tc.appendSizeAndData(value)\n\t}\n}"} {"input": "package rubber\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"go.uber.org/zap\"\n)\n\nconst (\n\tConfigWeightedBackend = \"weighted\"\n\n\tConfigSimpleBackend = \"simple\"\n)\n\nfunc compare(name, constant string) bool {\n\treturn strings.ToLower(name) == strings.ToLower(constant)\n}\n\nfunc makeBackend(log *zap.Logger, settings Settings) (Backend, error) {\n\tif compare(settings.Type, ConfigWeightedBackend) {\n\t\tlog.Debug(\"Using weighted backend\")\n\t\treturn CreateWeightedBackend(settings, log)\n\t}\n\tif compare(settings.Type, ConfigSimpleBackend) || compare(settings.Type, \"\") {\n\t\tlog.Debug(\"Using simple backend\")\n\t\tnodes := []string{settings.Preferred}\n\t\tnodes = append(nodes, settings.Nodes...)\n\t\treturn &singleServerBackend{\n\t\t\tlog: log,\n\t\t\tnodes: nodes,\n\t\t\ttimeout: settings.Timeout * time.Second,\n\n\t\t\tclient: &http.Client{\n\t\t\t\tTimeout: settings.Timeout * time.Second,\n\t\t\t},\n\t\t}, nil\n\t}\n\treturn nil, errors.New(\"Unknown backend\")\n}\n\n\nfunc Create(backend Backend) *Elastic {\n\treturn &Elastic{Backend: backend}\n}\n\n\n\n\nfunc New(log *zap.Logger, settings Settings) (*Elastic, error) ", "output": "{\n\tbackend, err := makeBackend(log, settings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn Create(backend), nil\n}"} {"input": "package testdata\n\nimport \"testing\"\n\n\n\nfunc TestFoo2(t *testing.T) ", "output": "{\n\ttype args struct {\n\t\tin0 string\n\t\tin1 int\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t}{\n\t}\n\tfor _, tt := range tests {\n\t\tFoo2(tt.args.in0, tt.args.in1)\n\t}\n}"} {"input": "package console\n\nimport \"github.com/cgrates/cgrates/apier/v1\"\n\nfunc init() {\n\tc := &CmdAccountAddTriggers{\n\t\tname: \"account_triggers_add\",\n\t\trpcMethod: \"ApierV1.AddAccountActionTriggers\",\n\t\trpcParams: &v1.AttrAddAccountActionTriggers{},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdAccountAddTriggers struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrAddAccountActionTriggers\n\t*CommandExecuter\n}\n\nfunc (self *CmdAccountAddTriggers) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdAccountAddTriggers) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdAccountAddTriggers) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrAddAccountActionTriggers{}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdAccountAddTriggers) PostprocessRpcParams() error {\n\treturn nil\n}\n\n\n\nfunc (self *CmdAccountAddTriggers) RpcResult() interface{} ", "output": "{\n\tvar s string\n\treturn &s\n}"} {"input": "package stripedash\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\n\nfunc Uint64ToDollars(i uint64) string ", "output": "{\n\td := []byte(strconv.FormatUint(i, 10))\n\n\tif len(d) < 3 {\n\t\treturn fmt.Sprintf(\"0.%s\", d)\n\t}\n\n\tcentStart := len(d) - 2\n\n\tdollars := d[0:centStart]\n\tcents := d[centStart:len(d)]\n\treturn fmt.Sprintf(\"%s.%s\", string(dollars), string(cents))\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"strings\"\n)\n\n\nfunc MakeIndexMessage(pkg *Package) string {\n\tdependenciesNames := []string{}\n\n\tfor _, dep := range pkg.Dependencies {\n\t\tdependenciesNames = append(dependenciesNames, dep.Name)\n\t}\n\n\tnamesAsString := strings.Join(dependenciesNames, \",\")\n\treturn fmt.Sprintf(\"INDEX|%s|%s\", pkg.Name, namesAsString)\n}\n\n\n\n\n\nfunc MakeQueryMessage(pkg *Package) string {\n\treturn fmt.Sprintf(\"QUERY|%s|\", pkg.Name)\n}\n\nvar possibleInvalidCommands = []string{\"BLINDEX\", \"REMOVES\", \"QUER\", \"LIZARD\", \"I\"}\nvar possibleInvalidChars = []string{\"=\", \"+\", \"☃\", \" \"}\n\n\n\nfunc MakeBrokenMessage() string {\n\tsyntaxError := rand.Intn(10)%2 == 0\n\n\tif syntaxError {\n\t\tinvalidChar := possibleInvalidChars[rand.Intn(len(possibleInvalidChars))]\n\t\treturn fmt.Sprintf(\"INDEX|emacs%selisp\", invalidChar)\n\t}\n\n\tinvalidCommand := possibleInvalidCommands[rand.Intn(len(possibleInvalidCommands))]\n\treturn fmt.Sprintf(\"%s|a|b\", invalidCommand)\n}\n\nfunc MakeRemoveMessage(pkg *Package) string ", "output": "{\n\treturn fmt.Sprintf(\"REMOVE|%s|\", pkg.Name)\n}"} {"input": "package libcontainerd\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/containerd/containerd\"\n\t\"github.com/containerd/containerd/windows/hcsshimtypes\"\n\tspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n\t\"github.com/pkg/errors\"\n)\n\nfunc summaryFromInterface(i interface{}) (*Summary, error) {\n\tswitch pd := i.(type) {\n\tcase *hcsshimtypes.ProcessDetails:\n\t\treturn &Summary{\n\t\t\tCreateTimestamp: pd.CreatedAt,\n\t\t\tImageName: pd.ImageName,\n\t\t\tKernelTime100ns: pd.KernelTime_100Ns,\n\t\t\tMemoryCommitBytes: pd.MemoryCommitBytes,\n\t\t\tMemoryWorkingSetPrivateBytes: pd.MemoryWorkingSetPrivateBytes,\n\t\t\tMemoryWorkingSetSharedBytes: pd.MemoryWorkingSetSharedBytes,\n\t\t\tProcessId: pd.ProcessID,\n\t\t\tUserTime100ns: pd.UserTime_100Ns,\n\t\t}, nil\n\tdefault:\n\t\treturn nil, errors.Errorf(\"Unknown process details type %T\", pd)\n\t}\n}\n\n\n\nfunc pipeName(containerID, processID, name string) string {\n\treturn fmt.Sprintf(`\\\\.\\pipe\\containerd-%s-%s-%s`, containerID, processID, name)\n}\n\nfunc newFIFOSet(bundleDir, containerID, processID string, withStdin, withTerminal bool) *containerd.FIFOSet {\n\tfifos := &containerd.FIFOSet{\n\t\tTerminal: withTerminal,\n\t\tOut: pipeName(containerID, processID, \"stdout\"),\n\t}\n\n\tif withStdin {\n\t\tfifos.In = pipeName(containerID, processID, \"stdin\")\n\t}\n\n\tif !fifos.Terminal {\n\t\tfifos.Err = pipeName(containerID, processID, \"stderr\")\n\t}\n\n\treturn fifos\n}\n\nfunc prepareBundleDir(bundleDir string, ociSpec *specs.Spec) (string, error) ", "output": "{\n\treturn bundleDir, nil\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSSecretsManagerRotationSchedule_RotationRules struct {\n\n\tAutomaticallyAfterDays int `json:\"AutomaticallyAfterDays,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) AWSCloudFormationType() string {\n\treturn \"AWS::SecretsManager::RotationSchedule.RotationRules\"\n}\n\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\n\n\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) Metadata() map[string]interface{} ", "output": "{\n\treturn r._metadata\n}"} {"input": "package notmain\n\nimport (\n\t\"testing\"\n\n\t\"github.com/letsencrypt/boulder/test\"\n)\n\nfunc TestLineValidAccepts(t *testing.T) {\n\terr := lineValid(\"2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 boulder-wfe[1595]: kKG6cwA Caught SIGTERM\")\n\ttest.AssertNotError(t, err, \"errored on valid checksum\")\n}\n\nfunc TestLineValidRejects(t *testing.T) {\n\terr := lineValid(\"2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 boulder-wfe[1595]: xxxxxxx Caught SIGTERM\")\n\ttest.AssertError(t, err, \"didn't error on invalid checksum\")\n}\n\nfunc TestLineValidRejectsNotAChecksum(t *testing.T) {\n\terr := lineValid(\"2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 boulder-wfe[1595]: xxxx Caught SIGTERM\")\n\ttest.AssertError(t, err, \"didn't error on invalid checksum\")\n\ttest.AssertErrorIs(t, err, errInvalidChecksum)\n}\n\n\n\nfunc TestLineValidNonOurobouros(t *testing.T) ", "output": "{\n\terr := lineValid(\"2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 boulder-wfe[1595]: xxxxxxx Caught SIGTERM\")\n\ttest.AssertError(t, err, \"didn't error on invalid checksum\")\n\n\tselfOutput := \"2020-07-06T18:07:43.109389+00:00 70877f679c72 datacenter 6 log-validator[1337]: xxxxxxx \" + err.Error()\n\terr2 := lineValid(selfOutput)\n\ttest.AssertNotError(t, err2, \"expected no error when feeding lineValid's error output into itself\")\n}"} {"input": "package main\n\nimport (\n\t\"github.com/trasa/watchmud-message\"\n)\n\nfunc (c *Client) handleSayResponse(resp *message.SayResponse) {\n\tif resp.Success {\n\t\tUIPrintf(\"You say '%s'\\n\", resp.Value)\n\t} else {\n\t\tif resp.GetResultCode() == \"NOT_IN_A_ROOM\" {\n\t\t\tUIPrintln(\"You yell into the darkness.\")\n\t\t} else {\n\t\t\tUIPrintResponseError(resp, resp.GetResultCode())\n\t\t}\n\t}\n}\n\nfunc (c *Client) handleSayNotification(note *message.SayNotification) {\n\tif note.Success {\n\t\tUIPrintf(\"%s says '%s'.\\n\", note.Sender, note.Value)\n\t} else {\n\t\tUIPrintResponseError(note, note.GetResultCode())\n\t}\n}\n\nfunc (c *Client) handleTellNotification(note *message.TellNotification) {\n\tif note.GetSuccess() {\n\t\tUIPrintf(\"%s tells you '%s'.\\n\", note.Sender, note.Value)\n\t} else {\n\t\tUIPrintResponseError(note, note.GetResultCode())\n\t}\n}\n\nfunc (c *Client) handleTellResponse(resp *message.TellResponse) {\n\tif resp.GetSuccess() {\n\t\tUIPrintln(\"sent.\")\n\t} else if resp.GetResultCode() == \"TO_PLAYER_NOT_FOUND\" {\n\t\tUIPrintln(\"Nobody here by that name.\")\n\t} else {\n\t\tUIPrintResponseError(resp, resp.GetResultCode())\n\t}\n}\n\nfunc (c *Client) handleTellAllResponse(resp *message.TellAllResponse) {\n\tif resp.GetSuccess() {\n\t\tUIPrintln(\"sent.\")\n\t} else {\n\t\tUIPrintResponseError(resp, resp.GetResultCode())\n\t}\n}\n\n\n\nfunc (c *Client) handleTellAllNotification(note *message.TellAllNotification) ", "output": "{\n\tif note.GetSuccess() {\n\t\tUIPrintf(\"tell_all %s> %s\", note.Sender, note.Value)\n\t} else {\n\t\tUIPrintResponseError(note, note.GetResultCode())\n\t}\n}"} {"input": "package memory\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/square/quotaservice/buckets\"\n\t\"github.com/square/quotaservice/config\"\n)\n\nvar factory = NewBucketFactory()\n\nfunc TestMain(m *testing.M) {\n\tsetUp()\n\tr := m.Run()\n\tos.Exit(r)\n}\n\n\n\nfunc TestTokenAcquisition(t *testing.T) {\n\tbucket := factory.NewBucket(\"memory\", \"memory\", config.NewDefaultBucketConfig(\"\"), false)\n\tbuckets.TestTokenAcquisition(t, bucket)\n}\n\nfunc TestGC(t *testing.T) {\n\tbuckets.TestGC(t, factory, \"memory\")\n}\n\nfunc setUp() ", "output": "{\n\tfactory.Init(config.NewDefaultServiceConfig())\n}"} {"input": "package controllers\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/golang/glog\"\n\n\tutilruntime \"k8s.io/apimachinery/pkg/util/runtime\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\n\n\n\n\nfunc WaitForCacheSync(controllerName string, stopCh <-chan struct{}, cacheSyncs ...cache.InformerSynced) bool ", "output": "{\n\tglog.Infof(\"Waiting for caches to sync for %s controller\", controllerName)\n\n\tif !cache.WaitForCacheSync(stopCh, cacheSyncs...) {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Unable to sync caches for %s controller\", controllerName))\n\t\treturn false\n\t}\n\n\tglog.Infof(\"Caches are synced for %s controller\", controllerName)\n\treturn true\n}"} {"input": "package wire\n\nimport (\n\t\"time\"\n)\n\n\ntype periodicTask struct {\n\tperiod time.Duration\n\ttask func()\n\tticker *time.Ticker\n\tstop chan struct{}\n}\n\nfunc newPeriodicTask(period time.Duration, task func()) *periodicTask {\n\treturn &periodicTask{\n\t\tperiod: period,\n\t\ttask: task,\n\t}\n}\n\n\n\n\n\n\nfunc (pt *periodicTask) Stop() {\n\tif pt.ticker == nil {\n\t\treturn\n\t}\n\n\tpt.ticker.Stop()\n\tclose(pt.stop)\n\n\tpt.ticker = nil\n\tpt.stop = nil\n}\n\nfunc (pt *periodicTask) poll(ticker *time.Ticker, stop chan struct{}) {\n\tfor {\n\t\tselect {\n\t\tcase <-stop:\n\t\t\treturn \n\t\tdefault:\n\t\t}\n\n\t\tselect {\n\t\tcase <-stop:\n\t\t\treturn \n\t\tcase <-ticker.C:\n\t\t\tpt.task()\n\t\t}\n\t}\n}\n\nfunc (pt *periodicTask) Start() ", "output": "{\n\tif pt.ticker != nil || pt.period <= 0 {\n\t\treturn\n\t}\n\n\tpt.ticker = time.NewTicker(pt.period)\n\tpt.stop = make(chan struct{})\n\tgo pt.poll(pt.ticker, pt.stop)\n}"} {"input": "package rest\n\nimport (\n\t\"net/http\"\n\t\"sync\"\n\n\t\"github.com/gorilla/mux\"\n\t\"gopkg.in/raiqub/web.v0\"\n)\n\n\n\n\n\ntype Rest struct {\n\trouter *mux.Router\n\troutes Routes\n\tmiddlePublic web.Chain\n\tmiddlePrivate web.Chain\n\tcors *CORSHandler\n\tprepare sync.Once\n}\n\n\nfunc NewRest() *Rest {\n\treturn &Rest{\n\t\tnil,\n\t\tmake(Routes, 0),\n\t\tmake(web.Chain, 0),\n\t\tmake(web.Chain, 0),\n\t\tnil,\n\t\tsync.Once{},\n\t}\n}\n\n\nfunc (rest *Rest) AddMiddlewarePrivate(m web.MiddlewareFunc) {\n\trest.middlePrivate = append(rest.middlePrivate, m)\n}\n\n\nfunc (rest *Rest) AddMiddlewarePublic(m web.MiddlewareFunc) {\n\trest.middlePublic = append(rest.middlePublic, m)\n}\n\n\nfunc (rest *Rest) AddResource(r Routable) {\n\trest.routes = append(rest.routes, r.Routes()...)\n}\n\n\nfunc (rest *Rest) EnableCORS() {\n\trest.cors = NewCORSHandler()\n}\n\n\n\n\nfunc (rest *Rest) ResourcesRoutes() Routes {\n\tresult := make(Routes, len(rest.routes))\n\tcopy(result, rest.routes)\n\n\treturn result\n}\n\n\nfunc (rest *Rest) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\trest.prepare.Do(rest.initRouter)\n\trest.router.ServeHTTP(w, req)\n}\n\n\nfunc Vars(r *http.Request) RouteVars {\n\treturn mux.Vars(r)\n}\n\nfunc (rest *Rest) initRouter() ", "output": "{\n\tif rest.cors != nil {\n\t\trest.routes = append(rest.routes,\n\t\t\trest.cors.CreatePreflight(rest.routes)...)\n\t}\n\n\trest.router = mux.NewRouter().StrictSlash(true)\n\tfor _, r := range rest.routes {\n\t\tmiddlewares := rest.middlePublic\n\t\tif r.MustAuth == true {\n\t\t\tmiddlewares = rest.middlePrivate\n\t\t}\n\n\t\tif rest.cors != nil {\n\t\t\tmiddlewares = append(middlewares,\n\t\t\t\t(&CORSMiddleware{*rest.cors, r.MustAuth}).Handle)\n\t\t}\n\n\t\trest.router.\n\t\t\tMethods(r.Method).\n\t\t\tPath(r.Path).\n\t\t\tName(r.Name).\n\t\t\tHandler(middlewares.Get(r.ActionFunc))\n\t}\n}"} {"input": "package libra\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n)\n\ntype validator struct {\n\tname string\n\tprogram\n\tstdin io.Reader\n}\n\nfunc (v validator) Name() string {\n\treturn v.name\n}\n\nfunc (v validator) Run() Status {\n\tstdout := new(bytes.Buffer)\n\tstderr := new(bytes.Buffer)\n\tv.program.cmd.Stdin = v.stdin\n\tv.program.cmd.Stdout = stdout\n\tv.program.cmd.Stderr = stderr\n\tres := v.program.Run()\n\tif res.Code != OK {\n\t\treturn Status{\n\t\t\tCode: RE,\n\t\t\tMsg: fmt.Sprintf(\"%v\", stderr.String()),\n\t\t}\n\t}\n\treturn res\n}\n\ntype valJob struct {\n\tabstractJob\n\tinputs []Input\n}\n\n\ntype Input interface {\n\tName() string\n\tReader() io.Reader\n}\n\nfunc (job valJob) Subtasks() []Task {\n\tret := make([]Task, len(job.inputs))\n\tfor i, v := range job.inputs {\n\t\tprog, _ := newProgram(job.src.Exec)\n\t\tret[i] = validator{name: v.Name(), program: prog, stdin: v.Reader()}\n\t}\n\treturn ret\n}\n\n\n\n\nfunc ValJob(src Src, inputs []Input) Job ", "output": "{\n\tret := valJob{}\n\tret.src = src\n\tret.inputs = inputs\n\treturn ret\n}"} {"input": "package iso20022\n\n\ntype ReportStatusAndReason1 struct {\n\n\tRelatedReference *Max35Text `xml:\"RltdRef\"`\n\n\tStatus *Status2Code `xml:\"Sts\"`\n\n\tRejected []*RejectedStatusReason9Choice `xml:\"Rjctd\"`\n}\n\n\n\nfunc (r *ReportStatusAndReason1) SetStatus(value string) {\n\tr.Status = (*Status2Code)(&value)\n}\n\nfunc (r *ReportStatusAndReason1) AddRejected() *RejectedStatusReason9Choice {\n\tnewValue := new(RejectedStatusReason9Choice)\n\tr.Rejected = append(r.Rejected, newValue)\n\treturn newValue\n}\n\nfunc (r *ReportStatusAndReason1) SetRelatedReference(value string) ", "output": "{\n\tr.RelatedReference = (*Max35Text)(&value)\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n)\n\nconst (\n\tsemanticAlphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-\"\n\n\tsemanticBuildAlphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-.\"\n)\n\n\n\nconst (\n\tAppName string = \"dcrdata\"\n\tAppMajor uint = 6\n\tAppMinor uint = 1\n\tAppPatch uint = 0\n)\n\n\nvar (\n\tappPreRelease = \"pre\"\n\n\tappBuild = \"dev\"\n)\n\n\n\nfunc Version() string {\n\tversion := fmt.Sprintf(\"%d.%d.%d\", AppMajor, AppMinor, AppPatch)\n\n\tpreRelease := normalizePreRelString(appPreRelease)\n\tif preRelease != \"\" {\n\t\tversion = fmt.Sprintf(\"%s-%s\", version, preRelease)\n\t}\n\n\tbuild := normalizeBuildString(appBuild)\n\tif build != \"\" {\n\t\tversion = fmt.Sprintf(\"%s+%s\", version, build)\n\t}\n\n\treturn version\n}\n\n\n\nfunc normalizeSemString(str, alphabet string) string {\n\tvar result bytes.Buffer\n\tfor _, r := range str {\n\t\tif strings.ContainsRune(alphabet, r) {\n\t\t\tresult.WriteRune(r)\n\t\t}\n\t}\n\treturn result.String()\n}\n\n\n\n\n\nfunc normalizePreRelString(str string) string {\n\treturn normalizeSemString(str, semanticAlphabet)\n}\n\n\n\n\n\n\n\nfunc normalizeBuildString(str string) string ", "output": "{\n\treturn normalizeSemString(str, semanticBuildAlphabet)\n}"} {"input": "package file\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/openshift/source-to-image/pkg/api\"\n\t\"github.com/openshift/source-to-image/pkg/scm/git\"\n\ttestfs \"github.com/openshift/source-to-image/pkg/test/fs\"\n)\n\n\n\nfunc TestDownloadWithContext(t *testing.T) {\n\tfs := &testfs.FakeFileSystem{}\n\tf := &File{fs}\n\n\tconfig := &api.Config{\n\t\tSource: git.MustParse(\"/foo\"),\n\t\tContextDir: \"bar\",\n\t}\n\tinfo, err := f.Download(config)\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error %v\", err)\n\t}\n\tif filepath.ToSlash(fs.CopySource) != \"/foo/bar\" {\n\t\tt.Errorf(\"Unexpected fs.CopySource %s\", fs.CopySource)\n\t}\n\tif info.Location != config.Source.URL.Path || info.ContextDir != config.ContextDir {\n\t\tt.Errorf(\"Unexpected info\")\n\t}\n}\n\nfunc TestDownload(t *testing.T) ", "output": "{\n\tfs := &testfs.FakeFileSystem{}\n\tf := &File{fs}\n\n\tconfig := &api.Config{\n\t\tSource: git.MustParse(\"/foo\"),\n\t}\n\tinfo, err := f.Download(config)\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error %v\", err)\n\t}\n\tif fs.CopySource != \"/foo\" {\n\t\tt.Errorf(\"Unexpected fs.CopySource %s\", fs.CopySource)\n\t}\n\tif info.Location != config.Source.URL.Path || info.ContextDir != config.ContextDir {\n\t\tt.Errorf(\"Unexpected info\")\n\t}\n}"} {"input": "package console\n\nimport \"github.com/accurateproject/accurate/api/v1\"\n\nfunc init() {\n\tc := &CmdExecuteScheduledActions{\n\t\tname: \"scheduler_execute\",\n\t\trpcMethod: \"ApiV1.ExecuteScheduledActions\",\n\t\trpcParams: &v1.AttrsExecuteScheduledActions{},\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdExecuteScheduledActions struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrsExecuteScheduledActions\n\t*CommandExecuter\n}\n\n\n\nfunc (self *CmdExecuteScheduledActions) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdExecuteScheduledActions) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrsExecuteScheduledActions{}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdExecuteScheduledActions) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdExecuteScheduledActions) RpcResult() interface{} {\n\tvar s string\n\treturn &s\n}\n\nfunc (self *CmdExecuteScheduledActions) Name() string ", "output": "{\n\treturn self.name\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com/alexandres/poormanscdn/client\"\n)\n\nvar path, cdnUrl, method, refererHost, userHost, secret string\nvar modified, expires int64\n\n\n\nfunc main() {\n\tflag.Parse()\n\tif cdnUrl == \"\" || secret == \"\" {\n\t\tlog.Fatal(\"cdnurl and secret are mandatory\")\n\t}\n\tlastModifiedAt := time.Unix(modified, 0)\n\texpiresAt := time.Unix(expires, 0)\n\tp := client.SigParams{\n\t\tMethod: method,\n\t\tPath: client.TrimPath(path),\n\t\tUserHost: userHost,\n\t\tRefererHost: refererHost,\n\t\tModified: lastModifiedAt,\n\t\tExpires: expiresAt,\n\t}\n\turl, err := client.GetSignedUrl(secret, cdnUrl, p)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Print(url)\n}\n\nfunc init() ", "output": "{\n\tflag.StringVar(&cdnUrl, \"cdnurl\", \"\", \"cdnurl\")\n\tflag.StringVar(&method, \"method\", \"GET\", \"method\")\n\tflag.StringVar(&refererHost, \"refererhost\", \"\", \"restrict referer host\")\n\tflag.StringVar(&userHost, \"userhost\", \"\", \"restrict user host\")\n\tflag.Int64Var(&modified, \"modified\", 0, \"modified\")\n\tflag.Int64Var(&expires, \"expires\", 0, \"expires\")\n\tflag.StringVar(&path, \"path\", \"\", \"path\")\n\tflag.StringVar(&secret, \"secret\", \"\", \"secret\")\n}"} {"input": "package profile\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\n\n\nfunc TestEmptyProfile(t *testing.T) ", "output": "{\n\tvar buf bytes.Buffer\n\tp, err := Parse(&buf)\n\tif err != nil {\n\t\tt.Error(\"Want no error, got\", err)\n\t}\n\tif p == nil {\n\t\tt.Fatal(\"Want a valid profile, got \")\n\t}\n\tif !p.Empty() {\n\t\tt.Errorf(\"Profile should be empty, got %#v\", p)\n\t}\n}"} {"input": "package bookshelf\n\n\ntype Book struct {\n\tID int64\n\tTitle string\n\tAuthor string\n\tPublishedDate string\n\tImageURL string\n\tDescription string\n\tCreatedBy string\n\tCreatedByID string\n}\n\n\n\nfunc (b *Book) CreatedByDisplayName() string {\n\tif b.CreatedByID == \"anonymous\" {\n\t\treturn \"Anonymous\"\n\t}\n\treturn b.CreatedBy\n}\n\n\n\n\n\ntype BookDatabase interface {\n\tListBooks() ([]*Book, error)\n\n\tListBooksCreatedBy(userID string) ([]*Book, error)\n\n\tGetBook(id int64) (*Book, error)\n\n\tAddBook(b *Book) (id int64, err error)\n\n\tDeleteBook(id int64) error\n\n\tUpdateBook(b *Book) error\n\n\tClose()\n}\n\nfunc (b *Book) SetCreatorAnonymous() ", "output": "{\n\tb.CreatedBy = \"\"\n\tb.CreatedByID = \"anonymous\"\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"fmt\"\n\t\"gsf/log\"\n)\n\ntype Config struct {\n\tDaemon \t\tint \t\t\t\t\t\t`json:\"daemon\"`\t\t\t\t\t\n\tServerAddr \tstring \t\t\t\t\t\t`json:\"server_addr\"`\t\t\t\n\tLogConf \tlog.LoggerConfig\t\t\t`json:\"log_conf\"`\t\t\t\t\n}\n\nvar config = &Config{}\nvar logger *log.Logger = nil\n\nfunc (c *Config) Init(filename string) error {\n\tdata, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = json.Unmarshal(data, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlogger, err = log.NewByConfig(&config.LogConf)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\n\nfunc (c *Config) String() string ", "output": "{\n\tdata, err := json.Marshal(c)\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"config json failed, err:\", err)\n\t}\n\treturn string(data)\n}"} {"input": "package sys\n\nimport (\n\t\"github.com/u-root/u-root/pkg/termios\"\n\t\"os\"\n)\n\n\n\n\nfunc IsATTY(file *os.File) bool ", "output": "{\n\t_, err := termios.GetTermios(file.Fd())\n\treturn err == nil\n}"} {"input": "package utils\n\nimport \"bytes\"\n\n\n\ntype CompositeError []error\n\n\nfunc (c *CompositeError) Error() string {\n\tvar b bytes.Buffer\n\tfor ind, err := range *c {\n\t\t_, _ = b.WriteString(err.Error())\n\t\tif ind == len(*c)-1 {\n\t\t\tbreak\n\t\t}\n\t\t_, _ = b.WriteRune('\\n')\n\t}\n\n\treturn b.String()\n}\n\n\nfunc (c *CompositeError) AppendError(err error) {\n\tif err != nil {\n\t\t*c = append(*c, err)\n\t}\n}\n\n\nfunc (c *CompositeError) Empty() bool {\n\treturn c == nil || len(*c) == 0\n}\n\n\n\n\n\nfunc NewCompositeError(errors ...error) error ", "output": "{\n\tres := &CompositeError{}\n\tfor _, err := range errors {\n\t\tres.AppendError(err)\n\t}\n\tif res.Empty() {\n\t\treturn nil\n\t}\n\treturn res\n}"} {"input": "package paul\n\nimport (\n\t\"github.com/FastAndFurious/fnf.gopaul/types\"\n\t\"github.com/FastAndFurious/fnf.gopaul/broker\"\n\t\"strings\"\n\t\"github.com/FastAndFurious/fnf.gopaul/util\"\n)\n\nconst (\n\tPLOTTER_LOGGER=\"PlotterLogger\"\n\tDISPLAY_WIDTH=100\n)\n\ntype PlotterLogger struct {\n\tobservations chan types.Message\n\tstart chan types.Message\n\tmin float32\n\tmax float32\n\tbroker.Logging\n}\n\n\n\n\nfunc (theLogger *PlotterLogger) work() {\n\n\tvar offset int64 = 0;\n\tfor {\n\t\tselect {\n\t\tcase actual := <-theLogger.observations:\n\t\t\tpayload := actual.(types.ObjectMessage).Payload.(types.Observation)\n\t\t\tt := payload.Timestamp - offset\n\t\t\tv := payload.Value\n\t\t\tif v < theLogger.min {\n\t\t\t\ttheLogger.min = v\n\t\t\t}\n\t\t\tif v > theLogger.max {\n\t\t\t\ttheLogger.max = v\n\t\t\t}\n\t\t\td := theLogger.max - theLogger.min\n\t\t\tp := (v - theLogger.min) * float32(DISPLAY_WIDTH) / d\n\t\t\tindent := strings.Repeat(\" \", int(p))\n\n\t\t\ttheLogger.Info(\"%06d: %s%d\", t, indent, int(v))\n\n\t\tcase actual := <-theLogger.start:\n\t\t\tpayload := actual.(types.ObjectMessage).Payload.(types.StartMessage)\n\t\t\ttheLogger.Info(\"StartMessage at %d\", payload.Timestamp)\n\t\t\toffset = payload.Timestamp\n\t\t\tutil.Logfln(\"StartMsg %v\", actual)\n\t\t}\n\t}\n\ttheLogger.Warn(\"Should never leave the go loop\")\n}\n\nfunc NewPlotterLogger(name string, source string, min float32, max float32, sink string, severity *types.Severity) *PlotterLogger ", "output": "{\n\n\tobservations := make(chan types.Message)\n\tstart := make(chan types.Message)\n\tbroker.GetBroker().SubscribeToInfo(PLOTTER_LOGGER, types.ProducerInfo{ source, \"\", types.ObservationType}, observations)\n\tbroker.GetBroker().SubscribeToInfo(PLOTTER_LOGGER, types.ProducerInfo{ \"\", \"\", types.StartMessageType}, start)\n\n\tinstance := &PlotterLogger{observations, start, min, max, broker.NewSpecifiedLogging( name, sink, severity) }\n\n\tgo instance.work()\n\n\treturn instance\n}"} {"input": "package Admin\n\nimport (\n\t\"github.com/jesusslim/slimgo\"\n)\n\ntype CommonController struct {\n\tslimgo.Controller\n}\n\n\n\nfunc (this *CommonController) Show() ", "output": "{\n\tthis.Data[\"json\"] = \"show it\"\n\tthis.ServeJson(nil)\n}"} {"input": "package main\n\n\nfunc (b bucketPerms) isValidBucketPERM() bool {\n\tswitch true {\n\tcase b.isPrivate():\n\t\tfallthrough\n\tcase b.isReadOnly():\n\t\tfallthrough\n\tcase b.isPublic():\n\t\tfallthrough\n\tcase b.isAuthorized():\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n\ntype bucketPerms string\n\n\nconst (\n\tbucketPrivate = bucketPerms(\"private\")\n\tbucketReadOnly = bucketPerms(\"readonly\")\n\tbucketPublic = bucketPerms(\"public\")\n\tbucketAuthorized = bucketPerms(\"authorized\")\n)\n\nfunc (b bucketPerms) String() string {\n\tif !b.isValidBucketPERM() {\n\t\treturn string(b)\n\t}\n\tif b.isReadOnly() {\n\t\treturn \"public-read\"\n\t}\n\tif b.isPublic() {\n\t\treturn \"public-read-write\"\n\t}\n\tif b.isAuthorized() {\n\t\treturn \"authenticated-read\"\n\t}\n\treturn \"private\"\n}\n\nfunc aclToPerms(acl string) bucketPerms {\n\tswitch acl {\n\tcase \"private\":\n\t\treturn bucketPerms(\"private\")\n\tcase \"public-read\":\n\t\treturn bucketPerms(\"readonly\")\n\tcase \"public-read-write\":\n\t\treturn bucketPerms(\"public\")\n\tcase \"authenticated-read\":\n\t\treturn bucketPerms(\"authorized\")\n\tdefault:\n\t\treturn bucketPerms(acl)\n\t}\n}\n\n\nfunc (b bucketPerms) isPrivate() bool {\n\treturn b == bucketPrivate\n}\n\n\nfunc (b bucketPerms) isReadOnly() bool {\n\treturn b == bucketReadOnly\n}\n\n\nfunc (b bucketPerms) isPublic() bool {\n\treturn b == bucketPublic\n}\n\n\n\n\nfunc (b bucketPerms) isAuthorized() bool ", "output": "{\n\treturn b == bucketAuthorized\n}"} {"input": "package main\n\nimport (\n\t\"github.com/joist-engineering/force/util\"\n)\n\nvar cmdWhoami = &Command{\n\tRun: runWhoami,\n\tUsage: \"whoami\",\n\tShort: \"Show information about the active account\",\n\tLong: `\nShow information about the active account\n\nExamples:\n\n force whoami\n`,\n}\n\n\n\nfunc runWhoami(cmd *Command, args []string) ", "output": "{\n\tforce, _ := ActiveForce()\n\tme, err := force.Whoami()\n\tif err != nil {\n\t\tutil.ErrorAndExit(err.Error())\n\t} else if len(args) == 0 {\n\t\tDisplayForceRecord(me)\n\t}\n}"} {"input": "package tests\n\nimport (\n\t\"database/sql\"\n\t_ \"github.com/lib/pq\"\n\t\"log\"\n\t\"strings\"\n)\n\n\n\nfunc GetDBConnection(dbHost string, userid string, dbPort string, database string, password string) (*sql.DB, error) {\n\n\tvar dbConn *sql.DB\n\tvar err error\n\n\tif password == \"\" {\n\t\tdbConn, err = sql.Open(\"postgres\", \"sslmode=disable user=\"+userid+\" host=\"+dbHost+\" port=\"+dbPort+\" dbname=\"+database)\n\t} else {\n\t\tdbConn, err = sql.Open(\"postgres\", \"sslmode=disable user=\"+userid+\" host=\"+dbHost+\" port=\"+dbPort+\" dbname=\"+database+\" password=\"+password)\n\t}\n\tif err != nil {\n\t\tlog.Println(\"error in getting connection :\" + err.Error())\n\t}\n\treturn dbConn, err\n}\n\nfunc Connect() (*sql.DB, error) ", "output": "{\n\tvar conn *sql.DB\n\tlog.SetFlags(log.Ltime | log.Lmicroseconds)\n\n\tvar err error\n\tvar hostportarr = strings.Split(HostPort, \":\")\n\tvar dbHost = hostportarr[0]\n\tvar dbPort = hostportarr[1]\n\n\tlog.Println(\"connecting to host:\" + dbHost + \" port:\" + dbPort + \" user:\" + userid + \" password:\" + password + \" database:\" + database)\n\tconn, err = GetDBConnection(dbHost, userid, dbPort, database, password)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn conn, err\n}"} {"input": "package util\n\n\nfunc Min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n\n\nfunc Max64(a, b int64) int64 {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n\n\n\n\nfunc Min64(a, b int64) int64 ", "output": "{\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}"} {"input": "package spanner\n\nimport (\n\t_ \"github.com/rakyll/go-sql-driver-spanner\" \n\t\"github.com/xo/usql/drivers\"\n)\n\n\n\nfunc init() ", "output": "{\n\tdrivers.Register(\"spanner\", drivers.Driver{})\n}"} {"input": "package iso20022\n\n\ntype CorporateActionElection1 struct {\n\n\tOptionType *CorporateActionOption1FormatChoice `xml:\"OptnTp\"`\n\n\tOptionNumber *Exact3NumericText `xml:\"OptnNb\"`\n\n\tOriginalInstructedQuantity *UnitOrFaceAmount1Choice `xml:\"OrgnlInstdQty\"`\n\n\tRemainingQuantity *UnitOrFaceAmount1Choice `xml:\"RmngQty\"`\n}\n\n\n\nfunc (c *CorporateActionElection1) SetOptionNumber(value string) {\n\tc.OptionNumber = (*Exact3NumericText)(&value)\n}\n\nfunc (c *CorporateActionElection1) AddOriginalInstructedQuantity() *UnitOrFaceAmount1Choice {\n\tc.OriginalInstructedQuantity = new(UnitOrFaceAmount1Choice)\n\treturn c.OriginalInstructedQuantity\n}\n\nfunc (c *CorporateActionElection1) AddRemainingQuantity() *UnitOrFaceAmount1Choice {\n\tc.RemainingQuantity = new(UnitOrFaceAmount1Choice)\n\treturn c.RemainingQuantity\n}\n\nfunc (c *CorporateActionElection1) AddOptionType() *CorporateActionOption1FormatChoice ", "output": "{\n\tc.OptionType = new(CorporateActionOption1FormatChoice)\n\treturn c.OptionType\n}"} {"input": "package target\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"testing\"\n)\n\nvar (\n\twrkdir string\n)\n\nfunc init() {\n\tlog.SetOutput(ioutil.Discard)\n\twrkdir, _ = os.Getwd()\n}\n\ntype badWriter struct {\n}\n\nfunc (bw badWriter) Write(p []byte) (n int, err error) {\n\treturn 0, fmt.Errorf(\"bad\")\n}\n\nfunc TestNewMake(t *testing.T) {\n\ttc, _, _ := createTestConfigs(t, nil, nil)\n\t_, err := NewMake(tc)\n\tok(t, err)\n}\n\nfunc TestMakeRun(t *testing.T) {\n\ttc, tcW, _ := createTestConfigs(t, nil, nil)\n\tm, _ := NewMake(tc)\n\terr := m.Run(\"ron:prep\")\n\tok(t, err)\n\twant := \"hello\\nprep1\\nprep2\\nprep3\\nprep4\\ngoodbye\\n\"\n\tequals(t, want, tcW.String())\n}\n\nfunc TestMakeRunErr(t *testing.T) {\n\ttc, _, _ := createTestConfigs(t, nil, nil)\n\tm, _ := NewMake(tc)\n\terr := m.Run(\"err\")\n\tif err == nil {\n\t\tt.Fatal(\"expected target not found\")\n\t}\n}\n\n\n\nfunc TestMakeRunNoTarget(t *testing.T) ", "output": "{\n\ttc, _, _ := createTestConfigs(t, nil, nil)\n\tm, _ := NewMake(tc)\n\terr := m.Run(\"prop\")\n\tif err == nil {\n\t\tt.Fatal(\"expected target not found\")\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestAdvertise(t *testing.T) {\n\tadvertiseStr := \"127.0.0.1\"\n\tadvertise := new(Advertise)\n\terr := advertise.parse(advertiseStr)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestServer(t *testing.T) {\n\tsm := new(ServerManage)\n\tdiscoveryStr := \"redis://root@127.0.0.1:6379/dragonfly/master\"\n\tdiscovery := new(Discovery)\n\tdiscovery.parse(discoveryStr)\n\tadvertiseStr := \"127.0.0.1\"\n\tadvertise := new(Advertise)\n\tadvertise.parse(advertiseStr)\n\tserver, err := discovery.init()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tsm.server = server\n\tsm.quit = make(chan bool)\n\tsm.clear = make(chan bool)\n\tsm.run(advertise)\n\tsm.stop()\n}\n\nfunc TestDiscovery(t *testing.T) ", "output": "{\n\tdiscoveryStr := \"redis://root@127.0.0.1:6379/dragonfly/master\"\n\tdiscovery := new(Discovery)\n\terr := discovery.parse(discoveryStr)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}"} {"input": "package retrieval\n\nimport (\n\t\"time\"\n\n\t\"github.com/prometheus/common/model\"\n\n\t\"github.com/prometheus/prometheus/config\"\n)\n\ntype nopAppender struct{}\n\nfunc (a nopAppender) Append(*model.Sample) {\n}\n\ntype slowAppender struct{}\n\nfunc (a slowAppender) Append(*model.Sample) {\n\ttime.Sleep(time.Millisecond)\n\treturn\n}\n\ntype collectResultAppender struct {\n\tresult model.Samples\n}\n\n\n\n\n\ntype fakeTargetProvider struct {\n\tsources []string\n\tupdate chan *config.TargetGroup\n}\n\nfunc (tp *fakeTargetProvider) Run(ch chan<- *config.TargetGroup, done <-chan struct{}) {\n\tdefer close(ch)\n\tfor {\n\t\tselect {\n\t\tcase tg := <-tp.update:\n\t\t\tch <- tg\n\t\tcase <-done:\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (tp *fakeTargetProvider) Sources() []string {\n\treturn tp.sources\n}\n\nfunc (a *collectResultAppender) Append(s *model.Sample) ", "output": "{\n\tfor ln, lv := range s.Metric {\n\t\tif len(lv) == 0 {\n\t\t\tdelete(s.Metric, ln)\n\t\t}\n\t}\n\ta.result = append(a.result, s)\n}"} {"input": "package fasthttpradix\n\n\nimport (\n\t\"github.com/valyala/fasthttp\"\n\trr \"github.com/byte-mug/golibs/radixroute\"\n\t\"strings\"\n)\n\n\nfunc NormPath(str string) string {\n\treturn \"/\"+strings.Trim(str,\"/\")+\"/\"\n}\n\nfunc InvalidPath(ctx *fasthttp.RequestCtx) {\n\tctx.SetBody([]byte(\"404 Not Found\\n\"))\n\tctx.SetStatusCode(fasthttp.StatusNotFound)\n}\n\ntype handling struct{\n\thandle fasthttp.RequestHandler\n}\ntype Router struct{\n\troutes map[string]*rr.Tree\n}\n\nfunc (r *Router) Handle(method string,path string,handler fasthttp.RequestHandler) {\n\tif handler==nil { panic(\"handler must not be nil\") }\n\th := &handling{handler}\n\tcpath := []byte(NormPath(path))\n\tbpath := cpath[:len(cpath)-1]\n\tif method==\"\" {\n\t\tmethod = \"DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT\"\n\t}\n\tfor _,m := range strings.Split(method,\",\") {\n\t\trrt := r.getOrCreate(m)\n\t\trrt.InsertRoute(bpath,h)\n\t\trrt.InsertRoute(cpath,h)\n\t}\n}\nfunc (r *Router) RequestHandler(ctx *fasthttp.RequestCtx) {\n\tt := r.routes[string(ctx.Method())]\n\tif t==nil {\n\t\tInvalidPath(ctx)\n\t\treturn\n\t}\n\ti,_ := t.Get(ctx.Path(),ctx.SetUserValue)\n\th,ok := i.(*handling)\n\tif !ok {\n\t\tInvalidPath(ctx)\n\t\treturn\n\t}\n\th.handle(ctx)\n}\n\nfunc (r *Router) getOrCreate(m string) *rr.Tree ", "output": "{\n\tt := r.routes[m]\n\tif t!=nil { return t }\n\tif r.routes==nil { r.routes = make(map[string]*rr.Tree) }\n\tr.routes[m] = rr.New()\n\treturn r.routes[m]\n}"} {"input": "package xen\n\nimport (\n\t\"github.com/solo-io/unik/pkg/types\"\n)\n\n\n\nfunc (p *XenProvider) ListImages() ([]*types.Image, error) ", "output": "{\n\timages := []*types.Image{}\n\tfor _, image := range p.state.GetImages() {\n\t\timages = append(images, image)\n\t}\n\treturn images, nil\n}"} {"input": "package ansiwriter\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\ntype Modifier func() string\n\nfunc escapeANSI(code int) string {\n\treturn fmt.Sprintf(\"\\033[%dm\", code)\n}\n\nfunc Bold() string { return escapeANSI(1) }\nfunc Black() string { return escapeANSI(30) }\nfunc Red() string { return escapeANSI(31) }\nfunc Green() string { return escapeANSI(32) }\nfunc Yellow() string { return escapeANSI(33) }\nfunc Blue() string { return escapeANSI(34) }\n\nfunc Cyan() string { return escapeANSI(36) }\nfunc White() string { return escapeANSI(37) }\n\ntype awr struct {\n\tio.Writer\n\tmodifiers []Modifier\n}\n\n\n\n\nfunc New(w io.Writer, mods ...Modifier) io.Writer {\n\treturn awr{w, mods}\n}\n\nfunc (a awr) Write(b []byte) (n int, err error) {\n\tfor _, mod := range a.modifiers {\n\t\ta.Writer.Write([]byte(mod()))\n\t}\n\tn, err = a.Writer.Write(b)\n\t_, _ = a.Writer.Write([]byte(\"\\033[0m\"))\n\treturn\n}\n\nfunc Magenta() string ", "output": "{ return escapeANSI(35) }"} {"input": "package pump\n\nimport (\n\t\"math\"\n\n\t\"github.com/tidepool-org/platform/data\"\n\t\"github.com/tidepool-org/platform/structure\"\n)\n\nconst (\n\tBolusAmountMaximumUnitsUnits = \"Units\"\n\tBolusAmountMaximumValueUnitsMaximum = 100.0\n\tBolusAmountMaximumValueUnitsMinimum = 0.0\n)\n\nfunc BolusAmountMaximumUnits() []string {\n\treturn []string{\n\t\tBolusAmountMaximumUnitsUnits,\n\t}\n}\n\ntype BolusAmountMaximum struct {\n\tUnits *string `json:\"units,omitempty\" bson:\"units,omitempty\"`\n\tValue *float64 `json:\"value,omitempty\" bson:\"value,omitempty\"`\n}\n\nfunc ParseBolusAmountMaximum(parser structure.ObjectParser) *BolusAmountMaximum {\n\tif !parser.Exists() {\n\t\treturn nil\n\t}\n\tdatum := NewBolusAmountMaximum()\n\tparser.Parse(datum)\n\treturn datum\n}\n\nfunc NewBolusAmountMaximum() *BolusAmountMaximum {\n\treturn &BolusAmountMaximum{}\n}\n\nfunc (b *BolusAmountMaximum) Parse(parser structure.ObjectParser) {\n\tb.Units = parser.String(\"units\")\n\tb.Value = parser.Float64(\"value\")\n}\n\nfunc (b *BolusAmountMaximum) Validate(validator structure.Validator) {\n\tvalidator.String(\"units\", b.Units).Exists().OneOf(BolusAmountMaximumUnits()...)\n\tvalidator.Float64(\"value\", b.Value).Exists().InRange(BolusAmountMaximumValueRangeForUnits(b.Units))\n}\n\nfunc (b *BolusAmountMaximum) Normalize(normalizer data.Normalizer) {}\n\n\n\nfunc BolusAmountMaximumValueRangeForUnits(units *string) (float64, float64) ", "output": "{\n\tif units != nil {\n\t\tswitch *units {\n\t\tcase BolusAmountMaximumUnitsUnits:\n\t\t\treturn BolusAmountMaximumValueUnitsMinimum, BolusAmountMaximumValueUnitsMaximum\n\t\t}\n\t}\n\treturn -math.MaxFloat64, math.MaxFloat64\n}"} {"input": "package main\n\n\n\n\n\ntype Scope struct {\n\tparent *Scope \n\tentities map[string]*Decl\n}\n\nfunc NewScope(outer *Scope) *Scope {\n\ts := new(Scope)\n\ts.parent = outer\n\ts.entities = make(map[string]*Decl)\n\treturn s\n}\n\n\n\n\n\nfunc (s *Scope) addNamedDecl(d *Decl) *Decl {\n\treturn s.addDecl(d.Name, d)\n}\n\nfunc (s *Scope) addDecl(name string, d *Decl) *Decl {\n\tdecl, ok := s.entities[name]\n\tif !ok {\n\t\ts.entities[name] = d\n\t\treturn d\n\t}\n\treturn decl\n}\n\nfunc (s *Scope) replaceDecl(name string, d *Decl) {\n\ts.entities[name] = d\n}\n\nfunc (s *Scope) mergeDecl(d *Decl) {\n\tdecl, ok := s.entities[d.Name]\n\tif !ok {\n\t\ts.entities[d.Name] = d\n\t} else {\n\t\tdecl := decl.DeepCopy()\n\t\tdecl.ExpandOrReplace(d)\n\t\ts.entities[d.Name] = decl\n\t}\n}\n\nfunc (s *Scope) lookup(name string) *Decl {\n\tdecl, ok := s.entities[name]\n\tif !ok {\n\t\tif s.parent != nil {\n\t\t\treturn s.parent.lookup(name)\n\t\t} else {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn decl\n}\n\nfunc AdvanceScope(s *Scope) (*Scope, *Scope) ", "output": "{\n\tif len(s.entities) == 0 {\n\t\treturn s, s.parent\n\t}\n\treturn NewScope(s), s\n}"} {"input": "package action\n\nimport (\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strings\"\n\t\"fmt\"\n)\n\ntype Http struct {\n\tconfig *ActionConfig\n}\n\nfunc (h *Http) Run() (*Result, error) {\n\turl := h.config.Params.GetString(\"url\")\n\tif url == \"\" {\n\t\treturn nil, fmt.Errorf(\"url parameter required\")\n\t}\n\n\tmethod := h.config.Params.GetString(\"method\")\n\tif method == \"\" {\n\t\tmethod = \"GET\"\n\t} else {\n\t\tmethod = strings.ToUpper(method)\n\t}\n\n\tclient := &http.Client{}\n\n\th.config.Log.Debugf(\"%s %s\", method, url)\n\n\treq, err := http.NewRequest(method, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult, err := h.genResult(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}\n\nfunc (h *Http) genResult(resp *http.Response) (*Result, error) {\n\tdata := make(map[string]interface{})\n\tdata[\"status-code\"] = resp.StatusCode\n\tdata[\"headers\"] = resp.Header\n\n\th.config.Log.Infof(\"%s %s -> %d\", resp.Request.Method, resp.Request.URL.String(), resp.StatusCode)\n\n\tbodyBytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata[\"raw-body\"] = bodyBytes\n\tdata[\"body\"] = string(bodyBytes)\n\n\treturn &Result{\n\t\tData: data,\n\t}, nil\n}\n\n\n\nfunc NewHttp(config *ActionConfig) *Http ", "output": "{\n\treturn &Http{\n\t\tconfig: config,\n\t}\n}"} {"input": "package dom\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\n\ntype Node interface {\n\tString() string\n\tParent() Node\n\tSetParent(node Node)\n\tChildren() []Node\n\tAddChild(child Node)\n\tClone() Node\n}\n\n\ntype Element struct {\n\ttext string\n\tparent Node\n\tchildren []Node\n}\n\n\nfunc NewElement(text string) *Element {\n\treturn &Element{\n\t\ttext: text,\n\t\tparent: nil,\n\t\tchildren: make([]Node, 0),\n\t}\n}\n\n\nfunc (e *Element) Parent() Node {\n\treturn e.parent\n}\n\n\nfunc (e *Element) SetParent(node Node) {\n\te.parent = node\n}\n\n\nfunc (e *Element) Children() []Node {\n\treturn e.children\n}\n\n\n\n\n\n\nfunc (e *Element) Clone() Node {\n\tcopy := &Element{\n\t\ttext: e.text,\n\t\tparent: nil,\n\t\tchildren: make([]Node, 0),\n\t}\n\tfor _, child := range e.children {\n\t\tcopy.AddChild(child)\n\t}\n\treturn copy\n}\n\n\nfunc (e *Element) String() string {\n\tbuffer := bytes.NewBufferString(e.text)\n\n\tfor _, c := range e.Children() {\n\t\ttext := c.String()\n\t\tfmt.Fprintf(buffer, \"\\n %s\", text)\n\t}\n\n\treturn buffer.String()\n}\n\nfunc (e *Element) AddChild(child Node) ", "output": "{\n\tcopy := child.Clone()\n\tcopy.SetParent(e)\n\te.children = append(e.children, copy)\n}"} {"input": "package restic\n\nimport \"syscall\"\n\nfunc (node Node) restoreSymlinkTimestamps(path string, utimes [2]syscall.Timespec) error {\n\treturn nil\n}\n\nfunc (node Node) device() int {\n\treturn int(node.Device)\n}\n\nfunc (s statUnix) atim() syscall.Timespec { return s.Atimespec }\n\nfunc (s statUnix) ctim() syscall.Timespec { return s.Ctimespec }\n\n\nfunc Getxattr(path, name string) ([]byte, error) {\n\treturn nil, nil\n}\n\n\n\nfunc Listxattr(path string) ([]string, error) {\n\treturn nil, nil\n}\n\n\nfunc Setxattr(path, name string, data []byte) error {\n\treturn nil\n}\n\nfunc (s statUnix) mtim() syscall.Timespec ", "output": "{ return s.Mtimespec }"} {"input": "package application\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/garyburd/redigo/redis\"\n)\n\ntype RedisDataStore struct {\n\tHost string\n\tPassword string\n\tpool *redis.Pool\n}\n\nfunc (s *RedisDataStore) checkConnection() error {\n\tc, err := redis.Dial(\"tcp\", s.Host)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = c.Do(\"AUTH\", s.Password)\n\tif err != nil {\n\t\tc.Close()\n\t\treturn err\n\t}\n\tc.Close()\n\treturn nil\n}\n\nfunc (s *RedisDataStore) Initialize() error {\n\terr := s.checkConnection()\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.pool = &redis.Pool{\n\t\tMaxIdle: 5,\n\t\tMaxActive: 5,\n\t\tDial: func() (redis.Conn, error) {\n\t\t\tc, err := redis.Dial(\"tcp\", s.Host)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\t_, err = c.Do(\"AUTH\", s.Password)\n\t\t\tif err != nil {\n\t\t\t\tc.Close()\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn c, nil\n\t\t},\n\t}\n\treturn nil\n}\n\n\n\nfunc (s *RedisDataStore) Set(key string, val []byte) error {\n\tc := s.pool.Get()\n\tdefer c.Close()\n\n\t_, err := c.Do(\"SET\", key, val)\n\treturn err\n}\n\nfunc (s *RedisDataStore) Get(key string) ([]byte, error) ", "output": "{\n\tc := s.pool.Get()\n\tdefer c.Close()\n\n\tval, err := c.Do(\"GET\", key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbytes, ok := val.([]byte)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unable to type-assert response of type %T to []byte\", val)\n\t}\n\treturn bytes, nil\n}"} {"input": "package main\n\nimport (\n\t\"github.com/kataras/iris\"\n)\n\n\n\n\nvar page = struct {\n\tTitle string\n}{\"Welcome\"}\n\n\n\nfunc main() {\n\tapp := newApp()\n\n\tapp.Run(iris.Addr(\":8080\"))\n}\n\nfunc newApp() *iris.Application ", "output": "{\n\tapp := iris.New()\n\tapp.RegisterView(iris.HTML(\"./public\", \".html\"))\n\n\tapp.Get(\"/\", func(ctx iris.Context) {\n\t\tctx.ViewData(\"Page\", page)\n\t\tctx.View(\"index.html\")\n\t})\n\n\n\tassetHandler := app.StaticHandler(\"./public\", false, false)\n\tapp.SPA(assetHandler)\n\n\treturn app\n}"} {"input": "package commands\n\nimport (\n\t\"github.com/codegangsta/cli\"\n\t\"github.com/ryo33/zenv/environment\"\n\t\"github.com/ryo33/zenv/util\"\n)\n\nvar activate = cli.Command{\n\tName: \"activate\",\n\tUsage: \"activate the environment\",\n\tDescription: `\n\t`,\n\tAction: doActivate,\n}\n\n\n\nfunc doActivate(c *cli.Context) ", "output": "{\n\targs := c.Args()\n\tif len(args) == 2 {\n\t\tenvironment.GetGlobalEnv(args[1]).Activate(args[0])\n\t} else {\n\t\tutil.PrintArgumentError(2)\n\t}\n}"} {"input": "package types\n\nimport (\n\t\"exec\"\n\t\"go/ast\"\n\t\"io/ioutil\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar gcName, gcPath string \n\nfunc init() {\n\tswitch runtime.GOARCH {\n\tcase \"386\":\n\t\tgcName = \"8g\"\n\tcase \"amd64\":\n\t\tgcName = \"6g\"\n\tcase \"arm\":\n\t\tgcName = \"5g\"\n\tdefault:\n\t\tgcName = \"unknown-GOARCH-compiler\"\n\t\tgcPath = gcName\n\t\treturn\n\t}\n\tgcPath, _ = exec.LookPath(gcName)\n}\n\nfunc compile(t *testing.T, dirname, filename string) {\n\tcmd := exec.Command(gcPath, filename)\n\tcmd.Dir = dirname\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tt.Errorf(\"%s %s failed: %s\", gcName, filename, err)\n\t\treturn\n\t}\n\tt.Logf(\"%s\", string(out))\n}\n\n\n\nvar imports = make(map[string]*ast.Object)\n\nfunc testPath(t *testing.T, path string) bool {\n\t_, err := GcImporter(imports, path)\n\tif err != nil {\n\t\tt.Errorf(\"testPath(%s): %s\", path, err)\n\t\treturn false\n\t}\n\treturn true\n}\n\nconst maxTime = 3e9 \n\n\n\nfunc TestGcImport(t *testing.T) {\n\tcompile(t, \"testdata\", \"exports.go\")\n\n\tnimports := 0\n\tif testPath(t, \"./testdata/exports\") {\n\t\tnimports++\n\t}\n\tnimports += testDir(t, \"\", time.Nanoseconds()+maxTime) \n\tt.Logf(\"tested %d imports\", nimports)\n}\n\nfunc testDir(t *testing.T, dir string, endTime int64) (nimports int) ", "output": "{\n\tdirname := filepath.Join(pkgRoot, dir)\n\tlist, err := ioutil.ReadDir(dirname)\n\tif err != nil {\n\t\tt.Errorf(\"testDir(%s): %s\", dirname, err)\n\t}\n\tfor _, f := range list {\n\t\tif time.Nanoseconds() >= endTime {\n\t\t\tt.Log(\"testing time used up\")\n\t\t\treturn\n\t\t}\n\t\tswitch {\n\t\tcase f.IsRegular():\n\t\t\tfor _, ext := range pkgExts {\n\t\t\t\tif strings.HasSuffix(f.Name, ext) {\n\t\t\t\t\tname := f.Name[0 : len(f.Name)-len(ext)] \n\t\t\t\t\tif testPath(t, filepath.Join(dir, name)) {\n\t\t\t\t\t\tnimports++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase f.IsDirectory():\n\t\t\tnimports += testDir(t, filepath.Join(dir, f.Name), endTime)\n\t\t}\n\t}\n\treturn\n}"} {"input": "package plAuth\n\nimport (\n\t\"fmt\"\n)\n\n\n\ntype UnsetPassword struct {\n\tuser *User\n}\n\nfunc (e UnsetPassword) Error() string {\n\treturn fmt.Sprintf(\"%s has no password set. Call SetPass() first!\", e.user)\n}\n\n\ntype WrongPassword int\n\nfunc (e WrongPassword) Error() string {\n\treturn fmt.Sprintf(\"Invalid Password\")\n}\n\n\ntype ValidationError struct {\n\tReason string\n}\n\nfunc (e ValidationError) Error() string {\n\treturn e.Reason\n}\n\ntype InterfaceConversionError struct {\n\tFailed interface{}\n}\n\n\n\ntype UserAllreadyExists struct {\n\texistingUser *User\n}\n\nfunc (e UserAllreadyExists) Error() string {\n\treturn fmt.Sprintf(\"A user with this data allreay exists: %v\", e.existingUser)\n}\n\nfunc (e InterfaceConversionError) Error() string ", "output": "{\n\treturn fmt.Sprintf(\"Conversition failed %#v\", e.Failed)\n}"} {"input": "package pkg\n\nimport (\n\tth \"html/template\"\n\ttt \"text/template\"\n)\n\nconst tmpl1 = `{{.Name}} {{.LastName}`\nconst tmpl2 = `{{fn}}`\n\n\n\nfunc fn() ", "output": "{\n\ttt.New(\"\").Parse(tmpl1) \n\ttt.New(\"\").Parse(tmpl2)\n\tt1 := tt.New(\"\")\n\tt1.Parse(tmpl1)\n\tth.New(\"\").Parse(tmpl1) \n\tth.New(\"\").Parse(tmpl2)\n\tt2 := th.New(\"\")\n\tt2.Parse(tmpl1)\n\ttt.New(\"\").Delims(\"[[\", \"]]\").Parse(\"{{abc-}}\")\n}"} {"input": "package context\n\nimport (\n\t\"github.com/gorilla/context\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype RequestParam struct {\n\tRequest *http.Request\n}\n\n\n\nfunc InitParams(req *http.Request) error {\n\terr := req.ParseForm()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trp := RequestParam{req}\n\n\tcontext.Set(req, params, &rp)\n\n\treturn nil\n}\n\nfunc (rp *RequestParam) Get(param string) string {\n\tif strings.HasPrefix(param, \":\") {\n\t\treturn rp.Request.URL.Query().Get(param)\n\t}\n\n\treturn rp.Request.Form.Get(param)\n}\n\nfunc (rp *RequestParam) GetInt(param string) (int, error) {\n\treturn strconv.Atoi(rp.Get(param))\n}\n\nfunc Params(req *http.Request) *RequestParam ", "output": "{\n\tif rp, ok := context.Get(req, params).(*RequestParam); ok {\n\t\treturn rp\n\t}\n\n\treturn nil\n}"} {"input": "package terminal \n\nimport (\n\t\"io\"\n\t\"syscall\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\n\ntype State struct {\n\ttermios syscall.Termios\n}\n\n\n\n\n\n\n\nfunc ReadPassword(fd int) ([]byte, error) {\n\tval, err := unix.IoctlGetTermios(fd, unix.TCGETS)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toldState := *val\n\n\tnewState := oldState\n\tnewState.Lflag &^= syscall.ECHO\n\tnewState.Lflag |= syscall.ICANON | syscall.ISIG\n\tnewState.Iflag |= syscall.ICRNL\n\terr = unix.IoctlSetTermios(fd, unix.TCSETS, &newState)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer unix.IoctlSetTermios(fd, unix.TCSETS, &oldState)\n\n\tvar buf [16]byte\n\tvar ret []byte\n\tfor {\n\t\tn, err := syscall.Read(fd, buf[:])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif n == 0 {\n\t\t\tif len(ret) == 0 {\n\t\t\t\treturn nil, io.EOF\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tif buf[n-1] == '\\n' {\n\t\t\tn--\n\t\t}\n\t\tret = append(ret, buf[:n]...)\n\t\tif n < len(buf) {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn ret, nil\n}\n\nfunc IsTerminal(fd int) bool ", "output": "{\n\tvar termio unix.Termio\n\terr := unix.IoctlSetTermio(fd, unix.TCGETA, &termio)\n\treturn err == nil\n}"} {"input": "package main\n\n\n\nfunc main() {\n\tx := formula()\n\tif x != 7.0 {\n\t\tprintln(x, 7.0)\n\t\tpanic(\"x != 7.0\")\n\t}\n}\n\nfunc formula() float32 ", "output": "{\n\tmA := [1]float32{1.0}\n\tdet1 := mA[0]\n\tdet2 := mA[0]\n\tdet3 := mA[0]\n\tdet4 := mA[0]\n\tdet5 := mA[0]\n\tdet6 := mA[0]\n\tdet7 := mA[0]\n\tdet8 := mA[0]\n\tdet9 := mA[0]\n\tdet10 := mA[0]\n\tdet11 := mA[0]\n\tdet12 := mA[0]\n\n\treturn det1 + det2*det3 +\n\t\tdet4*det5 + det6*det7 +\n\t\tdet8*det9 + det10*det11 +\n\t\tdet12\n}"} {"input": "package out\n\nimport \"math\"\n\n\ntype Point struct {\n\tVid int \n\tIpId int \n\tX []float64 \n\tDist float64 \n\tVals map[string][]float64 \n}\n\n\ntype Points []*Point\n\n\nfunc (o Points) Len() int {\n\treturn len(o)\n}\n\n\nfunc (o Points) Swap(i, j int) {\n\to[i], o[j] = o[j], o[i]\n}\n\n\nfunc (o Points) Less(i, j int) bool {\n\treturn o[i].Dist < o[j].Dist\n}\n\nfunc get_nod_point(vid int, A []float64) *Point {\n\tnod := Dom.Vid2node[vid]\n\tif nod != nil {\n\t\tvar dist float64\n\t\tif A != nil {\n\t\t\tdist = dist_point_point(nod.Vert.C, A)\n\t\t}\n\t\treturn &Point{vid, -1, nod.Vert.C, dist, make(map[string][]float64)}\n\t}\n\treturn nil\n}\n\n\n\n\nfunc dist_point_point(a, b []float64) float64 {\n\tif len(a) == 2 {\n\t\treturn math.Sqrt((a[0]-b[0])*(a[0]-b[0]) + (a[1]-b[1])*(a[1]-b[1]))\n\t}\n\treturn math.Sqrt((a[0]-b[0])*(a[0]-b[0]) + (a[1]-b[1])*(a[1]-b[1]) + (a[2]-b[2])*(a[2]-b[2]))\n}\n\nfunc get_ip_point(ipid int, A []float64) *Point ", "output": "{\n\tip := Ipoints[ipid]\n\tif ip != nil {\n\t\tvar dist float64\n\t\tif A != nil {\n\t\t\tdist = dist_point_point(ip.X, A)\n\t\t}\n\t\treturn &Point{-1, ipid, ip.X, dist, make(map[string][]float64)}\n\t}\n\treturn nil\n}"} {"input": "package gitea\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\n\ntype PublicKey struct {\n\tID int64 `json:\"id\"`\n\tKey string `json:\"key\"`\n\tURL string `json:\"url,omitempty\"`\n\tTitle string `json:\"title,omitempty\"`\n\tCreated time.Time `json:\"created_at,omitempty\"`\n}\n\n\nfunc (c *Client) ListPublicKeys(user string) ([]*PublicKey, error) {\n\tkeys := make([]*PublicKey, 0, 10)\n\treturn keys, c.getParsedResponse(\"GET\", fmt.Sprintf(\"/users/%s/keys\", user), nil, nil, &keys)\n}\n\n\nfunc (c *Client) ListMyPublicKeys() ([]*PublicKey, error) {\n\tkeys := make([]*PublicKey, 0, 10)\n\treturn keys, c.getParsedResponse(\"GET\", \"/user/keys\", nil, nil, &keys)\n}\n\n\n\n\n\nfunc (c *Client) CreatePublicKey(opt CreateKeyOption) (*PublicKey, error) {\n\tbody, err := json.Marshal(&opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkey := new(PublicKey)\n\treturn key, c.getParsedResponse(\"POST\", \"/user/keys\", jsonHeader, bytes.NewReader(body), key)\n}\n\n\nfunc (c *Client) DeletePublicKey(keyID int64) error {\n\t_, err := c.getResponse(\"DELETE\", fmt.Sprintf(\"/user/keys/%d\", keyID), nil, nil)\n\treturn err\n}\n\nfunc (c *Client) GetPublicKey(keyID int64) (*PublicKey, error) ", "output": "{\n\tkey := new(PublicKey)\n\treturn key, c.getParsedResponse(\"GET\", fmt.Sprintf(\"/user/keys/%d\", keyID), nil, nil, &key)\n}"} {"input": "package metrics\n\nimport \"github.com/mackerelio/mackerel-agent/mackerel\"\n\n\ntype Values map[string]float64\n\n\n\n\n\ntype ValuesCustomIdentifier struct {\n\tValues Values\n\tCustomIdentifier *string\n}\n\n\nfunc MergeValuesCustomIdentifiers(values []ValuesCustomIdentifier, newValue ValuesCustomIdentifier) []ValuesCustomIdentifier {\n\tfor _, value := range values {\n\t\tif value.CustomIdentifier == newValue.CustomIdentifier ||\n\t\t\t(value.CustomIdentifier != nil && newValue.CustomIdentifier != nil &&\n\t\t\t\t*value.CustomIdentifier == *newValue.CustomIdentifier) {\n\t\t\tvalue.Values.Merge(newValue.Values)\n\t\t\treturn values\n\t\t}\n\t}\n\treturn append(values, newValue)\n}\n\n\ntype Generator interface {\n\tGenerate() (Values, error)\n}\n\n\ntype PluginGenerator interface {\n\tGenerate() (Values, error)\n\tPrepareGraphDefs() ([]mackerel.CreateGraphDefsPayload, error)\n\tCustomIdentifier() *string\n}\n\nfunc (vs *Values) Merge(other Values) ", "output": "{\n\tfor k, v := range (map[string]float64)(other) {\n\t\t(*vs)[k] = v\n\t}\n}"} {"input": "package provision\n\nimport (\n\t\"testing\"\n\n\t\"github.com/docker/machine/drivers/fakedriver\"\n\t\"github.com/docker/machine/libmachine/auth\"\n\t\"github.com/docker/machine/libmachine/engine\"\n\t\"github.com/docker/machine/libmachine/provision/provisiontest\"\n\t\"github.com/docker/machine/libmachine/swarm\"\n)\n\n\n\nfunc TestRedHatDefaultStorageDriver(t *testing.T) ", "output": "{\n\tp := NewRedHatProvisioner(\"\", &fakedriver.Driver{})\n\tp.SSHCommander = provisiontest.NewFakeSSHCommander(provisiontest.FakeSSHCommanderOptions{})\n\tp.Provision(swarm.Options{}, auth.Options{}, engine.Options{})\n\tif p.EngineOptions.StorageDriver != \"devicemapper\" {\n\t\tt.Fatal(\"Default storage driver should be devicemapper\")\n\t}\n}"} {"input": "package glib\n\n\n\n\n\nimport \"C\"\nimport \"unsafe\"\n\n\n\ntype IActionMap interface {\n\tNative() uintptr\n\n\tLookupAction(actionName string) *Action\n\tAddAction(action IAction)\n\tRemoveAction(actionName string)\n}\n\n\ntype ActionMap struct {\n\t*Object\n}\n\n\n\n\n\nfunc (v *ActionMap) native() *C.GActionMap {\n\tif v == nil || v.GObject == nil {\n\t\treturn nil\n\t}\n\treturn C.toGActionMap(unsafe.Pointer(v.GObject))\n}\n\nfunc (v *ActionMap) Native() uintptr {\n\treturn uintptr(unsafe.Pointer(v.native()))\n}\n\n\n\nfunc wrapActionMap(obj *Object) *ActionMap {\n\treturn &ActionMap{obj}\n}\n\n\nfunc (v *ActionMap) LookupAction(actionName string) *Action {\n\tc := C.g_action_map_lookup_action(v.native(), (*C.gchar)(C.CString(actionName)))\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn wrapAction(wrapObject(unsafe.Pointer(c)))\n}\n\n\nfunc (v *ActionMap) AddAction(action IAction) {\n\tC.g_action_map_add_action(v.native(), action.toGAction())\n}\n\n\nfunc (v *ActionMap) RemoveAction(actionName string) {\n\tC.g_action_map_remove_action(v.native(), (*C.gchar)(C.CString(actionName)))\n}\n\nfunc marshalActionMap(p uintptr) (interface{}, error) ", "output": "{\n\tc := C.g_value_get_object((*C.GValue)(unsafe.Pointer(p)))\n\treturn wrapActionMap(wrapObject(unsafe.Pointer(c))), nil\n}"} {"input": "package layer\n\nimport \"io\"\n\ntype mountedLayer struct {\n\tname string\n\tmountID string\n\tinitID string\n\tparent *roLayer\n\tpath string\n\tlayerStore *layerStore\n\tactivityCount int\n}\n\nfunc (ml *mountedLayer) cacheParent() string {\n\tif ml.initID != \"\" {\n\t\treturn ml.initID\n\t}\n\tif ml.parent != nil {\n\t\treturn ml.parent.cacheID\n\t}\n\treturn \"\"\n}\n\n\n\nfunc (ml *mountedLayer) Path() (string, error) {\n\tif ml.path == \"\" {\n\t\treturn \"\", ErrNotMounted\n\t}\n\treturn ml.path, nil\n}\n\nfunc (ml *mountedLayer) Parent() Layer {\n\tif ml.parent != nil {\n\t\treturn ml.parent\n\t}\n\n\treturn nil\n}\n\nfunc (ml *mountedLayer) Size() (int64, error) {\n\treturn ml.layerStore.driver.DiffSize(ml.mountID, ml.cacheParent())\n}\n\nfunc (ml *mountedLayer) TarStream() (io.ReadCloser, error) ", "output": "{\n\tarchiver, err := ml.layerStore.driver.Diff(ml.mountID, ml.cacheParent())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn archiver, nil\n}"} {"input": "package base\n\nimport (\n\t\"math\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc GaussianRandom() {\n\n\trand.Seed(99)\n\n}\n\nfunc GetRandf(a float64, b float64) float64 {\n\n\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\n\treturn (b-a)*r.Float64() + a \n}\n\n\n\nfunc GetRandn(mu float64, std float64) float64 {\n\n\treturn rand.NormFloat64()*mu + std\n}\n\nfunc GetRani(a float64, b float64) float64 ", "output": "{\n\n\treturn math.Floor(GetRandf(a, b))\n}"} {"input": "package ble\n\nimport (\n\t\"testing\"\n\n\t\"gobot.io/x/gobot/gobottest\"\n)\n\n\n\nfunc TestBLESerialPort(t *testing.T) {\n\td := initTestBLESerialPort()\n\tgobottest.Assert(t, d.Address(), \"TEST123\")\n}\n\nfunc initTestBLESerialPort() *SerialPort ", "output": "{\n\treturn NewSerialPort(\"TEST123\", \"123\", \"456\")\n}"} {"input": "package generic\n\nimport (\n\t\"github.com/actgardner/gogen-avro/v8/schema\"\n\t\"github.com/actgardner/gogen-avro/v8/vm/types\"\n)\n\ntype recordDatum struct {\n\tdef *schema.RecordDefinition\n\tfields []Datum\n}\n\nfunc newRecordDatum(def *schema.RecordDefinition) *recordDatum {\n\treturn &recordDatum{\n\t\tdef: def,\n\t\tfields: make([]Datum, len(def.Fields())),\n\t}\n}\n\nfunc (r *recordDatum) Datum() interface{} {\n\tm := make(map[string]interface{})\n\tfor i, f := range r.def.Fields() {\n\t\tm[f.Name()] = r.fields[i].Datum()\n\t}\n\treturn m\n}\n\nfunc (r *recordDatum) SetBoolean(v bool) { panic(\"\") }\nfunc (r *recordDatum) SetInt(v int32) { panic(\"\") }\nfunc (r *recordDatum) SetLong(v int64) { panic(\"\") }\nfunc (r *recordDatum) SetFloat(v float32) { panic(\"\") }\nfunc (r *recordDatum) SetDouble(v float64) { panic(\"\") }\nfunc (r *recordDatum) SetBytes(v []byte) { panic(\"\") }\nfunc (r *recordDatum) SetString(v string) { panic(\"\") }\nfunc (r *recordDatum) Get(i int) types.Field {\n\tfield := r.def.Fields()[i]\n\tr.fields[i] = DatumForType(field.Type())\n\treturn r.fields[i]\n}\n\nfunc (r *recordDatum) AppendMap(key string) types.Field { panic(\"\") }\nfunc (r *recordDatum) AppendArray() types.Field { panic(\"\") }\nfunc (r *recordDatum) NullField(t int) {\n\tr.fields[t] = &primitiveDatum{nil}\n}\nfunc (r *recordDatum) Finalize() {}\n\nfunc (r *recordDatum) SetDefault(i int) ", "output": "{\n\tfield := r.def.Fields()[i]\n\tr.fields[i] = &primitiveDatum{field.Default()}\n}"} {"input": "package messages\n\nconst (\n\tPullAllMessageSignature = 0x3F\n)\n\n\ntype PullAllMessage struct{}\n\n\n\n\n\nfunc (i PullAllMessage) Signature() int {\n\treturn PullAllMessageSignature\n}\n\n\nfunc (i PullAllMessage) AllFields() []interface{} {\n\treturn []interface{}{}\n}\n\nfunc NewPullAllMessage() PullAllMessage ", "output": "{\n\treturn PullAllMessage{}\n}"} {"input": "package responsewriter\n\nimport (\n\t\"net/http\"\n\t\"unicode/utf8\"\n\n\t\"github.com/go-on/stack\"\n)\n\nvar (\n\tampOrig = []byte(`&`)[0]\n\tampRepl = []byte(`&`)\n\n\tsgQuoteOrig = []byte(`'`)[0]\n\tsgQuoteRepl = []byte(`'`)\n\n\tdblQuoteOrig = []byte(`\"`)[0]\n\tdblQuoteRepl = []byte(`"`)\n\n\tltQuoteOrig = []byte(`<`)[0]\n\tltQuoteRepl = []byte(`<`)\n\n\tgtQuoteOrig = []byte(`>`)[0]\n\tgtQuoteRepl = []byte(`>`)\n)\n\n\n\ntype EscapeHTML struct {\n\thttp.ResponseWriter\n\n\tstack.Contexter\n}\n\n\nvar _ stack.Contexter = &EscapeHTML{}\n\n\n\n\n\n\n\n\nfunc (e *EscapeHTML) Write(b []byte) (num int, err error) {\n\tvar esc []byte\n\tn := len(b)\n\tlast := 0\n\n\tfor i := 0; i < n; {\n\t\tr, width := utf8.DecodeRune(b[i:])\n\t\ti += width\n\t\tswitch r {\n\t\tcase '&':\n\t\t\tesc = ampRepl\n\t\tcase '\\'':\n\t\t\tesc = sgQuoteRepl\n\t\tcase '\"':\n\t\t\tesc = dblQuoteRepl\n\t\tcase '<':\n\t\t\tesc = ltQuoteRepl\n\t\tcase '>':\n\t\t\tesc = gtQuoteRepl\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\n\t\te.ResponseWriter.Write(b[last : i-width])\n\t\te.ResponseWriter.Write(esc)\n\t\tlast = i\n\t}\n\n\te.ResponseWriter.Write(b[last:])\n\treturn\n}\n\nfunc NewEscapeHTML(w http.ResponseWriter) *EscapeHTML ", "output": "{\n\te := &EscapeHTML{ResponseWriter: w}\n\tif ctx, ok := w.(stack.Contexter); ok {\n\t\te.Contexter = ctx\n\t}\n\treturn e\n}"} {"input": "package generator\n\nimport (\n\tkapi \"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/api/rest\"\n\t\"k8s.io/kubernetes/pkg/runtime\"\n\n\tbuildapi \"github.com/openshift/origin/pkg/build/api\"\n\t\"github.com/openshift/origin/pkg/build/generator\"\n\t\"github.com/openshift/origin/pkg/build/registry/clone\"\n)\n\n\nfunc NewStorage(generator *generator.BuildGenerator) *CloneREST {\n\treturn &CloneREST{generator: generator}\n}\n\n\n\ntype CloneREST struct {\n\tgenerator *generator.BuildGenerator\n}\n\n\n\n\n\nfunc (s *CloneREST) Create(ctx kapi.Context, obj runtime.Object) (runtime.Object, error) {\n\tif err := rest.BeforeCreate(clone.Strategy, ctx, obj); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s.generator.Clone(ctx, obj.(*buildapi.BuildRequest))\n}\n\nfunc (s *CloneREST) New() runtime.Object ", "output": "{\n\treturn &buildapi.BuildRequest{}\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com/lmorg/murex/lang\"\n\t\"github.com/lmorg/murex/test/count\"\n)\n\n\n\n\n\nfunc TestRunCommandLine(t *testing.T) {\n\tcount.Tests(t, 1)\n\n\trunCommandLine(`out: \"testing\" -> null`)\n}\n\nfunc TestRunSource(t *testing.T) {\n\tcount.Tests(t, 1)\n\n\tfile := \"test/source.mx\"\n\trunSource(file)\n}\n\nfunc TestRunSourceGzMods(t *testing.T) {\n\tcount.Tests(t, 1)\n\n\tfile := \"test/source.mx.gz\"\n\trunSource(file)\n}\n\nfunc TestMurex(t *testing.T) ", "output": "{\n\tcount.Tests(t, 1)\n\n\tlang.InitEnv()\n\n\tblock := []rune(\"a [Mon..Fri]->regexp m/^T/\")\n\n\t_, err := lang.ShellProcess.Fork(lang.F_NO_STDIN | lang.F_NO_STDOUT | lang.F_NO_STDERR).Execute(block)\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n}"} {"input": "package daemon\n\nimport (\n\t\"path/filepath\"\n\n\t\"github.com/pkg/errors\"\n\n\t\"github.com/mutagen-io/mutagen/pkg/filesystem\"\n)\n\nconst (\n\tlockName = \"daemon.lock\"\n\tendpointName = \"daemon.sock\"\n)\n\n\n\nfunc subpath(name string) (string, error) {\n\tdaemonRoot, err := filesystem.Mutagen(true, filesystem.MutagenDaemonDirectoryName)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to compute daemon directory\")\n\t}\n\n\treturn filepath.Join(daemonRoot, name), nil\n}\n\n\n\nfunc lockPath() (string, error) {\n\treturn subpath(lockName)\n}\n\n\n\n\n\nfunc EndpointPath() (string, error) ", "output": "{\n\treturn subpath(endpointName)\n}"} {"input": "package randutils\n\nimport (\n\t\"math/rand\"\n\t\"sync\"\n\t\"testing\"\n)\n\n\n\n\nfunc TestRandomConcurrentUsage(t *testing.T) ", "output": "{\n\tt.Parallel()\n\twg := sync.WaitGroup{}\n\twg.Add(100)\n\n\tvar source = NewThreadSafeSource()\n\trnd := rand.New(source)\n\tfor i := 0; i < 100; i++ {\n\t\tgo func() {\n\t\t\tfor j := 0; j < 200; j++ {\n\t\t\t\trnd.Int()\n\t\t\t}\n\t\t\twg.Done()\n\t\t}()\n\t\tgo func(i int64) {\n\t\t\tsource.Seed(i)\n\t\t}(int64(i))\n\t}\n\n\twg.Wait()\n}"} {"input": "package main\n\nimport \"github.com/go-gl/gl/v2.1/gl\"\n\n\n\nfunc rotateOnPoint(rot float64, loc vertex) {\n\tgl.Translated(loc.x, loc.y, loc.z)\n\tgl.Rotated(rot, 0.0, 0.0, 1.0)\n\tgl.Translated(-loc.x, -loc.y, -loc.z)\n}\n\n\n\n\n\nfunc fPtr(data []float32) *float32 ", "output": "{\n\treturn (*float32)(gl.Ptr(data))\n}"} {"input": "package elasticsearch_test\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"testing\"\n)\n\n\n\n\ntype Test struct{}\n\n\n\n\n\nfunc (t *Test) OK(tb testing.TB, err error) {\n\tif err != nil {\n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfmt.Printf(\"\\033[31m%s:%d: unexpected error: %s\\033[39m\\n\\n\", filepath.Base(file), line, err.Error())\n\t\ttb.FailNow()\n\t}\n}\n\n\nfunc (t *Test) Equals(tb testing.TB, exp, act interface{}) {\n\tif !reflect.DeepEqual(exp, act) {\n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfmt.Printf(\"\\033[31m%s:%d:\\n\\n\\texp: %#v\\n\\n\\tgot: %#v\\033[39m\\n\\n\", filepath.Base(file), line, exp, act)\n\t\ttb.FailNow()\n\t}\n}\n\nfunc (t *Test) Assert(tb testing.TB, condition bool, msg string, v ...interface{}) ", "output": "{\n\tif !condition {\n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfmt.Printf(\"\\033[31m%s:%d: \"+msg+\"\\033[39m\\n\\n\", append([]interface{}{filepath.Base(file), line}, v...)...)\n\t\ttb.FailNow()\n\t}\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype DeleteVolumeBackupPolicyRequest struct {\n\n\tPolicyId *string `mandatory:\"true\" contributesTo:\"path\" name:\"policyId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request DeleteVolumeBackupPolicyRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request DeleteVolumeBackupPolicyRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\nfunc (request DeleteVolumeBackupPolicyRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype DeleteVolumeBackupPolicyResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\n\nfunc (response DeleteVolumeBackupPolicyResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response DeleteVolumeBackupPolicyResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package systray\n\n\nimport \"C\"\n\nimport (\n\t\"unsafe\"\n)\n\nfunc nativeLoop() {\n\tC.nativeLoop()\n}\n\nfunc quit() {\n\tC.quit()\n}\n\n\n\n\nfunc SetIcon(iconBytes []byte) {\n\tcstr := (*C.char)(unsafe.Pointer(&iconBytes[0]))\n\tC.setIcon(cstr, (C.int)(len(iconBytes)))\n}\n\n\nfunc SetTitle(title string) {\n\tC.setTitle(C.CString(title))\n}\n\n\n\nfunc SetTooltip(tooltip string) {\n\tC.setTooltip(C.CString(tooltip))\n}\n\nfunc addOrUpdateMenuItem(item *MenuItem) {\n\tvar disabled C.short = 0\n\tif item.disabled {\n\t\tdisabled = 1\n\t}\n\tvar checked C.short = 0\n\tif item.checked {\n\t\tchecked = 1\n\t}\n\tC.add_or_update_menu_item(\n\n\t\tC.int(item.id),\n\t\tC.CString(item.title),\n\t\tC.CString(item.tooltip),\n\t\tdisabled,\n\t\tchecked,\n\t)\n}\n\n\n\n\n\nfunc systray_menu_item_selected(cId C.int) {\n\tsystrayMenuItemSelected(int32(cId))\n}\n\nfunc systray_ready() ", "output": "{\n\tsystrayReady()\n}"} {"input": "package ioext\n\nimport \"io\"\n\n\n\nfunc OffsetReader(r io.ReaderAt, off int64) io.Reader {\n\treturn &offsetReader{r, off}\n}\n\ntype offsetReader struct {\n\tr io.ReaderAt\n\toff int64\n}\n\n\n\nfunc (r *offsetReader) Read(p []byte) (int, error) ", "output": "{\n\tn, err := r.r.ReadAt(p, r.off)\n\tr.off += int64(n)\n\treturn n, err\n}"} {"input": "package handlers\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\n\t\"github.com/xoriath/alexandria-go/fetch\"\n\t\"github.com/xoriath/alexandria-go/index\"\n\t\"github.com/xoriath/alexandria-go/types\"\n)\n\n\ntype ReloadBook struct {\n\tbooks *types.Books\n\tindex string\n}\n\n\nfunc NewReloadBookHandler(books *types.Books, index string) *ReloadBook {\n\treturn &ReloadBook{books: books, index: index}\n}\n\nfunc (rb *ReloadBook) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ttempBooks, err := fetch.MainIndex(rb.index)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t} else {\n\t\trb.books = tempBooks\n\t\tjson.NewEncoder(w).Encode(rb.books)\n\t}\n}\n\n\ntype ReloadKeyword struct {\n\tbooks *types.Books\n\tstore *index.Store\n\tf1Pattern string\n}\n\n\n\n\nfunc (rk *ReloadKeyword) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\trk.store = fetch.F1Indexes(rk.books, rk.store)\n\n\tstat := rk.store.GetStatistics()\n\tjson.NewEncoder(w).Encode(stat)\n}\n\nfunc NewReloadKeywordHandler(books *types.Books, store *index.Store, f1Pattern string) *ReloadKeyword ", "output": "{\n\treturn &ReloadKeyword{books: books, store: store, f1Pattern: f1Pattern}\n}"} {"input": "package canvas\n\nimport \"math/rand\"\n\n\nfunc min(x, y int) int {\n\tif x < y {\n\t\treturn x\n\t}\n\treturn y\n}\n\n\n\n\n\nfunc random() float64 {\n\treturn rand.Float64()\n}\n\nfunc max(x, y int) int ", "output": "{\n\tif x > y {\n\t\treturn x\n\t}\n\treturn y\n}"} {"input": "package base\n\nimport (\n\t\"io\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc Test_Manager_Validate(t *testing.T) {\n\tc := HandlerCollection{\n\t\t\"node.user\": &UserHandler{},\n\t}\n\n\tm := &PgNodeManager{\n\t\tHandlers: c,\n\t}\n\n\tn := c.NewNode(\"node.user\")\n\n\tok, errors := m.Validate(n)\n\n\tassert.False(t, ok)\n\tassert.True(t, errors.HasErrors())\n}\n\ntype UserMeta struct {\n}\n\ntype User struct {\n\tName string `json:\"name\"`\n\tUsername string `json:\"username\"`\n\tPassword string `json:\"password\"`\n}\n\ntype UserHandler struct {\n}\n\nfunc (h *UserHandler) GetStruct() (NodeData, NodeMeta) {\n\treturn &User{}, &UserMeta{}\n}\n\nfunc (h *UserHandler) PreInsert(node *Node, m NodeManager) error {\n\treturn nil\n}\n\nfunc (h *UserHandler) PreUpdate(node *Node, m NodeManager) error {\n\treturn nil\n}\n\nfunc (h *UserHandler) PostInsert(node *Node, m NodeManager) error {\n\treturn nil\n}\n\nfunc (h *UserHandler) PostUpdate(node *Node, m NodeManager) error {\n\treturn nil\n}\n\n\n\nfunc (h *UserHandler) GetDownloadData(node *Node) *DownloadData {\n\treturn GetDownloadData()\n}\n\nfunc (h *UserHandler) Load(data []byte, meta []byte, node *Node) error {\n\treturn HandlerLoad(h, data, meta, node)\n}\n\nfunc (h *UserHandler) StoreStream(node *Node, r io.Reader) (int64, error) {\n\treturn DefaultHandlerStoreStream(node, r)\n}\n\nfunc (h *UserHandler) Validate(node *Node, m NodeManager, errors Errors) ", "output": "{\n\n\tdata := node.Data.(*User)\n\n\tif data.Username == \"\" {\n\t\terrors.AddError(\"data.username\", \"Username cannot be empty\")\n\t}\n\n\tif data.Name == \"\" {\n\t\terrors.AddError(\"data.name\", \"Name cannot be empty\")\n\t}\n\n\tif data.Password == \"\" {\n\t\terrors.AddError(\"data.password\", \"Password cannot be empty\")\n\t}\n}"} {"input": "package server\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/summadb/summadb/database\"\n)\n\n\n\nfunc handlehttp(db *database.SummaDB, w http.ResponseWriter, r *http.Request) ", "output": "{\n\tw.Write([]byte(\"hello\"))\n}"} {"input": "package constants\n\nimport (\n\t\"GoVM/chapter5-instructions/base\"\n\t\"GoVM/chapter4-rtdt\"\n)\n\n\ntype BIPUSH struct {\n\tval int8\n}\n\nfunc (self *BIPUSH) FetchOperands(reader *base.BytecodeReader) {\n\tself.val = reader.ReadInt8()\n}\n\nfunc (self *BIPUSH) Execute(frame *chapter4_rtdt.Frame) {\n\ti := int32(self.val)\n\tframe.OperandStack().PushInt(i)\n}\n\n\ntype SIPUSH struct {\n\tval int16\n}\n\n\n\nfunc (self *SIPUSH) Execute(frame *chapter4_rtdt.Frame) {\n\ti := int32(self.val)\n\tframe.OperandStack().PushInt(i)\n}\n\nfunc (self *SIPUSH) FetchOperands(reader *base.BytecodeReader) ", "output": "{\n\tself.val = reader.ReadInt16()\n}"} {"input": "package x509\n\n\nimport \"C\"\nimport (\n\t\"errors\"\n\t\"unsafe\"\n)\n\n\n\nfunc loadSystemRoots() (*CertPool, error) ", "output": "{\n\troots := NewCertPool()\n\n\tvar data C.CFDataRef = nil\n\terr := C.FetchPEMRoots(&data)\n\tif err == -1 {\n\t\treturn nil, errors.New(\"crypto/x509: failed to load darwin system roots with cgo\")\n\t}\n\n\tdefer C.CFRelease(C.CFTypeRef(data))\n\tbuf := C.GoBytes(unsafe.Pointer(C.CFDataGetBytePtr(data)), C.int(C.CFDataGetLength(data)))\n\troots.AppendCertsFromPEM(buf)\n\treturn roots, nil\n}"} {"input": "package vim25_test\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/vmware/govmomi/find\"\n\t\"github.com/vmware/govmomi/simulator\"\n\t\"github.com/vmware/govmomi/vim25\"\n)\n\n\n\nfunc ExampleTemporaryNetworkError() ", "output": "{\n\tsimulator.Run(func(ctx context.Context, c *vim25.Client) error {\n\t\tdelay := time.Millisecond * 100\n\t\tretry := func(err error) (bool, time.Duration) {\n\t\t\treturn vim25.IsTemporaryNetworkError(err), delay\n\t\t}\n\t\tc.RoundTripper = vim25.Retry(c.Client, retry, 3)\n\n\t\tvm, err := find.NewFinder(c).VirtualMachine(ctx, \"DC0_H0_VM0\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsimulator.StatusSDK = http.StatusBadGateway\n\n\t\tstate, err := vm.PowerState(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Println(state)\n\n\t\treturn nil\n\t})\n}"} {"input": "package controllers\n\nimport (\n\t\"net/http\"\n)\n\n\ntype SignUpController struct {\n\tBaseController\n}\n\n\n\n\nfunc (suc *SignUpController) Get() ", "output": "{\n\tif suc.AuthMode != \"db_auth\" || !suc.SelfRegistration {\n\t\tsuc.CustomAbort(http.StatusForbidden, \"\")\n\t}\n\tsuc.Data[\"AddNew\"] = false\n\tsuc.Forward(\"page_title_sign_up\", \"sign-up.htm\")\n}"} {"input": "package fs\n\nimport (\n\t\"syscall\"\n)\n\nfunc MountRootFS(path string) error {\n\treturn syscall.Mount(path, \"rootfs\", \"\", syscall.MS_BIND, \"\")\n}\n\nfunc MountAdditional(source, dest, t string) error {\n\treturn syscall.Mount(source, dest, t, syscall.MS_BIND, \"\")\n}\n\nfunc MountDevFS() error {\n\treturn syscall.Mount(\"tmpfs\", \"/dev\", \"tmpfs\", syscall.MS_BIND, \"\")\n}\n\nfunc MountProcFS() error {\n\treturn syscall.Mount(\"proc\", \"/proc\", \"proc\", syscall.MS_BIND, \"\")\n}\n\n\n\nfunc MountSysFS() error ", "output": "{\n\treturn syscall.Mount(\"sysfs\", \"/sys\", \"sysfs\", syscall.MS_BIND, \"\")\n}"} {"input": "package veritas_models\n\nimport (\n\t\"sort\"\n\t\"strconv\"\n\n\t\"github.com/cloudfoundry-incubator/bbs/models\"\n)\n\ntype VeritasLRP struct {\n\tProcessGuid string\n\tDesiredLRP *models.DesiredLRP\n\tActualLRPGroupsByIndex map[string]*models.ActualLRPGroup\n}\n\nfunc (l *VeritasLRP) OrderedActualLRPIndices() []string {\n\tindicesAsStrings := []string{}\n\tfor index := range l.ActualLRPGroupsByIndex {\n\t\tindicesAsStrings = append(indicesAsStrings, index)\n\t}\n\n\tsort.Sort(ByNumericalValue(indicesAsStrings))\n\treturn indicesAsStrings\n}\n\ntype ByNumericalValue []string\n\nfunc (a ByNumericalValue) Len() int { return len(a) }\nfunc (a ByNumericalValue) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\n\n\nfunc (a ByNumericalValue) Less(i, j int) bool ", "output": "{\n\tai, _ := strconv.Atoi(a[i])\n\taj, _ := strconv.Atoi(a[j])\n\n\treturn ai < aj\n}"} {"input": "package outputs\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/lfkeitel/spartan/event\"\n\n\ttomb \"gopkg.in/tomb.v2\"\n)\n\n\n\n\ntype OutputController struct {\n\tstart Output\n\tbatchSize int\n\tt tomb.Tomb\n\tin <-chan *event.Event\n\tout chan<- *event.Event\n}\n\n\n\nfunc NewOutputController(start Output, batchSize int) *OutputController {\n\treturn &OutputController{\n\t\tstart: start,\n\t\tbatchSize: batchSize,\n\t}\n}\n\n\n\n\nfunc (o *OutputController) Start(in chan *event.Event) error {\n\to.in = in\n\to.t.Go(o.run)\n\treturn nil\n}\n\n\n\n\nfunc (o *OutputController) Close() error {\n\to.t.Kill(nil)\n\treturn o.t.Wait()\n}\n\nfunc (o *OutputController) run() error {\n\tfmt.Println(\"Output Pipeline started\")\n\tfor {\n\t\tselect {\n\t\tcase <-o.t.Dying():\n\t\t\treturn nil\n\t\tdefault:\n\t\t}\n\n\t\tcurrentBatch := 0\n\t\tbatch := make([]*event.Event, o.batchSize)\n\t\tstopping := false\n\n\tCURRENT:\n\t\tfor currentBatch < o.batchSize {\n\t\t\tselect {\n\t\t\tcase event := <-o.in:\n\t\t\t\tbatch[currentBatch] = event\n\t\t\t\tcurrentBatch++\n\t\t\tcase <-o.t.Dying():\n\t\t\t\tstopping = true\n\t\t\t\tbreak CURRENT\n\t\t\t}\n\t\t}\n\n\t\tfmt.Println(\"Processing batch\")\n\t\to.start.Run(batch)\n\n\t\tif stopping {\n\t\t\treturn nil\n\t\t}\n\t}\n}\n\n\n\n\nfunc checkOptionsMap(o map[string]interface{}) map[string]interface{} ", "output": "{\n\tif o == nil {\n\t\to = make(map[string]interface{})\n\t}\n\treturn o\n}"} {"input": "package main\n\nimport \"fmt\"\n\ntype Bitcoin int\n\ntype Wallet struct {\n\tbalance Bitcoin\n}\n\n\nfunc (w *Wallet) Deposit(amount Bitcoin) {\n\tw.balance += amount\n}\n\nfunc (w *Wallet) Balance() Bitcoin {\n\treturn w.balance\n}\n\nfunc (w *Wallet) Withdraw(amount Bitcoin) {\n\tw.balance -= amount\n}\n\nfunc main() {\n\tname := \"sss\"\n\tfmt.Println(name)\n}\n\nfunc (b Bitcoin) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%d BTC\", b)\n}"} {"input": "package notifications\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n)\n\nvar url string\nvar serverKey string\nvar topic string\n\n\nfunc Init() {\n\turl = \"https://fcm.googleapis.com/fcm/send\"\n\tserverKey = os.Getenv(\"JFBKEY\")\n\tif serverKey == \"\" {\n\t\tlog.Fatal(\"Missing JFBKEY for Firebase Authentication\")\n\t}\n\ttopic = os.Getenv(\"JFBTOPIC\")\n\tif topic == \"\" {\n\t\tlog.Fatal(\"Missing JFBTOPIC for Firebase Topic\")\n\t}\n}\n\n\n\n\nfunc PushFirebase(title string, body string) ", "output": "{\n\tvar jsonStr = []byte(fmt.Sprintf(`{\"to\": \"/topics/%s\", \"priority\" : \"high\", \"notification\": {\"body\": \"%s\", \"icon\" : \"ic_notify\", \"tag\":\"JIMMY\", \"title\": \"%s\"}}`, topic, body, title))\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(jsonStr))\n\treq.Header.Set(\"Authorization\", \"key=\"+serverKey)\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tclient := &http.Client{}\n\t_, err = client.Do(req)\n\tif err != nil {\n\t\tlog.Println(\"Push failed\")\n\t}\n}"} {"input": "package database\n\nimport (\n\t\"labix.org/v2/mgo\"\n\t\"labix.org/v2/mgo/bson\"\n\t\"github.com/DewaldV/crucible/config\"\n)\n\ntype MgoConnection struct {\n\tDatabase string\n\tCollection string\n}\n\nfunc (conn *MgoConnection) FindOne(m bson.M, d interface{}) {\n\tExecuteWithCollection(conn.Database, conn.Collection, func(c *mgo.Collection) error { return c.Find(m).One(d) })\n}\n\nfunc (conn *MgoConnection) FindAll(m bson.M, d interface{}) {\n\tExecuteWithCollection(conn.Database, conn.Collection, func(c *mgo.Collection) error { return c.Find(m).All(d) })\n}\n\n\nfunc (conn *MgoConnection) Insert(d interface{}) {\n\tExecuteWithCollection(conn.Database, conn.Collection, func(c *mgo.Collection) error { return c.Insert(d) })\n}\n\n\n\n\n\nvar sessionPool map[string]*mgo.Session\n\nfunc LoadSessions(dataSourceConfig map[string]*config.DataSourceConfiguration) {\n\tsessionPool = make(map[string]*mgo.Session)\n\tfor key, source := range dataSourceConfig {\n\t\ts, _ := mgo.Dial(source.ServerName)\n\t\tsessionPool[key] = s\n\t}\n}\n\nfunc GetSession(dataSource string) *mgo.Session {\n\ts := sessionPool[dataSource]\n\treturn s.Clone()\n}\n\nfunc ExecuteWithCollection(database, collection string, f func(*mgo.Collection) error) error ", "output": "{\n\tsession := GetSession(\"Default\")\n\tdefer session.Close()\n\n\tsession.SetMode(mgo.Monotonic, true)\n\n\tc := session.DB(database).C(collection)\n\n\treturn f(c)\n}"} {"input": "package runtime\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype response struct {\n}\n\nfunc (r response) Code() int {\n\treturn 490\n}\nfunc (r response) Message() string {\n\treturn \"the message\"\n}\n\nfunc (r response) GetHeaders(_ string) []string {\n\treturn []string{\"the headers\", \"the headers2\"}\n}\nfunc (r response) Body() io.ReadCloser {\n\treturn ioutil.NopCloser(bytes.NewBufferString(\"the content\"))\n}\n\nfunc TestResponseReaderFunc(t *testing.T) {\n\tvar actual struct {\n\t\tHeader, Message, Body string\n\t\tCode int\n\t}\n\treader := ClientResponseReaderFunc(func(r ClientResponse, _ Consumer) (interface{}, error) {\n\t\tb, _ := ioutil.ReadAll(r.Body())\n\t\tactual.Body = string(b)\n\t\tactual.Code = r.Code()\n\t\tactual.Message = r.Message()\n\t\tactual.Header = r.GetHeader(\"blah\")\n\t\treturn actual, nil\n\t})\n\t_, _ = reader.ReadResponse(response{}, nil)\n\tassert.Equal(t, \"the content\", actual.Body)\n\tassert.Equal(t, \"the message\", actual.Message)\n\tassert.Equal(t, \"the header\", actual.Header)\n\tassert.Equal(t, 490, actual.Code)\n}\n\nfunc (r response) GetHeader(_ string) string ", "output": "{\n\treturn \"the header\"\n}"} {"input": "package utils\n\nimport \"testing\"\n\n\n\nfunc TestPrepareURL(t *testing.T) ", "output": "{\n\texpectedURL := \"https://guest:guest@greathost:83232/my/path?q=query&toto=lulu\"\n\n\tu, _ := PrepareURL(\n\t\t\"https://guest:guest@greathost:83232\", \"/my/path\",\n\t\tmap[string]string{\"q\": \"query\", \"toto\": \"lulu\"},\n\t)\n\tactualURL := u.String()\n\n\tif actualURL != expectedURL {\n\t\tt.Errorf(\"Expected %s, got %s\", expectedURL, actualURL)\n\t}\n}"} {"input": "package wallabago\n\nimport \"testing\"\n\nconst tagsResult = `[{\"id\":53,\"label\":\"2min\",\"slug\":\"2min\"},{\"id\":57,\"label\":\"android\",\"slug\":\"android\"},{\"id\":58,\"label\":\"linux\",\"slug\":\"linux\"}]`\n\n\n\nfunc mockGetTagsOfEntry(url string, httpMethod string, postData []byte) ([]byte, error) {\n\treturn []byte(tagsResult), nil\n}\n\nfunc TestGetTags(t *testing.T) {\n\texpectedID := 57\n\texpectedLabel := \"android\"\n\texpectedSlug := \"android\"\n\ttags, _ := GetTags(mockGetTagsOfEntry)\n\tif tags[1].ID != expectedID {\n\t\tt.Errorf(\"expected id=%v, but got %v\", expectedID, tags[1].ID)\n\t}\n\tif tags[1].Label != expectedLabel {\n\t\tt.Errorf(\"expected label=%v, but got %v\", expectedLabel, tags[1].Label)\n\t}\n\tif tags[1].Slug != expectedSlug {\n\t\tt.Errorf(\"expected slug=%v, but got %v\", expectedSlug, tags[1].Slug)\n\t}\n}\n\nfunc TestGetTagsOfEntry(t *testing.T) ", "output": "{\n\tarticleID := 3977\n\texpectedID := 57\n\texpectedLabel := \"android\"\n\texpectedSlug := \"android\"\n\ttags, _ := GetTagsOfEntry(mockGetTagsOfEntry, articleID)\n\tif tags[1].ID != expectedID {\n\t\tt.Errorf(\"expected id=%v, but got %v\", expectedID, tags[1].ID)\n\t}\n\tif tags[1].Label != expectedLabel {\n\t\tt.Errorf(\"expected label=%v, but got %v\", expectedLabel, tags[1].Label)\n\t}\n\tif tags[1].Slug != expectedSlug {\n\t\tt.Errorf(\"expected slug=%v, but got %v\", expectedSlug, tags[1].Slug)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/russmack/statemachiner\"\n)\n\n\nfunc main() {\n\ts := statemachiner.NewStateMachine()\n\ts.StartState = dispenseDogBiscuits\n\tc := NewHome()\n\ts.Start(c)\n}\n\n\ntype Home struct {\n\tDispenseDogBiscuits int `json:\"dispense_dog_biscuits\"`\n\tTotalDogBiscuits int `json:\"dog_biscuits\"`\n\tLights bool `json:\"lights\"`\n\tKettle bool `json:\"kettle\"`\n\tVacuumRoom string `json:\"vacuum_room\"`\n}\n\n\n\n\n\n\nfunc dispenseDogBiscuits(cargo interface{}) statemachiner.StateFn {\n\tcargo.(*Home).DispenseDogBiscuits = 10\n\tcargo.(*Home).TotalDogBiscuits += cargo.(*Home).DispenseDogBiscuits\n\tfmt.Printf(\"%+v\\n\", cargo)\n\treturn lights\n}\n\n\nfunc lights(cargo interface{}) statemachiner.StateFn {\n\tcargo.(*Home).Lights = true\n\tfmt.Printf(\"%+v\\n\", cargo)\n\treturn kettle\n}\n\n\nfunc kettle(cargo interface{}) statemachiner.StateFn {\n\tcargo.(*Home).Kettle = true\n\tfmt.Printf(\"%+v\\n\", cargo)\n\treturn vacuumRoom\n}\n\n\nfunc vacuumRoom(cargo interface{}) statemachiner.StateFn {\n\tif cargo.(*Home).TotalDogBiscuits < 20 {\n\t\treturn dispenseDogBiscuits\n\t} else {\n\t\tcargo.(*Home).VacuumRoom = \"kitchen\"\n\t}\n\tfmt.Printf(\"%+v\\n\", cargo)\n\treturn nil\n}\n\nfunc NewHome() *Home ", "output": "{\n\treturn &Home{}\n}"} {"input": "package main\n\nimport (\n\t\"time\"\n\n\t\"github.com/PalmStoneGames/polymer\"\n)\n\n\n\ntype Timer struct {\n\t*polymer.Proto\n\n\tTime time.Time `polymer:\"bind\"`\n}\n\nfunc (t *Timer) Created() {\n\tgo func() {\n\t\tfor {\n\t\t\tt.Time = time.Now()\n\n\t\t\tt.Notify(\"time\")\n\n\t\t\ttime.Sleep(time.Millisecond * 100)\n\t\t}\n\t}()\n}\n\nfunc (t *Timer) ComputeTime() string {\n\treturn t.Time.String()\n}\n\nfunc main() {}\n\nfunc init() ", "output": "{\n\tpolymer.Register(\"tick-timer\", &Timer{})\n}"} {"input": "package datastructures\n\n\ntype Comparable interface {\n\tCompare(Comparable) int\n}\n\n\ntype Comparables []Comparable\n\n\nfunc (cs Comparables) Len() int {\n\treturn len(cs)\n}\n\n\nfunc (cs Comparables) Less(i, j int) bool {\n\tif cs[i].Compare(cs[j]) < 0 {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\nfunc (cs *Comparables) Shift() Comparable {\n\tif len(*cs) == 0 {\n\t\treturn nil\n\t}\n\n\tf := (*cs)[0]\n\t*cs = (*cs)[1:]\n\treturn f\n}\n\n\n\n\n\ntype IntComparable int\n\n\nfunc (ic IntComparable) Compare(i Comparable) int {\n\tother, ok := i.(IntComparable)\n\n\tif !ok {\n\t\tpanic(\"param should be an intComparable\")\n\t}\n\n\tif int(ic) == int(other) {\n\t\treturn 0\n\t} else if int(ic) < int(other) {\n\t\treturn -1\n\t} else {\n\t\treturn 1\n\t}\n}\n\nfunc (cs Comparables) Swap(i, j int) ", "output": "{\n\tcs[i], cs[j] = cs[j], cs[i]\n}"} {"input": "package main\n\nvar log string\n\ntype T int\n\n\n\nfunc (T) b(s string) string {\n\tlog += \"b\"\n\treturn s\n}\n\ntype F func(s string) F\n\nfunc a(s string) F {\n\tlog += \"a(\" + s + \")\"\n\treturn F(a)\n}\n\nfunc b(s string) string {\n\tlog += \"b\"\n\treturn s\n}\n\ntype I interface {\n\ta(s string) I\n\tb(s string) string\n}\n\ntype T1 int\n\nfunc (t T1) a(s string) I {\n\tlog += \"a(\" + s + \")\"\n\treturn t\n}\n\nfunc (T1) b(s string) string {\n\tlog += \"b\"\n\treturn s\n}\n\nvar ok = true\n\nfunc bad() {\n\tif !ok {\n\t\tprintln(\"BUG\")\n\t\tok = false\n\t}\n\tprintln(log)\n}\n\nfunc main() {\n\tvar t T\n\tif t.a(\"1\").a(t.b(\"2\")); log != \"a(1)ba(2)\" {\n\t\tbad()\n\t}\n\tlog = \"\"\n\tif a(\"3\")(b(\"4\"))(b(\"5\")); log != \"a(3)ba(4)ba(5)\" {\n\t\tbad()\n\t}\n\tlog = \"\"\n\tvar i I = T1(0)\n\tif i.a(\"6\").a(i.b(\"7\")).a(i.b(\"8\")).a(i.b(\"9\")); log != \"a(6)ba(7)ba(8)ba(9)\" {\n\t\tbad()\n\t}\n}\n\nfunc (t T) a(s string) T ", "output": "{\n\tlog += \"a(\" + s + \")\"\n\treturn t\n}"} {"input": "package api\n\ntype Memstore map[string]*Collection\n\nfunc (m Memstore) Init(dbName string) error {\n\treturn nil\n}\n\nfunc (m Memstore) CreateCollection(slug, name string) (Collection, error) {\n\tm[slug] = &Collection{Name: name,\n\t\tSlug: slug,\n\t\tItems: map[string]Item{},\n\t}\n\treturn *m[slug], nil\n}\n\n\n\nfunc (m Memstore) GetCollectionData(slug string) (Collection, error) {\n\tif c, ok := m[slug]; ok {\n\t\t(*c).Items = nil\n\t\treturn *c, nil\n\t}\n\treturn Collection{}, CollectionNotFoundError\n}\n\nfunc (m Memstore) GetCollectionItems(slug string) (map[string]Item, error) {\n\tif c, ok := m[slug]; ok {\n\t\treturn c.Items, nil\n\t}\n\treturn map[string]Item{}, CollectionNotFoundError\n}\n\nfunc (m Memstore) AddItemToCollection(slug string, item Item) error {\n\tif c, ok := m[slug]; ok {\n\t\tc.Items[item.Tag] = item\n\t\treturn nil\n\t}\n\treturn CollectionNotFoundError\n}\n\nfunc (m Memstore) GetItemFromCollection(slug, tag string) (Item, error) {\n\tif _, ok := m[slug]; !ok {\n\t\treturn Item{}, CollectionNotFoundError\n\t}\n\tif _, ok := m[slug].Items[tag]; !ok {\n\t\treturn Item{}, BlobNotFoundError\n\t}\n\treturn m[slug].Items[tag], nil\n}\n\nfunc (m Memstore) UpdateCollection(slug, name string) error ", "output": "{\n\tif c, ok := m[slug]; !ok {\n\t\treturn CollectionNotFoundError\n\t} else {\n\t\tc.Name = name\n\t}\n\treturn nil\n}"} {"input": "package geth\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/etherite/go-etherite/core\"\n\t\"github.com/etherite/go-etherite/p2p/discv5\"\n\t\"github.com/etherite/go-etherite/params\"\n)\n\n\n\n\n\n\nfunc TestnetGenesis() string {\n\tenc, err := json.Marshal(core.DefaultTestnetGenesisBlock())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(enc)\n}\n\n\nfunc RinkebyGenesis() string {\n\tenc, err := json.Marshal(core.DefaultRinkebyGenesisBlock())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(enc)\n}\n\n\n\nfunc FoundationBootnodes() *Enodes {\n\tnodes := &Enodes{nodes: make([]*discv5.Node, len(params.DiscoveryV5Bootnodes))}\n\tfor i, url := range params.DiscoveryV5Bootnodes {\n\t\tnodes.nodes[i] = discv5.MustParseNode(url)\n\t}\n\treturn nodes\n}\n\nfunc MainnetGenesis() string ", "output": "{\n\treturn \"\"\n}"} {"input": "package app\n\nimport (\n\t\"net/url\"\n)\n\ntype Service interface {\n\tProxyPath() string\n\tURL() string\n\tBasicAuth() (username, password string, ok bool)\n\tAddSecret(parameters url.Values)\n}\n\ntype basicAuthService struct {\n\tproxyPath, url, clientId, clientSecret string\n}\n\nfunc (s basicAuthService) ProxyPath() string {\n\treturn s.proxyPath\n}\n\nfunc (s basicAuthService) URL() string {\n\treturn s.url\n}\n\nfunc (s basicAuthService) BasicAuth() (string, string, bool) {\n\treturn s.clientId, s.clientSecret, true\n}\n\nfunc (s basicAuthService) AddSecret(parameters url.Values) {\n}\n\ntype addParameterService struct {\n\tproxyPath, url, parameterName, clientSecret string\n}\n\nfunc (s addParameterService) ProxyPath() string {\n\treturn s.proxyPath\n}\n\nfunc (s addParameterService) URL() string {\n\treturn s.url\n}\n\n\n\nfunc (s addParameterService) AddSecret(parameters url.Values) {\n\tparameters.Add(s.parameterName, s.clientSecret)\n}\n\nfunc BasicAuthService(proxyPath, url, clientId, clientSecret string) Service {\n\treturn basicAuthService{proxyPath, url, clientId, clientSecret}\n}\n\nfunc AddParameterService(proxyPath, url, parameterName, clientSecret string) Service {\n\treturn addParameterService{proxyPath, url, parameterName, clientSecret}\n}\n\nfunc (s addParameterService) BasicAuth() (string, string, bool) ", "output": "{\n\treturn \"\", \"\", false\n}"} {"input": "package crypto\n\nimport (\n\t\"errors\"\n\t\"crypto/rsa\"\n\t\"crypto/x509\"\n\t\"encoding/pem\"\n)\n\nfunc LoadRSAPrivateKey(key []byte) (*rsa.PrivateKey, error) {\n\tparsed_key, err := LoadPrivateKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar rsa_private_key *rsa.PrivateKey\n\tvar ok bool = false\n\trsa_private_key, ok = parsed_key.(*rsa.PrivateKey)\n\tif !ok {\n\t\treturn nil, errors.New(\"invalid RSA private key.\")\n\t}\n\n\treturn rsa_private_key, nil\n}\n\nfunc LoadRSAPublicKey(key []byte) (*rsa.PublicKey, error) {\n\tparsed_key, err := LoadPublicKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar rsa_public_key *rsa.PublicKey\n\tvar ok bool = false\n\trsa_public_key, ok = parsed_key.(*rsa.PublicKey)\n\tif !ok {\n\t\treturn nil, errors.New(\"invalid RSA public key.\")\n\t}\n\n\treturn rsa_public_key, nil\n}\n\nfunc CreateRSAPrivateKeyPEM(prvkey *rsa.PrivateKey) ([]byte, error) {\n\tder := x509.MarshalPKCS1PrivateKey(prvkey)\n\tdata := pem.EncodeToMemory(\n\t\t&pem.Block{\n\t\t\tType: \"RSA PRIVATE KEY\",\n\t\t\tBytes: der,\n\t\t},\n\t)\n\n\treturn data, nil\n}\n\n\n\nfunc CreateRSAPublicKeyPEM(pubkey *rsa.PublicKey) ([]byte, error) ", "output": "{\n\tder, err := x509.MarshalPKIXPublicKey(pubkey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdata := pem.EncodeToMemory(\n\t\t&pem.Block{\n\t\t\tType: \"RSA PUBLIC KEY\",\n\t\t\tBytes: der,\n\t\t},\n\t)\n\n\treturn data, nil\n}"} {"input": "package client\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/mesosphere/dcos-commons/cli/config\"\n)\n\n\n\nvar PrintMessage = printMessage\n\n\n\nvar PrintMessageAndExit = printMessageAndExit\n\nfunc printMessage(format string, a ...interface{}) (int, error) {\n\treturn fmt.Println(fmt.Sprintf(format, a...))\n}\n\nfunc printMessageAndExit(format string, a ...interface{}) (int, error) {\n\tPrintMessage(format, a...)\n\tos.Exit(1)\n\treturn 0, nil\n}\n\n\n\n\n\n\n\nfunc PrintJSONBytes(responseBytes []byte) {\n\tvar outBuf bytes.Buffer\n\terr := json.Indent(&outBuf, responseBytes, \"\", \" \")\n\tif err != nil {\n\t\tPrintMessage(\"Failed to prettify JSON response data: %s\", err)\n\t\tPrintMessage(\"Original data follows:\")\n\t\toutBuf = *bytes.NewBuffer(responseBytes)\n\t}\n\tPrintMessage(\"%s\", outBuf.String())\n}\n\n\nfunc PrintResponseText(body []byte) {\n\tPrintMessage(\"%s\\n\", string(body))\n}\n\nfunc PrintVerbose(format string, a ...interface{}) (int, error) ", "output": "{\n\tif config.Verbose {\n\t\treturn PrintMessage(format, a...)\n\t}\n\treturn 0, nil\n}"} {"input": "package io\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc Info(args ...interface{}) {\n\tfmt.Print(\"\\033[1m-----> \")\n\targs = append(args, \"\\033[0m\")\n\tfmt.Println(args...)\n}\n\nfunc Infof(format string, args ...interface{}) {\n\tfmt.Print(\"\\033[1m-----> \")\n\tfmt.Printf(format+\"\\033[0m\", args...)\n}\n\nfunc Print(args ...interface{}) {\n\tfmt.Print(\" \")\n\tfmt.Println(args...)\n}\n\nfunc Printf(format string, args ...interface{}) {\n\tfmt.Print(\" \")\n\tfmt.Printf(format, args...)\n}\n\n\n\nfunc Error(args ...interface{}) {\n\tfmt.Print(\" ! \")\n\tfmt.Println(args...)\n\tos.Exit(1)\n}\n\nfunc Warnf(format string, args ...interface{}) ", "output": "{\n\tfmt.Print(\" ! \")\n\tfmt.Printf(format, args...)\n}"} {"input": "package mongo\n\nimport (\n\t\"fmt\"\n\t\"labix.org/v2/mgo\"\n\t\"testing\"\n)\n\nvar (\n\ttaro = &User{Name: \"Taro\", Age: 20}\n\thanako = &User{Name: \"Hanako\", Age: 22}\n)\n\n\n\n\n\nfunc TestFind(t *testing.T) {\n\tuser, err := Find(taro.Name)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif user.Name != taro.Name || user.Age != taro.Age {\n\t\tt.Error(fmt.Sprintf(\"検索結果が不正です。[期待値: %+v][実際: %+v]\", taro, user))\n\t}\n\n\tuser, err = Find(\"X\")\n\tif err == nil || err.Error() != \"not found\" {\n\t\tt.Error(\"検索結果が不正です。検索結果が存在します。\")\n\t}\n}\n\nfunc init() ", "output": "{\n\tsession, err := mgo.Dial(\"localhost\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer session.Close()\n\tsession.SetMode(mgo.Monotonic, true)\n\tc := session.DB(\"droneTest\").C(\"users\")\n\tc.DropCollection()\n\terr = c.Insert(taro)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = c.Insert(hanako)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}"} {"input": "package util\n\nimport (\n\t\"crypto\"\n\t\"io\"\n\n\t\"golang.org/x/crypto/ssh\"\n)\n\nfunc SignatureFormatFromSigningOptionAndCA(opt string, ca ssh.PublicKey) string {\n\tswitch {\n\tcase ca != nil && ca.Type() == ssh.KeyAlgoED25519:\n\t\treturn ssh.KeyAlgoED25519\n\tcase ca != nil && ca.Type() == ssh.KeyAlgoRSA && opt == \"\":\n\t\treturn ssh.SigAlgoRSA\n\tdefault:\n\t\treturn opt\n\t}\n}\n\ntype ExtendedAgentSigner interface {\n\tssh.Signer\n\tSignWithOpts(rand io.Reader, data []byte, opts crypto.SignerOpts) (*ssh.Signature, error)\n}\n\ntype ExtendedAgentSignerWrapper struct {\n\tOpts crypto.SignerOpts\n\tSigner ExtendedAgentSigner\n}\n\nfunc (e *ExtendedAgentSignerWrapper) PublicKey() ssh.PublicKey {\n\treturn e.Signer.PublicKey()\n}\n\nfunc (e *ExtendedAgentSignerWrapper) Sign(rand io.Reader, data []byte) (*ssh.Signature, error) {\n\treturn e.Signer.SignWithOpts(rand, data, e.Opts)\n}\n\ntype AlgorithmSignerWrapper struct {\n\tAlgorithm string\n\tSigner ssh.AlgorithmSigner\n}\n\nfunc (a *AlgorithmSignerWrapper) PublicKey() ssh.PublicKey {\n\treturn a.Signer.PublicKey()\n}\n\n\n\nfunc (a *AlgorithmSignerWrapper) Sign(rand io.Reader, data []byte) (*ssh.Signature, error) ", "output": "{\n\treturn a.Signer.SignWithAlgorithm(rand, data, a.Algorithm)\n}"} {"input": "package plugin\n\n\n\nimport (\n\t\"strings\"\n\t\"time\"\n\t\"github.com/microamp/gerri/cmd\"\n\t\"github.com/microamp/gerri/data\"\n)\n\n\n\nfunc ReplyDay(pm data.Privmsg, config *data.Config) (string, error) ", "output": "{\n\treturn cmd.Privmsg(pm.Target, strings.ToLower(time.Now().Weekday().String())), nil\n}"} {"input": "package v1\n\nimport (\n\tv1 \"github.com/openshift/api/config/v1\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/client-go/tools/cache\"\n)\n\n\ntype IdentityProviderLister interface {\n\tList(selector labels.Selector) (ret []*v1.IdentityProvider, err error)\n\tGet(name string) (*v1.IdentityProvider, error)\n\tIdentityProviderListerExpansion\n}\n\n\ntype identityProviderLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewIdentityProviderLister(indexer cache.Indexer) IdentityProviderLister {\n\treturn &identityProviderLister{indexer: indexer}\n}\n\n\nfunc (s *identityProviderLister) List(selector labels.Selector) (ret []*v1.IdentityProvider, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.IdentityProvider))\n\t})\n\treturn ret, err\n}\n\n\n\n\nfunc (s *identityProviderLister) Get(name string) (*v1.IdentityProvider, error) ", "output": "{\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"identityprovider\"), name)\n\t}\n\treturn obj.(*v1.IdentityProvider), nil\n}"} {"input": "package controllers\n\nimport (\n\t\"github.com/astaxie/beego\"\n)\n\ntype LoginController struct {\n\tbeego.Controller\n}\n\n\n\nfunc (c *LoginController) Get() ", "output": "{\n\tc.Layout = \"basic_layout.html\"\n\tc.TplName = \"login.html\"\n\n}"} {"input": "package uchiwa\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestSliceIntersection(t *testing.T) {\n\tvar a1, a2 []string\n\n\tfound := SliceIntersection(a1, a2)\n\tassert.Equal(t, false, found, \"if both slices are empty, it should return false\")\n\n\ta1 = []string{\"foo\", \"bar\"}\n\tfound = SliceIntersection(a1, a2)\n\tassert.Equal(t, false, found, \"if one slice is empty, it should return false\")\n\n\ta2 = []string{\"baz\", \"qux\"}\n\tfound = SliceIntersection(a1, a2)\n\tassert.Equal(t, false, found, \"it should return false is none of the elements in the slices are shared\")\n\n\ta2 = append(a2, \"foo\")\n\tfound = SliceIntersection(a1, a2)\n\tassert.Equal(t, true, found, \"it should return true if at least one element is shared between the slices\")\n}\n\n\n\nfunc TestMergeStringSlice(t *testing.T) ", "output": "{\n\tvar a1, a2 []string\n\n\tslice := MergeStringSlices(a1, a2)\n\tassert.Equal(t, []string(nil), slice, \"if both slices are empty, it should return an empty slice\")\n\n\ta1 = []string{\"1\", \"2\"}\n\tslice = MergeStringSlices(a1, a2)\n\tassert.Equal(t, a1, slice, \"if one slice is empty, it should return the other slice\")\n\n\ta2 = []string{\"2\"}\n\tslice = MergeStringSlices(a1, a2)\n\tassert.Equal(t, a1, slice, \"if one slice is empty, it should return the other slice\")\n\n\ta2 = []string{\"2\", \"3\"}\n\tslice = MergeStringSlices(a1, a2)\n\tassert.Equal(t, []string{\"1\", \"2\", \"3\"}, slice, \"if one slice is empty, it should return the other slice\")\n\n}"} {"input": "package readline\n\nimport (\n\t\"github.com/golang/glog\"\n\t\"github.com/jcw/flow\"\n\n\t\"bufio\"\n\t\"os\"\n)\n\n\n\n\n\n\ntype ReadlineStdIn struct {\n\tflow.Gadget\n\n\tOut flow.Output \n}\n\nfunc (g *ReadlineStdIn) Run() {\n\n\texit := false\n\n\tsin := bufio.NewScanner(os.Stdin)\n\n\tfor exit == false {\n\n\t\tvar line string\n\t\tfor sin.Scan() {\n\t\t\tline = sin.Text()\n\t\t\tg.Out.Send(line)\n\t\t}\n\n\t\terr := sin.Err()\n\n\t\tif err != nil {\n\t\t\tglog.Errorln(\"ReadlineStdIn Error:\", err)\n\t\t}\n\n\t}\n\n}\n\nfunc init() ", "output": "{\n\tglog.Info(\"ReadlineStdIn Init...\")\n\tflow.Registry[\"ReadlineStdIn\"] = func() flow.Circuitry { return new(ReadlineStdIn) }\n\n}"} {"input": "package managementlegacy\n\nimport (\n\t\"context\"\n\n\t\"github.com/rancher/rancher/pkg/clustermanager\"\n\t\"github.com/rancher/rancher/pkg/controllers/managementlegacy/catalog\"\n\t\"github.com/rancher/rancher/pkg/controllers/managementlegacy/cis\"\n\t\"github.com/rancher/rancher/pkg/controllers/managementlegacy/compose\"\n\t\"github.com/rancher/rancher/pkg/controllers/managementlegacy/globaldns\"\n\t\"github.com/rancher/rancher/pkg/controllers/managementlegacy/multiclusterapp\"\n\t\"github.com/rancher/rancher/pkg/types/config\"\n)\n\n\n\nfunc Register(ctx context.Context, management *config.ManagementContext, manager *clustermanager.Manager) ", "output": "{\n\tcatalog.Register(ctx, management)\n\tcompose.Register(ctx, management, manager)\n\tcis.Register(ctx, management)\n\tglobaldns.Register(ctx, management)\n\tmulticlusterapp.Register(ctx, management, manager)\n}"} {"input": "package channelparticipation\n\nimport (\n\t\"errors\"\n\n\tcb \"github.com/hyperledger/fabric-protos-go/common\"\n\t\"github.com/hyperledger/fabric/bccsp/factory\"\n\t\"github.com/hyperledger/fabric/common/channelconfig\"\n\t\"github.com/hyperledger/fabric/protoutil\"\n)\n\n\n\n\n\n\nfunc ValidateJoinBlock(configBlock *cb.Block) (channelID string, isAppChannel bool, err error) ", "output": "{\n\tif !protoutil.IsConfigBlock(configBlock) {\n\t\treturn \"\", false, errors.New(\"block is not a config block\")\n\t}\n\n\tenvelope, err := protoutil.ExtractEnvelope(configBlock, 0)\n\tif err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\tcryptoProvider := factory.GetDefault()\n\tbundle, err := channelconfig.NewBundleFromEnvelope(envelope, cryptoProvider)\n\tif err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\tchannelID = bundle.ConfigtxValidator().ChannelID()\n\n\t_, isSystemChannel := bundle.ConsortiumsConfig()\n\tif !isSystemChannel {\n\t\t_, isAppChannel = bundle.ApplicationConfig()\n\t\tif !isAppChannel {\n\t\t\treturn \"\", false, errors.New(\"invalid config: must have at least one of application or consortiums\")\n\t\t}\n\t}\n\n\treturn channelID, isAppChannel, err\n}"} {"input": "package dal\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\n\n\nfunc (d *Dal) UpdateCheckState(state bool, checkName string) error ", "output": "{\n\tfullPath := \"monitor/\" + checkName\n\n\tdata, err := d.Get(fullPath, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar tmp map[string]interface{}\n\n\tif err := json.Unmarshal([]byte(data[fullPath]), &tmp); err != nil {\n\t\treturn fmt.Errorf(\"Unable to perform unmarshal on '%v' config: %v\", checkName, err)\n\t}\n\n\ttmp[\"disable\"] = state\n\n\tnewData, err := json.Marshal(tmp)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to marshal final config for '%v': %v\", checkName, err)\n\t}\n\n\tif err := d.Set(fullPath, string(newData), &SetOptions{Dir: false, TTLSec: 0, PrevExist: \"\"}); err != nil {\n\t\treturn fmt.Errorf(\"Unable to update config '%v' in etcd: %v\", checkName, err)\n\t}\n\n\treturn nil\n}"} {"input": "package core\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype PlatformConfig interface {\n}\n\ntype platformconfig struct {\n\tJsonData []byte\n\tType string `json:\"type\"`\n}\n\n\n\n\n\nfunc (m *platformconfig) UnmarshalPolymorphicJSON(data []byte) (interface{}, error) {\n\n\tif data == nil || string(data) == \"null\" {\n\t\treturn nil, nil\n\t}\n\n\tvar err error\n\tswitch m.Type {\n\tcase \"AMD_MILAN_BM\":\n\t\tmm := AmdMilanBmPlatformConfig{}\n\t\terr = json.Unmarshal(data, &mm)\n\t\treturn mm, err\n\tdefault:\n\t\treturn *m, nil\n\t}\n}\n\nfunc (m platformconfig) String() string {\n\treturn common.PointerString(m)\n}\n\n\ntype PlatformConfigTypeEnum string\n\n\nconst (\n\tPlatformConfigTypeAmdMilanBm PlatformConfigTypeEnum = \"AMD_MILAN_BM\"\n)\n\nvar mappingPlatformConfigType = map[string]PlatformConfigTypeEnum{\n\t\"AMD_MILAN_BM\": PlatformConfigTypeAmdMilanBm,\n}\n\n\nfunc GetPlatformConfigTypeEnumValues() []PlatformConfigTypeEnum {\n\tvalues := make([]PlatformConfigTypeEnum, 0)\n\tfor _, v := range mappingPlatformConfigType {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}\n\nfunc (m *platformconfig) UnmarshalJSON(data []byte) error ", "output": "{\n\tm.JsonData = data\n\ttype Unmarshalerplatformconfig platformconfig\n\ts := struct {\n\t\tModel Unmarshalerplatformconfig\n\t}{}\n\terr := json.Unmarshal(data, &s.Model)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.Type = s.Model.Type\n\n\treturn err\n}"} {"input": "package versioned\n\nimport (\n\toauthv1 \"github.com/openshift/client-go/oauth/clientset/versioned/typed/oauth/v1\"\n\tdiscovery \"k8s.io/client-go/discovery\"\n\trest \"k8s.io/client-go/rest\"\n\tflowcontrol \"k8s.io/client-go/util/flowcontrol\"\n)\n\ntype Interface interface {\n\tDiscovery() discovery.DiscoveryInterface\n\tOauthV1() oauthv1.OauthV1Interface\n}\n\n\n\ntype Clientset struct {\n\t*discovery.DiscoveryClient\n\toauthV1 *oauthv1.OauthV1Client\n}\n\n\nfunc (c *Clientset) OauthV1() oauthv1.OauthV1Interface {\n\treturn c.oauthV1\n}\n\n\nfunc (c *Clientset) Discovery() discovery.DiscoveryInterface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.DiscoveryClient\n}\n\n\nfunc NewForConfig(c *rest.Config) (*Clientset, error) {\n\tconfigShallowCopy := *c\n\tif configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 {\n\t\tconfigShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst)\n\t}\n\tvar cs Clientset\n\tvar err error\n\tcs.oauthV1, err = oauthv1.NewForConfig(&configShallowCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &cs, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *Clientset {\n\tvar cs Clientset\n\tcs.oauthV1 = oauthv1.NewForConfigOrDie(c)\n\n\tcs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c)\n\treturn &cs\n}\n\n\n\n\nfunc New(c rest.Interface) *Clientset ", "output": "{\n\tvar cs Clientset\n\tcs.oauthV1 = oauthv1.New(c)\n\n\tcs.DiscoveryClient = discovery.NewDiscoveryClient(c)\n\treturn &cs\n}"} {"input": "package httpx\n\nimport (\n\t\"net/http\"\n\n\t\"golang.org/x/net/context\"\n)\n\nvar clientContextKey = 0\nvar defaultClient = &http.Client{}\n\n\n\n\n\n\n\n\n\nfunc ClientContext(parent context.Context, client *http.Client) context.Context {\n\tif client == nil {\n\t\tpanic(\"Cannot bind nil *http.Client to context tree\")\n\t}\n\n\treturn context.WithValue(parent, &clientContextKey, client)\n}\n\nfunc ClientFromContext(ctx context.Context) *http.Client ", "output": "{\n\tfound := ctx.Value(&clientContextKey)\n\n\tif found == nil {\n\t\treturn defaultClient\n\t}\n\n\treturn found.(*http.Client)\n}"} {"input": "package model\n\nimport (\n\t\"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/core/utils\"\n\n\t\"strings\"\n)\n\n\ntype Link struct {\n\n\tHref string `json:\"href\"`\n\n\tRel string `json:\"rel\"`\n}\n\n\n\nfunc (o Link) String() string ", "output": "{\n\tdata, err := utils.Marshal(o)\n\tif err != nil {\n\t\treturn \"Link struct{}\"\n\t}\n\n\treturn strings.Join([]string{\"Link\", string(data)}, \" \")\n}"} {"input": "package client\n\nimport (\n\t\"context\"\n\t\"strconv\"\n\n\t\"github.com/containerd/containerd/containers\"\n\t\"github.com/containerd/containerd/oci\"\n\tspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n)\n\nconst newLine = \"\\r\\n\"\n\nfunc withExitStatus(es int) oci.SpecOpts {\n\treturn func(_ context.Context, _ oci.Client, _ *containers.Container, s *specs.Spec) error {\n\t\ts.Process.Args = []string{\"cmd\", \"/c\", \"exit\", strconv.Itoa(es)}\n\t\treturn nil\n\t}\n}\n\nfunc withProcessArgs(args ...string) oci.SpecOpts {\n\treturn oci.WithProcessArgs(append([]string{\"cmd\", \"/c\"}, args...)...)\n}\n\nfunc withCat() oci.SpecOpts {\n\treturn oci.WithProcessArgs(\"cmd\", \"/c\", \"more\")\n}\n\nfunc withTrue() oci.SpecOpts {\n\treturn oci.WithProcessArgs(\"cmd\", \"/c\")\n}\n\n\n\nfunc withExecArgs(s *specs.Process, args ...string) {\n\ts.Args = append([]string{\"cmd\", \"/c\"}, args...)\n}\n\nfunc withExecExitStatus(s *specs.Process, es int) ", "output": "{\n\ts.Args = []string{\"cmd\", \"/c\", \"exit\", strconv.Itoa(es)}\n}"} {"input": "package plAuth\n\nimport (\n\t\"fmt\"\n)\n\n\n\ntype UnsetPassword struct {\n\tuser *User\n}\n\n\n\n\ntype WrongPassword int\n\nfunc (e WrongPassword) Error() string {\n\treturn fmt.Sprintf(\"Invalid Password\")\n}\n\n\ntype ValidationError struct {\n\tReason string\n}\n\nfunc (e ValidationError) Error() string {\n\treturn e.Reason\n}\n\ntype InterfaceConversionError struct {\n\tFailed interface{}\n}\n\nfunc (e InterfaceConversionError) Error() string {\n\treturn fmt.Sprintf(\"Conversition failed %#v\", e.Failed)\n}\n\ntype UserAllreadyExists struct {\n\texistingUser *User\n}\n\nfunc (e UserAllreadyExists) Error() string {\n\treturn fmt.Sprintf(\"A user with this data allreay exists: %v\", e.existingUser)\n}\n\nfunc (e UnsetPassword) Error() string ", "output": "{\n\treturn fmt.Sprintf(\"%s has no password set. Call SetPass() first!\", e.user)\n}"} {"input": "package channel\n\nimport (\n\t\"testing\"\n)\n\n\nfunc TestController(t *testing.T) {\n\tcontroller()\n}\n\nfunc TestBuffers(t *testing.T) ", "output": "{\n\tbuffers()\n}"} {"input": "package fake\n\nimport (\n\tv1beta1 \"k8s.io/client-go/kubernetes/typed/extensions/v1beta1\"\n\trest \"k8s.io/client-go/rest\"\n\ttesting \"k8s.io/client-go/testing\"\n)\n\ntype FakeExtensionsV1beta1 struct {\n\t*testing.Fake\n}\n\nfunc (c *FakeExtensionsV1beta1) DaemonSets(namespace string) v1beta1.DaemonSetInterface {\n\treturn &FakeDaemonSets{c, namespace}\n}\n\nfunc (c *FakeExtensionsV1beta1) Deployments(namespace string) v1beta1.DeploymentInterface {\n\treturn &FakeDeployments{c, namespace}\n}\n\nfunc (c *FakeExtensionsV1beta1) Ingresses(namespace string) v1beta1.IngressInterface {\n\treturn &FakeIngresses{c, namespace}\n}\n\nfunc (c *FakeExtensionsV1beta1) PodSecurityPolicies() v1beta1.PodSecurityPolicyInterface {\n\treturn &FakePodSecurityPolicies{c}\n}\n\nfunc (c *FakeExtensionsV1beta1) ReplicaSets(namespace string) v1beta1.ReplicaSetInterface {\n\treturn &FakeReplicaSets{c, namespace}\n}\n\n\n\n\n\nfunc (c *FakeExtensionsV1beta1) RESTClient() rest.Interface {\n\tvar ret *rest.RESTClient\n\treturn ret\n}\n\nfunc (c *FakeExtensionsV1beta1) Scales(namespace string) v1beta1.ScaleInterface ", "output": "{\n\treturn &FakeScales{c, namespace}\n}"} {"input": "package parseutil\n\nimport (\n\t\"strings\"\n\n\t\"src.elv.sh/pkg/parse\"\n)\n\n\nfunc Wordify(src string) []string {\n\ttree, _ := parse.Parse(parse.Source{Code: src}, parse.Config{})\n\treturn wordifyInner(tree.Root, nil)\n}\n\nfunc wordifyInner(n parse.Node, words []string) []string {\n\tif len(parse.Children(n)) == 0 || isCompound(n) {\n\t\ttext := parse.SourceText(n)\n\t\tif strings.TrimFunc(text, parse.IsWhitespace) != \"\" {\n\t\t\treturn append(words, text)\n\t\t}\n\t\treturn words\n\t}\n\tfor _, ch := range parse.Children(n) {\n\t\twords = wordifyInner(ch, words)\n\t}\n\treturn words\n}\n\n\n\nfunc isCompound(n parse.Node) bool ", "output": "{\n\t_, ok := n.(*parse.Compound)\n\treturn ok\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/hyperledger/fabric/common/channelconfig\"\n\tab \"github.com/hyperledger/fabric/protos/orderer\"\n)\n\n\ntype Orderer struct {\n\tConsensusTypeVal string\n\tBatchSizeVal *ab.BatchSize\n\tBatchTimeoutVal time.Duration\n\tKafkaBrokersVal []string\n\tMaxChannelsCountVal uint64\n\tOrganizationsVal map[string]channelconfig.Org\n\tCapabilitiesVal channelconfig.OrdererCapabilities\n}\n\n\nfunc (scm *Orderer) ConsensusType() string {\n\treturn scm.ConsensusTypeVal\n}\n\n\nfunc (scm *Orderer) BatchSize() *ab.BatchSize {\n\treturn scm.BatchSizeVal\n}\n\n\nfunc (scm *Orderer) BatchTimeout() time.Duration {\n\treturn scm.BatchTimeoutVal\n}\n\n\nfunc (scm *Orderer) KafkaBrokers() []string {\n\treturn scm.KafkaBrokersVal\n}\n\n\nfunc (scm *Orderer) MaxChannelsCount() uint64 {\n\treturn scm.MaxChannelsCountVal\n}\n\n\nfunc (scm *Orderer) Organizations() map[string]channelconfig.Org {\n\treturn scm.OrganizationsVal\n}\n\n\nfunc (scm *Orderer) Capabilities() channelconfig.OrdererCapabilities {\n\treturn scm.CapabilitiesVal\n}\n\n\ntype OrdererCapabilities struct {\n\tSupportedErr error\n\n\tSetChannelModPolicyDuringCreateVal bool\n\n\tResubmissionVal bool\n}\n\n\n\n\n\nfunc (oc *OrdererCapabilities) SetChannelModPolicyDuringCreate() bool {\n\treturn oc.SetChannelModPolicyDuringCreateVal\n}\n\n\nfunc (oc *OrdererCapabilities) Resubmission() bool {\n\treturn oc.ResubmissionVal\n}\n\nfunc (oc *OrdererCapabilities) Supported() error ", "output": "{\n\treturn oc.SupportedErr\n}"} {"input": "package mem\n\nimport (\n\t\"bytes\"\n\t\"sort\"\n\n\tsgmt \"github.com/m3db/m3/src/m3ninx/index/segment\"\n)\n\ntype bytesSliceIter struct {\n\terr error\n\tdone bool\n\n\tcurrentIdx int\n\tcurrent []byte\n\tbackingSlice [][]byte\n\topts Options\n}\n\nvar _ sgmt.FieldsIterator = &bytesSliceIter{}\n\n\n\nfunc (b *bytesSliceIter) Next() bool {\n\tif b.done || b.err != nil {\n\t\treturn false\n\t}\n\tb.currentIdx++\n\tif b.currentIdx >= len(b.backingSlice) {\n\t\tb.done = true\n\t\treturn false\n\t}\n\tb.current = b.backingSlice[b.currentIdx]\n\treturn true\n}\n\nfunc (b *bytesSliceIter) Current() []byte {\n\treturn b.current\n}\n\nfunc (b *bytesSliceIter) Err() error {\n\treturn nil\n}\n\nfunc (b *bytesSliceIter) Len() int {\n\treturn len(b.backingSlice)\n}\n\nfunc (b *bytesSliceIter) Close() error {\n\tb.current = nil\n\tb.opts.BytesSliceArrayPool().Put(b.backingSlice)\n\treturn nil\n}\n\nfunc sortSliceOfByteSlices(b [][]byte) {\n\tsort.Slice(b, func(i, j int) bool {\n\t\treturn bytes.Compare(b[i], b[j]) < 0\n\t})\n}\n\nfunc newBytesSliceIter(slice [][]byte, opts Options) *bytesSliceIter ", "output": "{\n\tsortSliceOfByteSlices(slice)\n\treturn &bytesSliceIter{\n\t\tcurrentIdx: -1,\n\t\tbackingSlice: slice,\n\t\topts: opts,\n\t}\n}"} {"input": "package libcontainer\n\nimport (\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/opencontainers/runc/libcontainer/configs\"\n)\n\n\ntype Status int\n\nconst (\n\tCreated Status = iota\n\tRunning\n\tPausing\n\tPaused\n\tStopped\n)\n\n\n\n\n\ntype BaseState struct {\n\tID string `json:\"id\"`\n\n\tInitProcessPid int `json:\"init_process_pid\"`\n\n\tInitProcessStartTime string `json:\"init_process_start\"`\n\n\tCreated time.Time `json:\"created\"`\n\n\tConfig configs.Config `json:\"config\"`\n}\n\n\n\n\n\n\ntype BaseContainer interface {\n\tID() string\n\n\tStatus() (Status, error)\n\n\tState() (*State, error)\n\n\tConfig() configs.Config\n\n\tProcesses() ([]int, error)\n\n\tStats() (*Stats, error)\n\n\tSet(config configs.Config) error\n\n\tStart(process *Process) (err error)\n\n\tRun(process *Process) (err error)\n\n\tDestroy() error\n\n\tSignal(s os.Signal, all bool) error\n\n\tExec() error\n}\n\nfunc (s Status) String() string ", "output": "{\n\tswitch s {\n\tcase Created:\n\t\treturn \"created\"\n\tcase Running:\n\t\treturn \"running\"\n\tcase Pausing:\n\t\treturn \"pausing\"\n\tcase Paused:\n\t\treturn \"paused\"\n\tcase Stopped:\n\t\treturn \"stopped\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\n\nfunc main() {\n\tadd := number(1)\n\tfmt.Println(\"add():\", add())\n\tfmt.Println(\"add():\", add())\n\n\tnumber2 := func(x int) func() int {\n\t\treturn func() int {\n\t\t\tx++\n\t\t\treturn x\n\t\t}\n\t}\n\n\tadd2 := number2(1)\n\tfmt.Println(\"add2():\", add2())\n\tfmt.Println(\"add2():\", add2())\n}\n\nfunc number(x int) func() int ", "output": "{\n\treturn func() int {\n\t\tx++\n\t\treturn x\n\t}\n}"} {"input": "package sysinfo\n\nimport (\n\t\"runtime\"\n\t\"unsafe\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\n\n\n\n\n\n\n\n\nfunc NumCPU() int {\n\tif ncpu := numCPU(); ncpu > 0 {\n\t\treturn ncpu\n\t}\n\treturn runtime.NumCPU()\n}\n\nfunc numCPU() int ", "output": "{\n\tpid, _, _ := unix.RawSyscall(unix.SYS_GETPID, 0, 0, 0)\n\n\tvar mask [1024 / 64]uintptr\n\t_, _, err := unix.RawSyscall(unix.SYS_SCHED_GETAFFINITY, pid, uintptr(len(mask)*8), uintptr(unsafe.Pointer(&mask[0])))\n\tif err != 0 {\n\t\treturn 0\n\t}\n\n\tncpu := 0\n\tfor _, e := range mask {\n\t\tif e == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tncpu += int(popcnt(uint64(e)))\n\t}\n\treturn ncpu\n}"} {"input": "package aerospike\n\ntype operateCommand struct {\n\t*readCommand\n\n\tpolicy *WritePolicy\n\toperations []*Operation\n}\n\nfunc newOperateCommand(cluster *Cluster, policy *WritePolicy, key *Key, operations []*Operation) *operateCommand {\n\treturn &operateCommand{\n\t\treadCommand: newReadCommand(cluster, policy, key, nil),\n\t\tpolicy: policy,\n\t\toperations: operations,\n\t}\n}\n\n\n\nfunc (cmd *operateCommand) Execute() error {\n\treturn cmd.execute(cmd)\n}\n\nfunc (cmd *operateCommand) writeBuffer(ifc command) error ", "output": "{\n\treturn cmd.setOperate(cmd.policy, cmd.key, cmd.operations)\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\n\n\n\n\n\n\n\ntype InstanceReservationShapeConfigDetails struct {\n\n\tOcpus *float32 `mandatory:\"false\" json:\"ocpus\"`\n\n\tMemoryInGBs *float32 `mandatory:\"false\" json:\"memoryInGBs\"`\n}\n\n\n\nfunc (m InstanceReservationShapeConfigDetails) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package daemon\n\nimport (\n\t\"testing\"\n\n\t\"github.com/docker/docker/pkg/signal\"\n\t\"github.com/docker/docker/runconfig\"\n)\n\nfunc TestGetFullName(t *testing.T) {\n\tname, err := GetFullContainerName(\"testing\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif name != \"/testing\" {\n\t\tt.Fatalf(\"Expected /testing got %s\", name)\n\t}\n\tif _, err := GetFullContainerName(\"\"); err == nil {\n\t\tt.Fatal(\"Error should not be nil\")\n\t}\n}\n\nfunc TestValidContainerNames(t *testing.T) {\n\tinvalidNames := []string{\"-rm\", \"&sdfsfd\", \"safd%sd\"}\n\tvalidNames := []string{\"word-word\", \"word_word\", \"1weoid\"}\n\n\tfor _, name := range invalidNames {\n\t\tif validContainerNamePattern.MatchString(name) {\n\t\t\tt.Fatalf(\"%q is not a valid container name and was returned as valid.\", name)\n\t\t}\n\t}\n\n\tfor _, name := range validNames {\n\t\tif !validContainerNamePattern.MatchString(name) {\n\t\t\tt.Fatalf(\"%q is a valid container name and was returned as invalid.\", name)\n\t\t}\n\t}\n}\n\n\n\nfunc TestContainerStopSignal(t *testing.T) ", "output": "{\n\tc := &Container{\n\t\tCommonContainer: CommonContainer{\n\t\t\tConfig: &runconfig.Config{},\n\t\t},\n\t}\n\n\tdef, err := signal.ParseSignal(signal.DefaultStopSignal)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\ts := c.stopSignal()\n\tif s != int(def) {\n\t\tt.Fatalf(\"Expected %v, got %v\", def, s)\n\t}\n\n\tc = &Container{\n\t\tCommonContainer: CommonContainer{\n\t\t\tConfig: &runconfig.Config{StopSignal: \"SIGKILL\"},\n\t\t},\n\t}\n\ts = c.stopSignal()\n\tif s != 9 {\n\t\tt.Fatalf(\"Expected 9, got %v\", s)\n\t}\n}"} {"input": "package utils\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestParse(t *testing.T) ", "output": "{\n\tdata := map[string]interface{}{\n\t\t\"Foo\": \"Bar\",\n\t}\n\tbuf, err := NewParseTmpl(\"Foo={{.Foo}}\").Parse(data)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tt.Log(buf.String())\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc parseM3uPlaylist(data string) (songs []*SongRecord) {\n\tvar songIndex int\n\tvar newSong *SongRecord\n\n\tfor _, line := range strings.Split(data, \"\\n\") {\n\t\tline = strings.TrimSpace(line)\n\t\tif !isSongRecord(line) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif isSongRecordHeader(line) {\n\t\t\tsongIndex += 1\n\t\t\tnewSong = extractSongRecordHeader(songIndex, line)\n\t\t} else {\n\t\t\tnewSong.setFilepath(line)\n\t\t\tsongs = append(songs, newSong)\n\t\t}\n\t}\n\treturn songs\n}\n\nfunc isSongRecord(input string) bool {\n\treturn input != \"\" && !strings.HasPrefix(input, \"#EXTM3U\")\n}\n\n\n\nfunc extractSongRecordHeader(index int, line string) (s *SongRecord) {\n\tvar title, duration string\n\tif i := strings.IndexAny(line, \"-0123456789\"); i > -1 {\n\t\tconst separator = \",\"\n\t\tline = line[i:]\n\t\tif j := strings.Index(line, separator); j > -1 {\n\t\t\ttitle = line[j+len(separator):]\n\t\t\tduration = line[:j]\n\t\t}\n\t}\n\n\treturn NewSongRecord(index, \"\", title, duration)\n}\n\nfunc writePlsPlaylist(songs []*SongRecord) error {\n\tfmt.Println(\"[playlist]\")\n\tfor _, song := range songs {\n\t\tif pls, err := song.ToPls(); err != nil {\n\t\t\treturn err\n\t\t} else {\n\t\t\tfmt.Printf(pls)\n\t\t}\n\t}\n\tfmt.Printf(\"NumberOfEntries=%d\\nVersion=2\\n\", len(songs))\n\treturn nil\n}\n\nfunc isSongRecordHeader(input string) bool ", "output": "{\n\treturn strings.HasPrefix(input, \"#EXTINF:\")\n}"} {"input": "package common\n\nimport (\n\t\"github.com/cihangir/gene/utils\"\n)\n\n\ntype Output struct {\n\tContent []byte\n\tPath string\n\tDoNotFormat bool\n\tDoNotOverride bool\n}\n\n\n\n\nfunc WriteOutput(output []Output) error ", "output": "{\n\tfor _, file := range output {\n\t\tif len(file.Content) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif file.DoNotOverride {\n\t\t\tif _, err := utils.ReadFile(file.Path); err == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tif file.DoNotFormat {\n\t\t\tif err := utils.Write(file.Path, file.Content); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tif err := utils.WriteFormattedFile(file.Path, file.Content); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package zygo\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\n\n\n\nfunc MsgpackMapMacro(env *Glisp, name string,\n\targs []Sexp) (Sexp, error) {\n\n\tif len(args) < 1 {\n\t\treturn SexpNull, fmt.Errorf(\"struct-name is missing. use: \" +\n\t\t\t\"(msgpack-map struct-name)\\n\")\n\t}\n\n\treturn MakeList([]Sexp{\n\t\tenv.MakeSymbol(\"def\"),\n\t\targs[0],\n\t\tMakeList([]Sexp{\n\t\t\tenv.MakeSymbol(\"quote\"),\n\t\t\tenv.MakeSymbol(\"msgmap\"),\n\t\t\tSexpStr{S: args[0].(SexpSymbol).name},\n\t\t}),\n\t}), nil\n}\n\nfunc DeclareMsgpackMapFunction(env *Glisp, name string, args []Sexp) (Sexp, error) {\n\tif len(args) != 1 {\n\t\treturn SexpNull, WrongNargs\n\t}\n\n\tswitch t := args[0].(type) {\n\tcase SexpStr:\n\t\treturn t, nil\n\t}\n\treturn SexpNull, errors.New(\"argument must be string: the name of the new msgpack-map constructor function to create\")\n}\n\nfunc (env *Glisp) ImportMsgpackMap() ", "output": "{\n\tenv.AddMacro(\"msgpack-map\", MsgpackMapMacro)\n\tenv.AddFunction(\"declare-msgpack-map\", DeclareMsgpackMapFunction)\n}"} {"input": "package main\n\nimport \"fmt\"\n\ntype Bitcoin int\n\ntype Wallet struct {\n\tbalance Bitcoin\n}\n\nfunc (b Bitcoin) String() string {\n\treturn fmt.Sprintf(\"%d BTC\", b)\n}\nfunc (w *Wallet) Deposit(amount Bitcoin) {\n\tw.balance += amount\n}\n\n\n\nfunc (w *Wallet) Withdraw(amount Bitcoin) {\n\tw.balance -= amount\n}\n\nfunc main() {\n\tname := \"sss\"\n\tfmt.Println(name)\n}\n\nfunc (w *Wallet) Balance() Bitcoin ", "output": "{\n\treturn w.balance\n}"} {"input": "package builders\n\nimport (\n\t\"time\"\n\n\t\"github.com/docker/docker/api/types\"\n)\n\n\n\nfunc Container(name string, builders ...func(container *types.Container)) *types.Container {\n\tcontainer := &types.Container{\n\t\tID: \"container_id\",\n\t\tNames: []string{\"/\" + name},\n\t\tCommand: \"top\",\n\t\tImage: \"busybox:latest\",\n\t\tStatus: \"Up 1 second\",\n\t\tCreated: time.Now().Unix(),\n\t}\n\n\tfor _, builder := range builders {\n\t\tbuilder(container)\n\t}\n\n\treturn container\n}\n\n\nfunc WithLabel(key, value string) func(*types.Container) {\n\treturn func(c *types.Container) {\n\t\tif c.Labels == nil {\n\t\t\tc.Labels = map[string]string{}\n\t\t}\n\t\tc.Labels[key] = value\n\t}\n}\n\n\n\n\n\nfunc WithPort(privateport, publicport uint16, builders ...func(*types.Port)) func(*types.Container) {\n\treturn func(c *types.Container) {\n\t\tif c.Ports == nil {\n\t\t\tc.Ports = []types.Port{}\n\t\t}\n\t\tport := &types.Port{\n\t\t\tPrivatePort: privateport,\n\t\t\tPublicPort: publicport,\n\t\t}\n\t\tfor _, builder := range builders {\n\t\t\tbuilder(port)\n\t\t}\n\t\tc.Ports = append(c.Ports, *port)\n\t}\n}\n\n\nfunc IP(ip string) func(*types.Port) {\n\treturn func(p *types.Port) {\n\t\tp.IP = ip\n\t}\n}\n\n\nfunc TCP(p *types.Port) {\n\tp.Type = \"tcp\"\n}\n\n\nfunc UDP(p *types.Port) {\n\tp.Type = \"udp\"\n}\n\nfunc WithName(name string) func(*types.Container) ", "output": "{\n\treturn func(c *types.Container) {\n\t\tc.Names = append(c.Names, \"/\"+name)\n\t}\n}"} {"input": "package jsonutil\n\nimport (\n\t\"github.com/buger/jsonparser\"\n\t\"strconv\"\n)\n\nfunc GetString(data []byte, keys ...string) (string, error) {\n\treturn jsonparser.GetString(data, keys...)\n}\n\n\n\nfunc GetFloat(data []byte, keys ...string) (float64, error) {\n\treturn jsonparser.GetFloat(data, keys...)\n}\n\nfunc MustGetFloat(data []byte, keys ...string) float64 {\n\tf, err := GetFloat(data, keys...)\n\tif err != nil {\n\t\treturn 0.0\n\t}\n\treturn f\n}\n\nfunc GetInt(data []byte, keys ...string) (int64, error) {\n\treturn jsonparser.GetInt(data, keys...)\n}\n\nfunc MustGetInt(data []byte, keys ...string) int64 {\n\ti, err := GetInt(data, keys...)\n\tif err != nil {\n\t\tif s := MustGetString(data, keys...); len(s) == 0 {\n\t\t\treturn 0\n\t\t} else if i, err = strconv.ParseInt(s, 10, 64); err != nil {\n\t\t\treturn 0\n\t\t}\n\t}\n\treturn i\n}\n\nfunc GetBoolean(data []byte, keys ...string) (bool, error) {\n\treturn jsonparser.GetBoolean(data, keys...)\n}\n\nfunc MustGetBoolean(data []byte, keys ...string) bool {\n\tb, err := GetBoolean(data, keys...)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn b\n}\n\nfunc MustGetString(data []byte, keys ...string) string ", "output": "{\n\ts, err := GetString(data, keys...)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn s\n}"} {"input": "package crypto\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\nfunc BenchmarkRandom(b *testing.B) {\n\tfor index := 0; index < b.N; index++ {\n\t\tRandom(32)\n\t}\n}\n\nfunc TestEncrypt(t *testing.T) {\n\tsrc := \"I'mAPlainSecret\"\n\tos.Setenv(\"SECRET_KEY\", \"secretkey@example.com\")\n\tConvey(\"auth.Encrypt Test\", t, func() {\n\t\tsecret := Encrypt(src)\n\t\tSo(len(secret), ShouldEqual, 60)\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t\tSo(secret, ShouldNotEqual, Encrypt(src))\n\t})\n}\n\nfunc TestVerify(t *testing.T) {\n\tsrc := \"I'mAPlainSecret\"\n\tConvey(\"auth.Verify Test\", t, func() {\n\t\tfor index := 0; index < 10; index++ {\n\t\t\tsecret := Encrypt(src)\n\t\t\tSo(Verify(src, secret), ShouldBeTrue)\n\t\t}\n\t})\n}\n\nfunc BenchmarkMixin(b *testing.B) {\n\tsrc := \"I'mAPlainSecret\"\n\tos.Setenv(\"SECRET_KEY\", \"secretkey@example.com\")\n\tfor index := 0; index < b.N; index++ {\n\t\tmixin(src)\n\t}\n}\n\n\n\nfunc BenchmarkVerify(b *testing.B) {\n\tsrc := \"I'mAPlainSecret\"\n\tos.Setenv(\"SECRET_KEY\", \"secretkey@example.com\")\n\tsecret := Encrypt(src)\n\tfor index := 0; index < b.N; index++ {\n\t\tVerify(src, secret)\n\t}\n}\n\nfunc BenchmarkEncrypt(b *testing.B) ", "output": "{\n\tsrc := \"I'mAPlainSecret\"\n\tos.Setenv(\"SECRET_KEY\", \"secretkey@example.com\")\n\tfor index := 0; index < b.N; index++ {\n\t\tEncrypt(src)\n\t}\n}"} {"input": "package rorm\n\ntype rorm struct {\n\tredisQuerier *RedisQuerier\n}\n\n\n\nfunc (r *rorm) QueryHash(key string) HashQuerySeter {\n\treturn &hashQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\nfunc (r *rorm) QueryKeys(key string) KeysQuerySeter {\n\treturn &keysQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\nfunc (r *rorm) QueryString(key string) StringQuerySeter {\n\treturn &stringQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\nfunc (r *rorm) QueryZSet(key string) ZSetQuerySeter {\n\treturn &zsetQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\nfunc (r *rorm) QuerySet(key string) SetQuerySeter {\n\treturn &setQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\nfunc (r rorm) Using(alias string) ROrmer {\n\tclient, ok := redisRegistry[alias]\n\tif !ok {\n\t\tpanic(\"using reids '\" + alias + \"' not exist.\")\n\t}\n\tr.redisQuerier = &RedisQuerier{\n\t\tClient: client,\n\t}\n\treturn &r\n}\n\nfunc (r *rorm) Querier() Querier {\n\treturn r.redisQuerier\n}\n\nfunc NewROrm() ROrmer ", "output": "{\n\treturn new(rorm).Using(\"default\")\n}"} {"input": "package router\n\n\n\n\nimport (\n\t\"github.com/weaveworks/mesh\"\n)\n\n\n\ntype AWSVPCConnection struct {\n\testablishedChan chan struct{}\n\terrorChan chan error\n}\n\nfunc (conn *AWSVPCConnection) Confirm() {\n\tclose(conn.establishedChan)\n}\n\nfunc (conn *AWSVPCConnection) EstablishedChannel() <-chan struct{} {\n\treturn conn.establishedChan\n}\n\n\n\nfunc (conn *AWSVPCConnection) Stop() {}\n\nfunc (conn *AWSVPCConnection) ControlMessage(tag byte, msg []byte) {\n}\n\nfunc (conn *AWSVPCConnection) DisplayName() string {\n\treturn \"awsvpc\"\n}\n\n\n\nfunc (conn *AWSVPCConnection) Forward(key ForwardPacketKey) FlowOp {\n\treturn DiscardingFlowOp{}\n}\n\ntype AWSVPC struct{}\n\nfunc NewAWSVPC() AWSVPC {\n\treturn AWSVPC{}\n}\n\n\n\nfunc (vpc AWSVPC) AddFeaturesTo(features map[string]string) {}\n\nfunc (vpc AWSVPC) PrepareConnection(params mesh.OverlayConnectionParams) (mesh.OverlayConnection, error) {\n\tconn := &AWSVPCConnection{\n\t\testablishedChan: make(chan struct{}),\n\t\terrorChan: make(chan error, 1),\n\t}\n\treturn conn, nil\n}\n\nfunc (vpc AWSVPC) Diagnostics() interface{} {\n\treturn nil\n}\n\n\n\nfunc (vpc AWSVPC) InvalidateRoutes() {}\n\nfunc (vpc AWSVPC) InvalidateShortIDs() {}\n\nfunc (vpc AWSVPC) StartConsumingPackets(localPeer *mesh.Peer, peers *mesh.Peers, consumer OverlayConsumer) error {\n\treturn nil\n}\n\nfunc (conn *AWSVPCConnection) ErrorChannel() <-chan error ", "output": "{\n\treturn conn.errorChan\n}"} {"input": "package crate_test\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\t_ \"github.com/herenow/go-crate\"\n\t\"log\"\n)\n\n\n\nfunc ExampleCrateDriver_Query() {\n\tdb, err := sql.Open(\"crate\", \"http://localhost:4200\")\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\trows, err := db.Query(\"SELECT name FROM sys.cluster\")\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar name string\n\n\t\tif err := rows.Scan(&name); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"%s\\n\", name)\n\t}\n\n\tif err := rows.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc ExampleCrateDrive_Open() ", "output": "{\n\t_, err := sql.Open(\"crate\", \"http://localhost:4200\")\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}"} {"input": "package bot\n\nimport (\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/graffic/wanon/telegram\"\n\n\t\"gopkg.in/yaml.v2\"\n)\n\n\ntype ConfService struct {\n\tbytes []byte\n}\n\n\nfunc LoadConf(fileName string) (*ConfService, error) {\n\tconf := new(ConfService)\n\n\tfile, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn conf, err\n\t}\n\n\tconf.bytes, err = ioutil.ReadAll(file)\n\tif err != nil {\n\t\treturn conf, err\n\t}\n\n\treturn conf, nil\n}\n\n\n\nfunc (service *ConfService) Get(in interface{}) error {\n\treturn yaml.Unmarshal(service.bytes, in)\n}\n\n\n\nfunc createAPI(conf *ConfService) (telegram.API, error) ", "output": "{\n\tvar apiConf telegram.Configuration\n\tconf.Get(&apiConf)\n\tapi := telegram.NewAPI(&http.Client{Timeout: time.Second * 15}, apiConf)\n\tresult, err := api.GetMe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Info(\"%s online\", result.Username)\n\n\treturn api, nil\n}"} {"input": "package k1\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"os/exec\"\n\t\"strings\"\n\n\t\"github.com/songgao/water\"\n)\n\nfunc execCommand(name, sargs string) error {\n\targs := strings.Split(sargs, \" \")\n\tcmd := exec.Command(name, args...)\n\tlogger.Infof(\"exec command: %s %s\", name, sargs)\n\treturn cmd.Run()\n}\n\nfunc initTun(tun string, ipNet *net.IPNet, mtu int) error {\n\tip := ipNet.IP\n\tmaskIP := net.IP(ipNet.Mask)\n\tsargs := fmt.Sprintf(\"%s %s %s mtu %d netmask %s up\", tun, ip.String(), ip.String(), mtu, maskIP.String())\n\tif err := execCommand(\"ifconfig\", sargs); err != nil {\n\t\treturn err\n\t}\n\treturn addRoute(tun, ipNet)\n}\n\n\n\nfunc createTun(ip net.IP, mask net.IPMask) (*water.Interface, error) {\n\tifce, err := water.New(water.Config{\n\t\tDeviceType: water.TUN,\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogger.Infof(\"create %s\", ifce.Name())\n\n\tipNet := &net.IPNet{\n\t\tIP: ip,\n\t\tMask: mask,\n\t}\n\n\tif err := initTun(ifce.Name(), ipNet, MTU); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ifce, nil\n}\n\n\nfunc fixTunIP(ip net.IP) net.IP {\n\treturn net.IPv4zero\n}\n\nfunc addRoute(tun string, subnet *net.IPNet) error ", "output": "{\n\tip := subnet.IP\n\tmaskIP := net.IP(subnet.Mask)\n\tsargs := fmt.Sprintf(\"-n add -net %s -netmask %s -interface %s\", ip.String(), maskIP.String(), tun)\n\treturn execCommand(\"route\", sargs)\n}"} {"input": "package exchange\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\ntype ValidPeriod struct {\n\tdate time.Time\n\texpires time.Time\n}\n\n\n\n\n\n\n\nfunc NewValidPeriodWithLifetime(date time.Time, lifetime time.Duration) ValidPeriod {\n\treturn ValidPeriod{date, date.Add(lifetime)}\n}\n\n\nfunc (vp ValidPeriod) Date() time.Time {\n\treturn vp.date\n}\n\n\nfunc (vp ValidPeriod) Expires() time.Time {\n\treturn vp.expires\n}\n\n\nfunc (vp ValidPeriod) Lifetime() time.Duration {\n\treturn vp.expires.Sub(vp.date)\n}\n\n\n\n\nfunc (vp ValidPeriod) Contains(t time.Time) bool {\n\treturn !t.Before(vp.date) && !t.After(vp.expires)\n}\n\n\nfunc (vp ValidPeriod) String() string {\n\treturn fmt.Sprintf(\"[%s] to [%s]\", vp.date, vp.expires)\n}\n\nfunc NewValidPeriod(date, expires time.Time) ValidPeriod ", "output": "{\n\treturn ValidPeriod{date, expires}\n}"} {"input": "package msgraph\n\nimport \"context\"\n\n\ntype FieldValueSetRequestBuilder struct{ BaseRequestBuilder }\n\n\n\n\n\ntype FieldValueSetRequest struct{ BaseRequest }\n\n\nfunc (r *FieldValueSetRequest) Get(ctx context.Context) (resObj *FieldValueSet, err error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\terr = r.JSONRequest(ctx, \"GET\", query, nil, &resObj)\n\treturn\n}\n\n\nfunc (r *FieldValueSetRequest) Update(ctx context.Context, reqObj *FieldValueSet) error {\n\treturn r.JSONRequest(ctx, \"PATCH\", \"\", reqObj, nil)\n}\n\n\nfunc (r *FieldValueSetRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}\n\nfunc (b *FieldValueSetRequestBuilder) Request() *FieldValueSetRequest ", "output": "{\n\treturn &FieldValueSetRequest{\n\t\tBaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client},\n\t}\n}"} {"input": "package travel\n\nimport (\n\t\"os\"\n\n\t\"github.com/akerl/speculate/v2/creds\"\n)\n\nfunc clearEnvironment() error {\n\tfor varName := range creds.Translations[\"envvar\"] {\n\t\tlogger.InfoMsgf(\"Unsetting env var: %s\", varName)\n\t\terr := os.Unsetenv(varName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc stringInSlice(list []string, key string) bool {\n\tfor _, item := range list {\n\t\tif item == key {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc sliceUnion(a []string, b []string) []string {\n\tvar res []string\n\tfor _, item := range a {\n\t\tif stringInSlice(b, item) {\n\t\t\tres = append(res, item)\n\t\t}\n\t}\n\treturn res\n}\n\ntype attrFunc func(Path) string\n\nfunc uniquePathAttributes(paths []Path, af attrFunc) []string {\n\ttmpMap := map[string]bool{}\n\tfor _, item := range paths {\n\t\tattr := af(item)\n\t\ttmpMap[attr] = true\n\t}\n\ttmpList := []string{}\n\tfor item := range tmpMap {\n\t\ttmpList = append(tmpList, item)\n\t}\n\treturn tmpList\n}\n\n\n\nfunc filterPathsByAttribute(paths []Path, match string, af attrFunc) []Path ", "output": "{\n\tfilteredPaths := []Path{}\n\tfor _, item := range paths {\n\t\tif af(item) == match {\n\t\t\tfilteredPaths = append(filteredPaths, item)\n\t\t}\n\t}\n\treturn filteredPaths\n}"} {"input": "package archive\n\n\n\nimport (\n\t\"os\"\n\n\t\"github.com/martinlindhe/formats/parse\"\n)\n\n\n\n\nfunc isVDI(b []byte) bool {\n\n\ts := string(b[0:40])\n\treturn s == \"<<< Oracle VM VirtualBox Disk Image >>>\"+\"\\n\"\n}\n\nfunc parseVDI(file *os.File, pl parse.ParsedLayout) (*parse.ParsedLayout, error) {\n\n\tpos := int64(0)\n\tpl.FileKind = parse.Archive\n\tpl.Layout = []parse.Layout{{\n\t\tOffset: pos,\n\t\tLength: 40,\n\t\tInfo: \"header\",\n\t\tType: parse.Group,\n\t\tChilds: []parse.Layout{\n\t\t\t{Offset: pos, Length: 40, Info: \"magic\", Type: parse.ASCII},\n\t\t}}}\n\n\treturn &pl, nil\n}\n\nfunc VDI(c *parse.Checker) (*parse.ParsedLayout, error) ", "output": "{\n\n\tif !isVDI(c.Header) {\n\t\treturn nil, nil\n\t}\n\treturn parseVDI(c.File, c.ParsedLayout)\n}"} {"input": "package factory\n\nimport (\n\t\"encoding/json\"\n\t\"path/filepath\"\n\n\t\"github.com/golang/glog\"\n\t\"github.com/hyperhq/runv/factory/base\"\n\t\"github.com/hyperhq/runv/factory/cache\"\n\t\"github.com/hyperhq/runv/factory/direct\"\n\t\"github.com/hyperhq/runv/factory/multi\"\n\t\"github.com/hyperhq/runv/factory/single\"\n\t\"github.com/hyperhq/runv/factory/template\"\n\t\"github.com/hyperhq/runv/hypervisor\"\n)\n\ntype Factory interface {\n\tGetVm(cpu, mem int) (*hypervisor.Vm, error)\n\tCloseFactory()\n}\n\ntype FactoryConfig struct {\n\tCache int `json:\"cache\"`\n\tTemplate bool `json:\"template\"`\n\tCpu int `json:\"cpu\"`\n\tMemory int `json:\"memory\"`\n}\n\n\n\n\n\nfunc NewFromPolicy(bootConfig hypervisor.BootConfig, policy string) Factory {\n\tvar configs []FactoryConfig\n\tjsonString := \"[\" + policy + \"]\"\n\terr := json.Unmarshal([]byte(jsonString), &configs)\n\tif err != nil && policy != \"none\" {\n\t\tglog.Errorf(\"Incorrect policy: %s\", policy)\n\t}\n\treturn NewFromConfigs(bootConfig, configs)\n}\n\nfunc NewFromConfigs(bootConfig hypervisor.BootConfig, configs []FactoryConfig) Factory ", "output": "{\n\tbases := make([]base.Factory, len(configs))\n\tfor i, c := range configs {\n\t\tvar b base.Factory\n\t\tboot := bootConfig\n\t\tboot.CPU = c.Cpu\n\t\tboot.Memory = c.Memory\n\t\tif c.Template {\n\t\t\tb = template.New(filepath.Join(hypervisor.BaseDir, \"template\"), boot)\n\t\t} else {\n\t\t\tb = direct.New(boot)\n\t\t}\n\t\tbases[i] = cache.New(c.Cache, b)\n\t}\n\n\tif len(bases) == 0 {\n\t\treturn single.Dummy(bootConfig)\n\t} else if len(bases) == 1 {\n\t\treturn single.New(bases[0])\n\t} else {\n\t\treturn multi.New(bases)\n\t}\n}"} {"input": "package fakevtworkerclient\n\nimport (\n\t\"time\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/youtube/vitess/go/vt/logutil\"\n\t\"github.com/youtube/vitess/go/vt/vtctl/fakevtctlclient\"\n\t\"github.com/youtube/vitess/go/vt/worker/vtworkerclient\"\n)\n\n\n\n\ntype FakeVtworkerClient struct {\n\t*fakevtctlclient.FakeLoggerEventStreamingClient\n}\n\n\nfunc NewFakeVtworkerClient() *FakeVtworkerClient {\n\treturn &FakeVtworkerClient{fakevtctlclient.NewFakeLoggerEventStreamingClient()}\n}\n\n\n\nfunc (f *FakeVtworkerClient) FakeVtworkerClientFactory(addr string, dialTimeout time.Duration) (vtworkerclient.Client, error) {\n\treturn &perAddrFakeVtworkerClient{f, addr}, nil\n}\n\n\n\ntype perAddrFakeVtworkerClient struct {\n\t*FakeVtworkerClient\n\taddr string\n}\n\n\n\n\n\nfunc (c *perAddrFakeVtworkerClient) Close() {}\n\nfunc (c *perAddrFakeVtworkerClient) ExecuteVtworkerCommand(ctx context.Context, args []string) (logutil.EventStream, error) ", "output": "{\n\treturn c.FakeLoggerEventStreamingClient.StreamResult(c.addr, args)\n}"} {"input": "package files\n\nimport (\n\tu \"github.com/araddon/gou\"\n\t\"github.com/lytics/cloudstorage\"\n\n\t\"github.com/araddon/qlbridge/datasource\"\n\t\"github.com/araddon/qlbridge/schema\"\n)\n\nvar (\n\t_ FileHandler = (*csvFiles)(nil)\n)\n\nfunc init() {\n\tRegisterFileHandler(\"csv\", &csvFiles{})\n}\n\n\ntype csvFiles struct {\n\tappendcols []string\n}\n\n\nfunc (m *csvFiles) FileAppendColumns() []string { return m.appendcols }\nfunc (m *csvFiles) File(path string, obj cloudstorage.Object) *FileInfo {\n\treturn FileInfoFromCloudObject(path, obj)\n}\nfunc (m *csvFiles) Scanner(store cloudstorage.StoreReader, fr *FileReader) (schema.ConnScanner, error) {\n\tcsv, err := datasource.NewCsvSource(fr.Table, 0, fr.F, fr.Exit)\n\tif err != nil {\n\t\tu.Errorf(\"Could not open file for csv reading %v\", err)\n\t\treturn nil, err\n\t}\n\treturn csv, nil\n}\n\nfunc (m *csvFiles) Init(store FileStore, ss *schema.Schema) error ", "output": "{ return nil }"} {"input": "package dynamo\n\nimport (\n\t\"errors\"\n\n\t\"golang.org/x/crypto/acme/autocert\"\n)\n\n\ntype Provider struct {\n\tclient *client\n}\n\n\nfunc NewProvider() *Provider {\n\treturn new(Provider)\n}\n\n\nfunc (p *Provider) Name() string {\n\treturn \"dynamodb\"\n}\n\n\nfunc (p *Provider) Configure(config map[string]interface{}) (err error) {\n\tconst prefix = \"unable to configure DynamoDB provider\"\n\tif config == nil {\n\t\treturn errors.New(prefix + \", no configuration provided\")\n\t}\n\n\tregion := get(config, \"region\", \"\")\n\tif region == \"\" {\n\t\treturn errors.New(prefix + \", no AWS Region was specified\")\n\t}\n\n\ttable := get(config, \"table\", \"\")\n\tif table == \"\" {\n\t\treturn errors.New(prefix + \", no Table Name was specified\")\n\t}\n\n\tkeyColumn := get(config, \"keyColumn\", \"key\")\n\tvalColumn := get(config, \"valueColumn\", \"value\")\n\n\tif p.client, err = newClient(region, table, keyColumn, valColumn); err == nil {\n\t\tif _, err := p.client.Get(\"testkey\"); err == nil && err == errKeyNotFound {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn err\n}\n\n\n\n\n\nfunc (p *Provider) GetCache() (autocert.Cache, bool) {\n\tif p.client != nil {\n\t\treturn newCache(p.client), true\n\t}\n\n\treturn nil, false\n}\n\n\nfunc get(config map[string]interface{}, key, defaultValue string) string {\n\tif v, ok := config[key]; ok {\n\t\tif s, ok := v.(string); ok {\n\t\t\treturn s\n\t\t}\n\t}\n\treturn defaultValue\n}\n\nfunc (p *Provider) GetSecret(secretName string) (string, bool) ", "output": "{\n\tif p.client != nil {\n\t\tif value, err := p.client.Get(secretName); err == nil {\n\t\t\treturn value, true\n\t\t}\n\t}\n\n\treturn \"\", false\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"bytes\"\n)\n\n\n\nfunc revocationdump(pos int) ", "output": "{\n\tp := make([]byte, blocksize)\n\t_, err := r.Seek(int64(pos), 0)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif readblock(r, p) == false {\n\t\treturn\n\t}\n\trr := bytes.NewReader(p)\n\th, b := getblock(rr)\n\tif err, ok := b.(error); ok && err != nil {\n\t\tpanic(err)\n\t}\n\tif h == nil || h.BlockType != RevocationRecordsBlock {\n\t\tpanic(\"block at pos does not represent a revocation record\")\n\t}\n\trv := b.(*RevocationRecord)\n\tblocks := rv.ReadAll(rr, *u64)\n\tfor _, block := range blocks {\n\t\tfmt.Printf(\"0x%08X\\n\", block - *first)\n\t}\n}"} {"input": "package tmpl\n\nimport (\n\t\"fmt\"\n\t\"html/template\"\n\t\"net/http\"\n)\n\n\ntype Page struct {\n\tTitle string\n\tBackLink string\n}\n\n\ntype Template struct {\n\ttemplates map[string]*template.Template\n\ttemplateData map[string]map[string]interface{}\n\ttemplateFilepath string\n}\n\n\nfunc New(templateFilepath string) *Template {\n\treturn &Template{\n\t\ttemplateFilepath: templateFilepath,\n\t\ttemplates: make(map[string]*template.Template),\n\t\ttemplateData: make(map[string]map[string]interface{}),\n\t}\n}\n\n\n\nfunc (self *Template) AddTemplate(name string, templates ...string) {\n\tif len(templates) > 0 {\n\t\tfor i := 0; i < len(templates); i++ {\n\t\t\ttemplates[i] = self.templateFilepath + \"templates/\" + templates[i] + \".tpl\"\n\t\t}\n\t\tself.templates[name] = template.Must(template.ParseFiles(templates...))\n\t}\n\n\tself.templateData[name] = make(map[string]interface{})\n}\n\n\n\n\n\n\n\n\nfunc (self *Template) RenderPage(w http.ResponseWriter, tmpl string, p *Page) {\n\tself.AddDataToTemplate(tmpl, \"Page\", p)\n\n\terr := self.templates[tmpl].Execute(w, self.templateData[tmpl])\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}\n\nfunc (self *Template) AddDataToTemplate(template, data_id string, data interface{}) error ", "output": "{\n\t_, ok := self.templateData[template]\n\tif !ok {\n\t\treturn fmt.Errorf(\"There is no template named '%s' registered.\", template)\n\t}\n\n\tself.templateData[template][data_id] = data\n\n\treturn nil\n}"} {"input": "package logs\n\nimport (\n\t\"io\"\n\n\t\"github.com/cloudfoundry/dropsonde/log_sender\"\n\t\"github.com/cloudfoundry/sonde-go/events\"\n)\n\ntype LogSender interface {\n\tSendAppLog(appID, message, sourceType, sourceInstance string) error\n\tSendAppErrorLog(appID, message, sourceType, sourceInstance string) error\n\tScanLogStream(appID, sourceType, sourceInstance string, reader io.Reader)\n\tScanErrorLogStream(appID, sourceType, sourceInstance string, reader io.Reader)\n\tLogMessage(msg []byte, msgType events.LogMessage_MessageType) log_sender.LogChainer\n}\n\nvar logSender LogSender\n\n\n\n\n\n\n\n\nfunc SendAppLog(appID, message, sourceType, sourceInstance string) error {\n\tif logSender == nil {\n\t\treturn nil\n\t}\n\treturn logSender.SendAppLog(appID, message, sourceType, sourceInstance)\n}\n\n\n\n\nfunc SendAppErrorLog(appID, message, sourceType, sourceInstance string) error {\n\tif logSender == nil {\n\t\treturn nil\n\t}\n\treturn logSender.SendAppErrorLog(appID, message, sourceType, sourceInstance)\n}\n\n\n\nfunc ScanLogStream(appID, sourceType, sourceInstance string, reader io.Reader) {\n\tif logSender == nil {\n\t\treturn\n\t}\n\tlogSender.ScanLogStream(appID, sourceType, sourceInstance, reader)\n}\n\n\n\nfunc ScanErrorLogStream(appID, sourceType, sourceInstance string, reader io.Reader) {\n\tif logSender == nil {\n\t\treturn\n\t}\n\tlogSender.ScanErrorLogStream(appID, sourceType, sourceInstance, reader)\n}\n\n\n\nfunc LogMessage(msg []byte, msgType events.LogMessage_MessageType) log_sender.LogChainer {\n\treturn logSender.LogMessage(msg, msgType)\n}\n\nfunc Initialize(ls LogSender) ", "output": "{\n\tlogSender = ls\n}"} {"input": "package hll\n\nimport \"testing\"\n\nfunc TestOnesTo(t *testing.T) {\n\ttestCases := []struct {\n\t\tstartPos, endPos uint\n\t\texpectResult uint64\n\t}{\n\t\t{0, 0, 1},\n\t\t{63, 63, 1 << 63},\n\t\t{2, 4, 4 + 8 + 16},\n\t\t{56, 63, 0xFF00000000000000},\n\t}\n\n\tfor i, testCase := range testCases {\n\t\tactualResult := onesFromTo(testCase.startPos, testCase.endPos)\n\t\tif testCase.expectResult != actualResult {\n\t\t\tt.Errorf(\"Case %d actual result was %v\", i, actualResult)\n\t\t}\n\t}\n}\n\n\n\nfunc TestConcat(t *testing.T) {\n\ttestCases := []struct {\n\t\tinputs []concatInput\n\t\texpectResult uint64\n\t}{\n\t\t{[]concatInput{{0xABCD, 0, 15}, {0x1234, 0, 15}}, 0xABCD1234},\n\t\t{[]concatInput{{0x0000ABCD0000, 16, 31}, {0x1234000000000000, 48, 63}}, 0xABCD1234},\n\t\t{[]concatInput{{0x1234, 0, 15}, {0x12, 0, 7}}, 0x123412},\n\t}\n\n\tfor i, testCase := range testCases {\n\t\tactualResult := concat(testCase.inputs)\n\t\tif testCase.expectResult != actualResult {\n\t\t\tt.Errorf(\"Case %d actual result was %x\", i, actualResult)\n\t\t}\n\t}\n}\n\nfunc TestExtractShift(t *testing.T) ", "output": "{\n\ttestCases := []struct {\n\t\tinput uint64\n\t\tstartPos, endPos uint\n\t\texpectResult uint64\n\t}{\n\t\t{0, 0, 63, 0},\n\t\t{0xAABBCCDD00, 8, 47, 0xAABBCCDD},\n\t\t{0xFF00000000000000, 56, 63, 0xFF},\n\t\t{0xFF, 0, 7, 0xFF},\n\t}\n\n\tfor i, testCase := range testCases {\n\t\tactualResult := extractShift(testCase.input, testCase.startPos, testCase.endPos)\n\t\tif testCase.expectResult != actualResult {\n\t\t\tt.Errorf(\"Case %d actual result was %v\", i, actualResult)\n\t\t}\n\t}\n}"} {"input": "package main\n\ntype Session struct {\n\tseq int32\n\tservers map[int32]int32 \n}\n\n\nfunc NewSession(server int) *Session {\n\ts := new(Session)\n\ts.servers = make(map[int32]int32, server)\n\ts.seq = 0\n\treturn s\n}\n\nfunc (s *Session) nextSeq() int32 {\n\ts.seq++\n\treturn s.seq\n}\n\n\nfunc (s *Session) Put(server int32) (seq int32) {\n\tseq = s.nextSeq()\n\ts.servers[seq] = server\n\treturn\n}\n\n\n\n\nfunc (s *Session) Del(seq int32) bool {\n\tdelete(s.servers, seq)\n\treturn (len(s.servers) == 0)\n}\n\nfunc (s *Session) Size() int {\n\treturn len(s.servers)\n}\n\nfunc (s *Session) Servers() (seqs []int32, servers []int32) ", "output": "{\n\tvar (\n\t\ti = len(s.servers)\n\t\tseq, server int32\n\t)\n\tseqs = make([]int32, i)\n\tservers = make([]int32, i)\n\tfor seq, server = range s.servers {\n\t\ti--\n\t\tseqs[i] = seq\n\t\tservers[i] = server\n\t}\n\treturn\n}"} {"input": "package protoreflect\n\nimport \"google.golang.org/protobuf/encoding/protowire\"\n\n\n\n\n\ntype Enum interface {\n\tDescriptor() EnumDescriptor\n\n\tType() EnumType\n\n\tNumber() EnumNumber\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype Message interface {\n\tDescriptor() MessageDescriptor\n\n\tType() MessageType\n\n\tNew() Message\n\n\tInterface() ProtoMessage\n\n\tRange(f func(FieldDescriptor, Value) bool)\n\n\tHas(FieldDescriptor) bool\n\n\tClear(FieldDescriptor)\n\n\tGet(FieldDescriptor) Value\n\n\tSet(FieldDescriptor, Value)\n\n\tMutable(FieldDescriptor) Value\n\n\tNewField(FieldDescriptor) Value\n\n\tWhichOneof(OneofDescriptor) FieldDescriptor\n\n\tGetUnknown() RawFields\n\n\tSetUnknown(RawFields)\n\n\tIsValid() bool\n\n\tProtoMethods() *methods\n}\n\n\n\n\ntype RawFields []byte\n\n\n\n\n\n\n\ntype List interface {\n\tLen() int\n\n\tGet(int) Value\n\n\tSet(int, Value)\n\n\tAppend(Value)\n\n\tAppendMutable() Value\n\n\tTruncate(int)\n\n\tNewElement() Value\n\n\tIsValid() bool\n}\n\n\n\n\n\ntype Map interface {\n\tLen() int\n\n\tRange(f func(MapKey, Value) bool)\n\n\tHas(MapKey) bool\n\n\tClear(MapKey)\n\n\tGet(MapKey) Value\n\n\tSet(MapKey, Value)\n\n\tMutable(MapKey) Value\n\n\tNewValue() Value\n\n\tIsValid() bool\n}\n\nfunc (b RawFields) IsValid() bool ", "output": "{\n\tfor len(b) > 0 {\n\t\t_, _, n := protowire.ConsumeField(b)\n\t\tif n < 0 {\n\t\t\treturn false\n\t\t}\n\t\tb = b[n:]\n\t}\n\treturn true\n}"} {"input": "package log4me\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n)\n\ntype LoggerI struct {\n\tEnabled bool\n}\n\nfunc (l LoggerI) Info(v ...interface{}) {\n\tif !l.Enabled {\n\t\treturn\n\t}\n\n\tfmt.Fprintln(ioutil.Discard, v...)\n\n}\n\nfunc (l LoggerI) String() string {\n\tif l.Enabled {\n\t\treturn \"LoggerI: Enabled\"\n\t}\n\treturn \"LoggerI: Disabled\"\n}\n\ntype LoggerF struct {\n\tEnabled bool\n}\n\ntype F func()\n\nfunc (l LoggerF) Info(f F) {\n\tif l.Enabled {\n\t\tf()\n\t}\n}\n\n\n\nfunc (l LoggerF) String() string ", "output": "{\n\tif l.Enabled {\n\t\treturn \"LoggerF: Enabled\"\n\t}\n\treturn \"LoggerF: Disabled\"\n}"} {"input": "package model\n\nimport (\n\t\"github.com/Konstantin8105/GoFea/input/element\"\n\t\"github.com/Konstantin8105/GoFea/input/material\"\n)\n\ntype materialLinearGroup struct {\n\tmaterial material.Linear\n\telementIndex element.Index\n}\n\n\ntype materialByElement []materialLinearGroup\n\nfunc (a materialByElement) Len() int { return len(a) }\n\nfunc (a materialByElement) Less(i, j int) bool { return a[i].elementIndex < a[j].elementIndex }\nfunc (a materialByElement) Equal(i, j int) bool { return a[i].elementIndex == a[j].elementIndex }\nfunc (a materialByElement) Name(i int) int { return int(a[i].elementIndex) }\n\nfunc (a materialByElement) Swap(i, j int) ", "output": "{ a[i], a[j] = a[j], a[i] }"} {"input": "package checkers\n\nimport (\n\t\"errors\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com/jkomoros/boardgame\"\n\t\"github.com/jkomoros/boardgame/base\"\n\t\"github.com/jkomoros/boardgame/moves\"\n)\n\n\n\n\ntype gameDelegate struct {\n\tbase.GameDelegate\n}\n\nvar memoizedDelegateName string\n\nfunc (g *gameDelegate) Name() string {\n\n\n\tif memoizedDelegateName == \"\" {\n\t\tpkgPath := reflect.ValueOf(g).Elem().Type().PkgPath()\n\t\tpathPieces := strings.Split(pkgPath, \"/\")\n\t\tmemoizedDelegateName = pathPieces[len(pathPieces)-1]\n\t}\n\treturn memoizedDelegateName\n}\n\nfunc (g *gameDelegate) ConfigureMoves() []boardgame.MoveConfig {\n\n\tauto := moves.NewAutoConfigurer(g)\n\n\treturn moves.Combine(\n\n\t\tmoves.Add(\n\t\t\tauto.MustConfig(new(moves.NoOp),\n\t\t\t\tmoves.WithMoveName(\"Example No Op Move\"),\n\t\t\t\tmoves.WithHelpText(\"This move is an example that is always legal and does nothing. It exists to show how to return moves and make sure 'go test' works from the beginning, but you should remove it.\"),\n\t\t\t),\n\t\t),\n\t)\n\n}\n\nfunc (g *gameDelegate) GameStateConstructor() boardgame.ConfigurableSubState {\n\treturn new(gameState)\n}\n\nfunc (g *gameDelegate) PlayerStateConstructor(index boardgame.PlayerIndex) boardgame.ConfigurableSubState {\n\treturn new(playerState)\n}\n\nfunc (g *gameDelegate) DistributeComponentToStarterStack(state boardgame.ImmutableState, c boardgame.Component) (boardgame.ImmutableStack, error) {\n\n\treturn nil, errors.New(\"Not yet implemented\")\n\n}\n\n\n\n\n\nfunc NewDelegate() boardgame.GameDelegate ", "output": "{\n\treturn &gameDelegate{}\n}"} {"input": "package target\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"testing\"\n)\n\nvar (\n\twrkdir string\n)\n\nfunc init() {\n\tlog.SetOutput(ioutil.Discard)\n\twrkdir, _ = os.Getwd()\n}\n\ntype badWriter struct {\n}\n\n\n\nfunc TestNewMake(t *testing.T) {\n\ttc, _, _ := createTestConfigs(t, nil, nil)\n\t_, err := NewMake(tc)\n\tok(t, err)\n}\n\nfunc TestMakeRun(t *testing.T) {\n\ttc, tcW, _ := createTestConfigs(t, nil, nil)\n\tm, _ := NewMake(tc)\n\terr := m.Run(\"ron:prep\")\n\tok(t, err)\n\twant := \"hello\\nprep1\\nprep2\\nprep3\\nprep4\\ngoodbye\\n\"\n\tequals(t, want, tcW.String())\n}\n\nfunc TestMakeRunErr(t *testing.T) {\n\ttc, _, _ := createTestConfigs(t, nil, nil)\n\tm, _ := NewMake(tc)\n\terr := m.Run(\"err\")\n\tif err == nil {\n\t\tt.Fatal(\"expected target not found\")\n\t}\n}\n\nfunc TestMakeRunNoTarget(t *testing.T) {\n\ttc, _, _ := createTestConfigs(t, nil, nil)\n\tm, _ := NewMake(tc)\n\terr := m.Run(\"prop\")\n\tif err == nil {\n\t\tt.Fatal(\"expected target not found\")\n\t}\n}\n\nfunc (bw badWriter) Write(p []byte) (n int, err error) ", "output": "{\n\treturn 0, fmt.Errorf(\"bad\")\n}"} {"input": "package mysql\n\nimport (\n\t\"github.com/jmoiron/sqlx\"\n\t\"github.com/upframe/shopy\"\n)\n\n\ntype LinkService struct {\n\tDB *sqlx.DB\n}\n\nvar linkMap = map[string]string{\n\t\"Hash\": \"hash\",\n\t\"User\": \"user_id\",\n\t\"Path\": \"path\",\n\t\"Used\": \"used\",\n\t\"Time\": \"time\",\n\t\"Expires\": \"expires\",\n}\n\n\nfunc (s *LinkService) Get(hash string) (*shopy.Link, error) {\n\tlink := &shopy.Link{}\n\terr := s.DB.Get(link, \"SELECT * FROM links WHERE hash=?\", hash)\n\n\treturn link, err\n}\n\n\nfunc (s *LinkService) Gets(first, limit int, order string) ([]*shopy.Link, error) {\n\tlinks := []*shopy.Link{}\n\tvar err error\n\n\torder = fieldsToColumns(linkMap, order)[0]\n\n\tif limit == 0 {\n\t\terr = s.DB.Select(&links, \"SELECT * FROM links ORDER BY ?\", order)\n\t} else {\n\t\terr = s.DB.Select(&links, \"SELECT * FROM links ORDER BY ? LIMIT ? OFFSET ?\", order, limit, first)\n\t}\n\n\treturn links, err\n}\n\n\nfunc (s *LinkService) Create(l *shopy.Link) error {\n\t_, err := s.DB.NamedExec(insertQuery(\"links\", getAllColumns(linkMap)), l)\n\treturn err\n}\n\n\nfunc (s *LinkService) Update(l *shopy.Link, fields ...string) error {\n\t_, err := s.DB.NamedExec(updateQuery(\"links\", \"hash\", fieldsToColumns(linkMap, fields...)), l)\n\treturn err\n}\n\n\n\n\nfunc (s *LinkService) Delete(hash string) error ", "output": "{\n\tl, err := s.Get(hash)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tl.Used = true\n\treturn s.Update(l, \"Used\")\n}"} {"input": "package iso20022\n\n\ntype ActionMessage3 struct {\n\n\tDestination *UserInterface3Code `xml:\"Dstn\"`\n\n\tFormat *OutputFormat1Code `xml:\"Frmt,omitempty\"`\n\n\tContent *Max20000Text `xml:\"Cntt\"`\n}\n\nfunc (a *ActionMessage3) SetDestination(value string) {\n\ta.Destination = (*UserInterface3Code)(&value)\n}\n\nfunc (a *ActionMessage3) SetFormat(value string) {\n\ta.Format = (*OutputFormat1Code)(&value)\n}\n\n\n\nfunc (a *ActionMessage3) SetContent(value string) ", "output": "{\n\ta.Content = (*Max20000Text)(&value)\n}"} {"input": "package readline\n\nimport \"io\"\n\ntype Instance struct {\n\tt *Terminal\n\to *Operation\n}\n\ntype Config struct {\n\tPrompt string\n\tHistoryFile string\n}\n\nfunc NewEx(cfg *Config) (*Instance, error) {\n\tt, err := NewTerminal(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trl := t.Readline()\n\treturn &Instance{\n\t\tt: t,\n\t\to: rl,\n\t}, nil\n}\n\nfunc New(prompt string) (*Instance, error) {\n\treturn NewEx(&Config{Prompt: prompt})\n}\n\n\n\nfunc (i *Instance) Stderr() io.Writer {\n\treturn i.o.Stderr()\n}\n\nfunc (i *Instance) Readline() (string, error) {\n\treturn i.o.String()\n}\n\nfunc (i *Instance) ReadSlice() ([]byte, error) {\n\treturn i.o.Slice()\n}\n\nfunc (i *Instance) Close() error {\n\tif err := i.t.Close(); err != nil {\n\t\treturn err\n\t}\n\ti.o.Close()\n\treturn nil\n}\n\nfunc (i *Instance) Stdout() io.Writer ", "output": "{\n\treturn i.o.Stdout()\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/polariseye/polarserver/common\"\n\t\"github.com/polariseye/polarserver/common/errorCode\"\n\t\"github.com/polariseye/polarserver/moduleManage\"\n)\n\ntype testStruct struct {\n\tclassName string\n}\n\nvar TestBLL *testStruct\n\nfunc init() {\n\tTestBLL = NewTestStruct()\n\tmoduleManage.RegisterModule(func() (moduleManage.IModule, moduleManage.ModuleType) {\n\t\treturn NewTestStruct(), moduleManage.NormalModule\n\t})\n}\n\n\nfunc (this *testStruct) Name() string {\n\treturn this.className\n}\n\nfunc (this *testStruct) InitModule() []error {\n\tfmt.Println(\"初始化\")\n\n\treturn nil\n}\n\n\n\nfunc (this *testStruct) ConvertModule() []error {\n\tfmt.Println(\"数据转换\")\n\n\treturn nil\n}\n\n\nfunc (this *testStruct) C_Hello(request *common.RequestModel, d int, name string) *common.ResultModel {\n\tresult := common.NewResultModel(errorCode.ClientDataError)\n\n\tresult.Value[\"Hello\"] = name + \"_\" + this.Name()\n\tresult.Value[\"Extra\"] = d\n\n\tresult.SetNormalError(errorCode.Success)\n\treturn result\n}\n\nfunc NewTestStruct() *testStruct {\n\treturn &testStruct{\n\t\tclassName: \"TestBLL\",\n\t}\n}\n\nfunc (this *testStruct) CheckModule() []error ", "output": "{\n\tfmt.Println(\"check\")\n\n\treturn nil\n}"} {"input": "package safebrowsing\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\n\ntype logger interface {\n\tFinest(arg0 interface{}, args ...interface{})\n\tFine(arg0 interface{}, args ...interface{})\n\tDebug(arg0 interface{}, args ...interface{})\n\tTrace(arg0 interface{}, args ...interface{})\n\tInfo(arg0 interface{}, args ...interface{})\n\tWarn(arg0 interface{}, args ...interface{}) error\n\tError(arg0 interface{}, args ...interface{}) error\n\tCritical(arg0 interface{}, args ...interface{}) error\n}\n\n\n\ntype DefaultLogger struct{}\n\n\nfunc (dl *DefaultLogger) Finest(arg0 interface{}, args ...interface{}) {\n\tdl.log(\"FINE\", arg0, args...)\n}\nfunc (dl *DefaultLogger) Fine(arg0 interface{}, args ...interface{}) {\n\tdl.log(\"FINE\", arg0, args...)\n}\nfunc (dl *DefaultLogger) Debug(arg0 interface{}, args ...interface{}) {\n\tdl.log(\"DEBG\", arg0, args...)\n}\nfunc (dl *DefaultLogger) Trace(arg0 interface{}, args ...interface{}) {\n\tdl.log(\"TRAC\", arg0, args...)\n}\nfunc (dl *DefaultLogger) Info(arg0 interface{}, args ...interface{}) {\n\tdl.log(\"INFO\", arg0, args...)\n}\nfunc (dl *DefaultLogger) Warn(arg0 interface{}, args ...interface{}) error {\n\tdl.log(\"WARN\", arg0, args...)\n\treturn nil\n}\nfunc (dl *DefaultLogger) Error(arg0 interface{}, args ...interface{}) error {\n\tdl.log(\"EROR\", arg0, args...)\n\treturn nil\n}\nfunc (dl *DefaultLogger) Critical(arg0 interface{}, args ...interface{}) error {\n\tdl.log(\"CRIT\", arg0, args...)\n\treturn nil\n}\n\nfunc (dl *DefaultLogger) log(level string, arg0 interface{}, args ...interface{}) ", "output": "{\n\tprefix := fmt.Sprintf(\n\t\t\"[%v] [%s] \",\n\t\ttime.Now().Format(\"2006-01-02 15:04:05\"),\n\t\tlevel)\n\tfmt.Printf(prefix+arg0.(string)+\"\\n\", args...)\n}"} {"input": "package metrics\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\n\ntype GaugeMetric struct {\n\tvalue float64\n\tmutex sync.RWMutex\n}\n\nfunc (metric *GaugeMetric) Humanize() string {\n\tformatString := \"[GaugeMetric; value=%f]\"\n\n\tmetric.mutex.RLock()\n\tdefer metric.mutex.RUnlock()\n\n\treturn fmt.Sprintf(formatString, metric.value)\n}\n\nfunc (metric *GaugeMetric) Set(value float64) float64 {\n\tmetric.mutex.Lock()\n\tdefer metric.mutex.Unlock()\n\n\tmetric.value = value\n\n\treturn metric.value\n}\n\n\n\nfunc (metric *GaugeMetric) Increment() float64 {\n\treturn metric.IncrementBy(1)\n}\n\nfunc (metric *GaugeMetric) DecrementBy(value float64) float64 {\n\tmetric.mutex.Lock()\n\tdefer metric.mutex.Unlock()\n\n\tmetric.value -= value\n\n\treturn metric.value\n}\n\nfunc (metric *GaugeMetric) Decrement() float64 {\n\treturn metric.DecrementBy(1)\n}\n\nfunc (metric *GaugeMetric) Get() float64 {\n\tmetric.mutex.RLock()\n\tdefer metric.mutex.RUnlock()\n\n\treturn metric.value\n}\n\nfunc (metric *GaugeMetric) Marshallable() map[string]interface{} {\n\tmetric.mutex.RLock()\n\tdefer metric.mutex.RUnlock()\n\n\tv := make(map[string]interface{}, 2)\n\n\tv[valueKey] = metric.value\n\tv[typeKey] = gaugeTypeValue\n\n\treturn v\n}\n\nfunc (metric *GaugeMetric) IncrementBy(value float64) float64 ", "output": "{\n\tmetric.mutex.Lock()\n\tdefer metric.mutex.Unlock()\n\n\tmetric.value += value\n\n\treturn metric.value\n}"} {"input": "package utils\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n)\n\n\n\n\n\n\n\nconst (\n\twriteExec = 1 << iota\n\twriteSkipSame\n)\n\n\nfunc ReadFile(file string) string {\n\tdata, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\tlog.Fatalf(\"ReadFile: %v\", err)\n\t}\n\treturn string(data)\n}\n\n\n\n\n\nfunc WriteFile(b, file string, flag int) {\n\tnew := []byte(b)\n\tif flag&writeSkipSame != 0 {\n\t\told, err := ioutil.ReadFile(file)\n\t\tif err == nil && bytes.Equal(old, new) {\n\t\t\treturn\n\t\t}\n\t}\n\tmode := os.FileMode(0666)\n\tif flag&writeExec != 0 {\n\t\tmode = 0777\n\t}\n\terr := ioutil.WriteFile(file, new, mode)\n\tif err != nil {\n\t\tlog.Fatalf(\"WriteFile: %v\", err)\n\t}\n}\n\n\n\n\nfunc CopyFile(dst, src string, flag int) ", "output": "{\n\tWriteFile(ReadFile(src), dst, flag)\n}"} {"input": "package etcd\n\nimport (\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apiserver/pkg/registry/generic\"\n\t\"k8s.io/apiserver/pkg/registry/generic/registry\"\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/registry/cachesize\"\n\t\"k8s.io/kubernetes/pkg/registry/securitycontextconstraints\"\n)\n\n\ntype REST struct {\n\t*registry.Store\n}\n\n\nfunc NewREST(optsGetter generic.RESTOptionsGetter) *REST {\n\tstore := ®istry.Store{\n\t\tCopier: api.Scheme,\n\t\tNewFunc: func() runtime.Object { return &api.SecurityContextConstraints{} },\n\t\tNewListFunc: func() runtime.Object { return &api.SecurityContextConstraintsList{} },\n\t\tObjectNameFunc: func(obj runtime.Object) (string, error) {\n\t\t\treturn obj.(*api.SecurityContextConstraints).Name, nil\n\t\t},\n\t\tPredicateFunc: securitycontextconstraints.Matcher,\n\t\tQualifiedResource: api.Resource(\"securitycontextconstraints\"),\n\t\tWatchCacheSize: cachesize.GetWatchCacheSizeByResource(\"securitycontextconstraints\"),\n\n\t\tCreateStrategy: securitycontextconstraints.Strategy,\n\t\tUpdateStrategy: securitycontextconstraints.Strategy,\n\t\tDeleteStrategy: securitycontextconstraints.Strategy,\n\t\tReturnDeletedObject: true,\n\t}\n\toptions := &generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: securitycontextconstraints.GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\tpanic(err) \n\t}\n\treturn &REST{store}\n}\n\n\n\n\nfunc (r *REST) ShortNames() []string ", "output": "{\n\treturn []string{\"scc\"}\n}"} {"input": "package loggo\n\nvar (\n\tdefaultContext = newDefaultContxt()\n)\n\nfunc newDefaultContxt() *Context {\n\tctx := NewContext(WARNING)\n\tctx.AddWriter(DefaultWriterName, defaultWriter())\n\treturn ctx\n}\n\n\n\n\n\n\n\n\nfunc LoggerInfo() string {\n\treturn defaultContext.Config().String()\n}\n\n\n\nfunc GetLogger(name string, size ...int) Logger {\n\treturn defaultContext.GetLogger(name, size...)\n}\n\n\n\n\n\nfunc ResetLogging() {\n\tdefaultContext.ResetLoggerLevels()\n\tdefaultContext.ResetWriters()\n}\n\n\nfunc ResetWriters() {\n\tdefaultContext.ResetWriters()\n}\n\n\n\n\nfunc ReplaceDefaultWriter(writer Writer) (Writer, error) {\n\treturn defaultContext.ReplaceWriter(DefaultWriterName, writer)\n}\n\n\n\n\nfunc RegisterWriter(name string, writer Writer) error {\n\treturn defaultContext.AddWriter(name, writer)\n}\n\n\n\nfunc RemoveWriter(name string) (Writer, error) {\n\treturn defaultContext.RemoveWriter(name)\n}\n\n\n\n\n\n\n\n\n\n\nfunc ConfigureLoggers(specification string) error {\n\tconfig, err := ParseConfigString(specification)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefaultContext.ApplyConfig(config)\n\treturn nil\n}\n\nfunc DefaultContext() *Context ", "output": "{\n\treturn defaultContext\n}"} {"input": "package types\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"path\"\n\t\"strings\"\n)\n\n\ntype Resource string\n\nfunc (res Resource) String() string {\n\treturn string(res)\n}\n\n\n\n\n\nfunc (res Resource) Subresource(resources ...Resource) Resource {\n\telements := []string{res.String()}\n\n\tfor _, resource := range resources {\n\t\telements = append(elements, resource.String())\n\t}\n\n\treturn Resource(path.Join(elements...))\n}\n\n\nfunc (res Resource) GetNamespace() (Namespace, error) {\n\treturn nil, fmt.Errorf(\"no namespace found for %s\", res)\n}\n\nfunc (res Resource) RelativeTo(other Resource) (Resource, error) ", "output": "{\n\tprefix := other.String()\n\tstr := res.String()\n\n\tif !strings.HasPrefix(str, prefix) {\n\t\treturn Resource(\"\"), errors.New(\"value error\")\n\t}\n\n\trelative := strings.TrimPrefix(strings.TrimPrefix(str, prefix), \"/\")\n\tif relative == \"\" {\n\t\trelative = \".\"\n\t}\n\n\treturn Resource(relative), nil\n}"} {"input": "package client\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/mesosphere/dcos-commons/cli/config\"\n)\n\n\n\nvar PrintMessage = printMessage\n\n\n\nvar PrintMessageAndExit = printMessageAndExit\n\nfunc printMessage(format string, a ...interface{}) (int, error) {\n\treturn fmt.Println(fmt.Sprintf(format, a...))\n}\n\n\n\n\nfunc PrintVerbose(format string, a ...interface{}) (int, error) {\n\tif config.Verbose {\n\t\treturn PrintMessage(format, a...)\n\t}\n\treturn 0, nil\n}\n\n\n\n\nfunc PrintJSONBytes(responseBytes []byte) {\n\tvar outBuf bytes.Buffer\n\terr := json.Indent(&outBuf, responseBytes, \"\", \" \")\n\tif err != nil {\n\t\tPrintMessage(\"Failed to prettify JSON response data: %s\", err)\n\t\tPrintMessage(\"Original data follows:\")\n\t\toutBuf = *bytes.NewBuffer(responseBytes)\n\t}\n\tPrintMessage(\"%s\", outBuf.String())\n}\n\n\nfunc PrintResponseText(body []byte) {\n\tPrintMessage(\"%s\\n\", string(body))\n}\n\nfunc printMessageAndExit(format string, a ...interface{}) (int, error) ", "output": "{\n\tPrintMessage(format, a...)\n\tos.Exit(1)\n\treturn 0, nil\n}"} {"input": "package loadbalancer\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CreateListenerRequest struct {\n\n\tCreateListenerDetails `contributesTo:\"body\"`\n\n\tLoadBalancerId *string `mandatory:\"true\" contributesTo:\"path\" name:\"loadBalancerId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CreateListenerRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request CreateListenerRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request CreateListenerRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype CreateListenerResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CreateListenerResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response CreateListenerResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request CreateListenerRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package engine\n\nimport (\n\t\"time\"\n\n\t\"github.com/aws/amazon-ecs-agent/agent/api\"\n)\n\n\n\ntype impossibleTransitionError struct {\n\tstate api.ContainerStatus\n}\n\nfunc (err *impossibleTransitionError) Error() string {\n\treturn \"Cannot transition to \" + err.state.String()\n}\nfunc (err *impossibleTransitionError) ErrorName() string { return \"ImpossibleStateTransitionError\" }\n\ntype DockerTimeoutError struct {\n\tduration time.Duration\n\ttransition string\n}\n\nfunc (err *DockerTimeoutError) Error() string {\n\treturn \"Could not transition to \" + err.transition + \"; timed out after waiting \" + err.duration.String()\n}\nfunc (err *DockerTimeoutError) ErrorName() string { return \"DockerTimeoutError\" }\n\ntype ContainerVanishedError struct{}\n\nfunc (err ContainerVanishedError) Error() string { return \"No container matching saved ID found\" }\nfunc (err ContainerVanishedError) ErrorName() string { return \"ContainerVanishedError\" }\n\ntype CannotXContainerError struct {\n\ttransition string\n\tmsg string\n}\n\nfunc (err CannotXContainerError) Error() string { return err.msg }\nfunc (err CannotXContainerError) ErrorName() string {\n\treturn \"Cannot\" + err.transition + \"ContainerError\"\n}\n\ntype OutOfMemoryError struct{}\n\nfunc (err OutOfMemoryError) Error() string { return \"Container killed due to memory usage\" }\nfunc (err OutOfMemoryError) ErrorName() string { return \"OutOfMemoryError\" }\n\n\ntype DockerStateError struct {\n\tdockerError string\n\tname string\n}\n\nfunc NewDockerStateError(err string) DockerStateError {\n\treturn DockerStateError{\n\t\tdockerError: err,\n\t\tname: \"DockerStateError\",\n\t}\n}\n\n\nfunc (err DockerStateError) ErrorName() string {\n\treturn err.name\n}\n\nfunc (err DockerStateError) Error() string ", "output": "{\n\treturn err.dockerError\n}"} {"input": "package test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/ncarlier/webhookd/pkg/assert\"\n\t\"github.com/ncarlier/webhookd/pkg/strcase\"\n)\n\n\n\nfunc TestToSnakeCase(t *testing.T) ", "output": "{\n\ttestCases := []struct {\n\t\tvalue string\n\t\texpected string\n\t}{\n\t\t{\"hello-world\", \"hello_world\"},\n\t\t{\"helloWorld\", \"hello_world\"},\n\t\t{\"HelloWorld\", \"hello_world\"},\n\t\t{\"Hello/_World\", \"hello__world\"},\n\t\t{\"Hello/world\", \"hello_world\"},\n\t}\n\tfor _, tc := range testCases {\n\t\tvalue := strcase.ToSnake(tc.value)\n\t\tassert.Equal(t, tc.expected, value, \"\")\n\t}\n}"} {"input": "package dockertools\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\tdocker \"github.com/fsouza/go-dockerclient\"\n\tkubecontainer \"k8s.io/kubernetes/pkg/kubelet/container\"\n\tkubetypes \"k8s.io/kubernetes/pkg/kubelet/types\"\n)\n\n\n\n\n\n\n\nfunc toRuntimeContainer(c *docker.APIContainers) (*kubecontainer.Container, error) {\n\tif c == nil {\n\t\treturn nil, fmt.Errorf(\"unable to convert a nil pointer to a runtime container\")\n\t}\n\n\tdockerName, hash, err := getDockerContainerNameInfo(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &kubecontainer.Container{\n\t\tID: kubetypes.DockerID(c.ID).ContainerID(),\n\t\tName: dockerName.ContainerName,\n\t\tImage: c.Image,\n\t\tHash: hash,\n\t\tCreated: c.Created,\n\t\tStatus: mapStatus(c.Status),\n\t}, nil\n}\n\n\nfunc toRuntimeImage(image *docker.APIImages) (*kubecontainer.Image, error) {\n\tif image == nil {\n\t\treturn nil, fmt.Errorf(\"unable to convert a nil pointer to a runtime image\")\n\t}\n\n\treturn &kubecontainer.Image{\n\t\tID: image.ID,\n\t\tTags: image.RepoTags,\n\t\tSize: image.VirtualSize,\n\t}, nil\n}\n\nfunc mapStatus(status string) kubecontainer.ContainerStatus ", "output": "{\n\tswitch {\n\tcase strings.HasPrefix(status, \"Up\"):\n\t\treturn kubecontainer.ContainerStatusRunning\n\tcase strings.HasPrefix(status, \"Exited\"):\n\t\treturn kubecontainer.ContainerStatusExited\n\tdefault:\n\t\treturn kubecontainer.ContainerStatusUnknown\n\t}\n}"} {"input": "package parlib\n\nimport (\n\t\"errors\"\n)\n\n\nfunc Cstrlen(str []byte) int {\n var i int = 0\n for (str[i] != 0) { i++ }\n return i\n}\n\n\n\n\nfunc StringByteSlice(s string) []byte {\n\ta, err := ByteSliceFromString(s)\n\tif err != nil {\n\t\tpanic(\"syscall: string with NUL passed to StringByteSlice\")\n\t}\n\treturn a\n}\n\n\n\n\n\n\n\n\n\nfunc StringBytePtr(s string) *byte { return &StringByteSlice(s)[0] }\n\n\n\n\nfunc BytePtrFromString(s string) (*byte, error) {\n\ta, err := ByteSliceFromString(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &a[0], nil\n}\n\n\n\n\nfunc StringSlicePtr(ss []string) []*byte {\n bb := make([]*byte, len(ss)+1)\n for i := 0; i < len(ss); i++ {\n bb[i] = StringBytePtr(ss[i])\n }\n bb[len(ss)] = nil\n return bb\n}\n\n\n\n\nfunc SlicePtrFromStrings(ss []string) ([]*byte, error) {\n var err error\n bb := make([]*byte, len(ss)+1)\n for i := 0; i < len(ss); i++ {\n bb[i], err = BytePtrFromString(ss[i])\n if err != nil {\n return nil, err\n }\n }\n bb[len(ss)] = nil\n return bb, nil\n}\n\nfunc ByteSliceFromString(s string) ([]byte, error) ", "output": "{\n\tfor i := 0; i < len(s); i++ {\n\t\tif s[i] == 0 {\n\t\t\treturn nil, errors.New(\"String contains a NULL byte.\")\n\t\t}\n\t}\n\ta := make([]byte, len(s)+1)\n\tcopy(a, s)\n\treturn a, nil\n}"} {"input": "package state\n\nimport (\n\t\"sync\"\n)\n\n\n\n\n\ntype NotifyGroup struct {\n\tl sync.Mutex\n\tnotify map[chan struct{}]struct{}\n}\n\n\n\nfunc (n *NotifyGroup) Notify() {\n\tn.l.Lock()\n\tdefer n.l.Unlock()\n\tfor ch, _ := range n.notify {\n\t\tselect {\n\t\tcase ch <- struct{}{}:\n\t\tdefault:\n\t\t}\n\t}\n\tn.notify = nil\n}\n\n\nfunc (n *NotifyGroup) Wait(ch chan struct{}) {\n\tn.l.Lock()\n\tdefer n.l.Unlock()\n\tif n.notify == nil {\n\t\tn.notify = make(map[chan struct{}]struct{})\n\t}\n\tn.notify[ch] = struct{}{}\n}\n\n\nfunc (n *NotifyGroup) Clear(ch chan struct{}) {\n\tn.l.Lock()\n\tdefer n.l.Unlock()\n\tif n.notify == nil {\n\t\treturn\n\t}\n\tdelete(n.notify, ch)\n}\n\n\n\n\n\nfunc (n *NotifyGroup) Empty() bool {\n\tn.l.Lock()\n\tdefer n.l.Unlock()\n\treturn len(n.notify) == 0\n}\n\nfunc (n *NotifyGroup) WaitCh() chan struct{} ", "output": "{\n\tch := make(chan struct{}, 1)\n\tn.Wait(ch)\n\treturn ch\n}"} {"input": "package console\n\nimport \"github.com/cgrates/cgrates/utils\"\n\nfunc init() {\n\tc := &CmdGetCacheAge{\n\t\tname: \"cache_age\",\n\t\trpcMethod: \"ApierV1.GetCachedItemAge\",\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdGetCacheAge struct {\n\tname string\n\trpcMethod string\n\trpcParams *StringWrapper\n\t*CommandExecuter\n}\n\nfunc (self *CmdGetCacheAge) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdGetCacheAge) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdGetCacheAge) RpcParams() interface{} {\n\tif self.rpcParams == nil {\n\t\tself.rpcParams = &StringWrapper{}\n\t}\n\treturn self.rpcParams\n}\n\n\n\nfunc (self *CmdGetCacheAge) RpcResult() interface{} {\n\treturn &utils.CachedItemAge{}\n}\n\nfunc (self *CmdGetCacheAge) PostprocessRpcParams() error ", "output": "{\n\treturn nil\n}"} {"input": "package core\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n\t\"net/http\"\n)\n\n\ntype DeleteVirtualCircuitRequest struct {\n\n\tVirtualCircuitId *string `mandatory:\"true\" contributesTo:\"path\" name:\"virtualCircuitId\"`\n\n\tIfMatch *string `mandatory:\"false\" contributesTo:\"header\" name:\"if-match\"`\n}\n\nfunc (request DeleteVirtualCircuitRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\ntype DeleteVirtualCircuitResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\n\n\nfunc (response DeleteVirtualCircuitResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/jackytck/projecteuler/tools\"\n)\n\nfunc match(p, s string) bool {\n\tm := make(map[rune]bool)\n\tfor _, r := range s {\n\t\tm[r] = true\n\t}\n\tvar e string\n\tfor _, r := range p {\n\t\tif m[r] {\n\t\t\te += string(r)\n\t\t}\n\t}\n\treturn e == s\n}\n\nfunc check(p string, log []string) bool {\n\tfor _, s := range log {\n\t\tif !match(p, s) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\n\nfunc main() {\n\tfmt.Println(solve(\"./p079_keylog.txt\"))\n}\n\nfunc solve(path string) string ", "output": "{\n\tlogs, err := tools.ReadFile(path)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\texist := make(map[string]bool)\n\tvar unique []string\n\tfor _, v := range logs {\n\t\tif !exist[v] {\n\t\t\tunique = append(unique, v)\n\t\t\texist[v] = true\n\t\t}\n\t}\n\n\tfor p := range tools.Perms([]int{0, 1, 2, 3, 6, 7, 8, 9}) {\n\t\tpsw := tools.JoinIntsString(p...)\n\t\tif check(psw, unique) {\n\t\t\treturn psw\n\t\t}\n\t}\n\n\treturn \"\"\n}"} {"input": "package logutils\n\nimport (\n\t\"github.com/stretchr/testify/mock\"\n)\n\ntype MockLog struct {\n\tmock.Mock\n}\n\n\n\nfunc (m *MockLog) Fatalf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Panicf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Errorf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Warnf(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Infof(format string, args ...interface{}) {\n\tmArgs := []interface{}{format}\n\tm.Called(append(mArgs, args...)...)\n}\n\nfunc (m *MockLog) Child(name string) Log {\n\tm.Called(name)\n\treturn m\n}\n\nfunc (m *MockLog) SetLevel(level LogLevel) {\n\tm.Called(level)\n}\n\nfunc NewMockLog() *MockLog ", "output": "{\n\treturn &MockLog{}\n}"} {"input": "package stack\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\n\t\"github.com/docker/docker/cli/command/bundlefile\"\n\t\"github.com/spf13/pflag\"\n)\n\nfunc addComposefileFlag(opt *string, flags *pflag.FlagSet) {\n\tflags.StringVarP(opt, \"compose-file\", \"c\", \"\", \"Path to a Compose file\")\n}\n\nfunc addBundlefileFlag(opt *string, flags *pflag.FlagSet) {\n\tflags.StringVar(opt, \"bundle-file\", \"\", \"Path to a Distributed Application Bundle file\")\n\tflags.SetAnnotation(\"bundle-file\", \"experimental\", nil)\n}\n\n\n\nfunc loadBundlefile(stderr io.Writer, namespace string, path string) (*bundlefile.Bundlefile, error) {\n\tdefaultPath := fmt.Sprintf(\"%s.dab\", namespace)\n\n\tif path == \"\" {\n\t\tpath = defaultPath\n\t}\n\tif _, err := os.Stat(path); err != nil {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"Bundle %s not found. Specify the path with --file\",\n\t\t\tpath)\n\t}\n\n\tfmt.Fprintf(stderr, \"Loading bundle from %s\\n\", path)\n\treader, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer reader.Close()\n\n\tbundle, err := bundlefile.LoadFile(reader)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error reading %s: %v\\n\", path, err)\n\t}\n\treturn bundle, err\n}\n\nfunc addRegistryAuthFlag(opt *bool, flags *pflag.FlagSet) ", "output": "{\n\tflags.BoolVar(opt, \"with-registry-auth\", false, \"Send registry authentication details to Swarm agents\")\n}"} {"input": "package view\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"html/template\"\n)\n\n\n\nfunc Show() string ", "output": "{\n\n\ttpl, err := template.ParseFiles(`tpl/head.html`)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\n\tbuf := new(bytes.Buffer)\n\terr = tpl.Execute(buf, nil)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\treturn buf.String()\n}"} {"input": "package cache\n\nimport (\n\tkapi \"k8s.io/kubernetes/pkg/api\"\n\tkapierrors \"k8s.io/kubernetes/pkg/api/errors\"\n\t\"k8s.io/kubernetes/pkg/controller/framework\"\n\n\toapi \"github.com/openshift/origin/pkg/api\"\n\tauthorizationapi \"github.com/openshift/origin/pkg/authorization/api\"\n\tclusterpolicyregistry \"github.com/openshift/origin/pkg/authorization/registry/clusterpolicy\"\n\t\"github.com/openshift/origin/pkg/client\"\n)\n\ntype InformerToClusterPolicyLister struct {\n\tframework.SharedIndexInformer\n}\n\n\nfunc (i *InformerToClusterPolicyLister) LastSyncResourceVersion() string {\n\treturn i.SharedIndexInformer.LastSyncResourceVersion()\n}\n\nfunc (i *InformerToClusterPolicyLister) ClusterPolicies() client.ClusterPolicyLister {\n\treturn i\n}\n\n\n\nfunc (i *InformerToClusterPolicyLister) Get(name string) (*authorizationapi.ClusterPolicy, error) {\n\tkeyObj := &authorizationapi.ClusterPolicy{ObjectMeta: kapi.ObjectMeta{Name: name}}\n\tkey, _ := framework.DeletionHandlingMetaNamespaceKeyFunc(keyObj)\n\n\titem, exists, getErr := i.GetIndexer().GetByKey(key)\n\tif getErr != nil {\n\t\treturn nil, getErr\n\t}\n\tif !exists {\n\t\texistsErr := kapierrors.NewNotFound(authorizationapi.Resource(\"clusterpolicy\"), name)\n\t\treturn nil, existsErr\n\t}\n\treturn item.(*authorizationapi.ClusterPolicy), nil\n}\n\nfunc (i *InformerToClusterPolicyLister) List(options kapi.ListOptions) (*authorizationapi.ClusterPolicyList, error) ", "output": "{\n\tclusterPolicyList := &authorizationapi.ClusterPolicyList{}\n\treturnedList := i.GetIndexer().List()\n\tmatcher := clusterpolicyregistry.Matcher(oapi.ListOptionsToSelectors(&options))\n\tfor i := range returnedList {\n\t\tclusterPolicy := returnedList[i].(*authorizationapi.ClusterPolicy)\n\t\tif matches, err := matcher.Matches(clusterPolicy); err == nil && matches {\n\t\t\tclusterPolicyList.Items = append(clusterPolicyList.Items, *clusterPolicy)\n\t\t}\n\t}\n\treturn clusterPolicyList, nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/directorz/mailfull-go\"\n\t\"github.com/directorz/mailfull-go/cmd\"\n)\n\n\ntype CmdDomainDel struct {\n\tcmd.Meta\n}\n\n\nfunc (c *CmdDomainDel) Synopsis() string {\n\treturn \"Delete and backup a domain.\"\n}\n\n\n\n\n\nfunc (c *CmdDomainDel) Run(args []string) int {\n\tnoCommit, err := noCommitFlag(&args)\n\tif err != nil {\n\t\tfmt.Fprintf(c.UI.ErrorWriter, \"%v\\n\", c.Help())\n\t\treturn 1\n\t}\n\n\tif len(args) != 1 {\n\t\tfmt.Fprintf(c.UI.ErrorWriter, \"%v\\n\", c.Help())\n\t\treturn 1\n\t}\n\n\tdomainName := args[0]\n\n\trepo, err := mailfull.OpenRepository(\".\")\n\tif err != nil {\n\t\tc.Meta.Errorf(\"%v\\n\", err)\n\t\treturn 1\n\t}\n\n\tif err := repo.DomainRemove(domainName); err != nil {\n\t\tc.Meta.Errorf(\"%v\\n\", err)\n\t\treturn 1\n\t}\n\n\tif noCommit {\n\t\treturn 0\n\t}\n\tif err = repo.GenerateDatabases(); err != nil {\n\t\tc.Meta.Errorf(\"%v\\n\", err)\n\t\treturn 1\n\t}\n\n\treturn 0\n}\n\nfunc (c *CmdDomainDel) Help() string ", "output": "{\n\ttxt := fmt.Sprintf(`\nUsage:\n %s %s [-n] domain\n\nDescription:\n %s\n\nRequired Args:\n domain\n The domain name that you want to delete.\n\nOptional Args:\n -n\n Don't update databases.\n`,\n\t\tc.CmdName, c.SubCmdName,\n\t\tc.Synopsis())\n\n\treturn txt[1:]\n}"} {"input": "package rulevalidation\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"k8s.io/kubernetes/pkg/api\"\n\t\"k8s.io/kubernetes/pkg/api/unversioned\"\n\t\"k8s.io/kubernetes/pkg/util/sets\"\n\n\tauthorizationapi \"github.com/openshift/origin/pkg/authorization/api\"\n)\n\n\n\nfunc CompactRules(rules []authorizationapi.PolicyRule) ([]authorizationapi.PolicyRule, error) {\n\tcompacted := make([]authorizationapi.PolicyRule, 0, len(rules))\n\n\tsimpleRules := map[unversioned.GroupResource]*authorizationapi.PolicyRule{}\n\tfor _, rule := range rules {\n\t\tif resource, isSimple := isSimpleResourceRule(&rule); isSimple {\n\t\t\tif existingRule, ok := simpleRules[resource]; ok {\n\t\t\t\tif existingRule.Verbs == nil {\n\t\t\t\t\texistingRule.Verbs = sets.NewString()\n\t\t\t\t}\n\t\t\t\texistingRule.Verbs.Insert(rule.Verbs.List()...)\n\t\t\t} else {\n\t\t\t\tobjCopy, err := api.Scheme.DeepCopy(rule)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\truleCopy, ok := objCopy.(authorizationapi.PolicyRule)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, fmt.Errorf(\"expected authorizationapi.PolicyRule, got %#v\", objCopy)\n\t\t\t\t}\n\t\t\t\tsimpleRules[resource] = &ruleCopy\n\t\t\t}\n\t\t} else {\n\t\t\tcompacted = append(compacted, rule)\n\t\t}\n\t}\n\n\tfor _, simpleRule := range simpleRules {\n\t\tcompacted = append(compacted, *simpleRule)\n\t}\n\n\treturn compacted, nil\n}\n\n\n\n\nfunc isSimpleResourceRule(rule *authorizationapi.PolicyRule) (unversioned.GroupResource, bool) ", "output": "{\n\tresource := unversioned.GroupResource{}\n\n\tif len(rule.ResourceNames) > 0 || len(rule.NonResourceURLs) > 0 || rule.AttributeRestrictions != nil {\n\t\treturn resource, false\n\t}\n\tif len(rule.APIGroups) != 1 || len(rule.Resources) != 1 {\n\t\treturn resource, false\n\t}\n\n\tsimpleRule := &authorizationapi.PolicyRule{APIGroups: rule.APIGroups, Resources: rule.Resources, Verbs: rule.Verbs}\n\tif !reflect.DeepEqual(simpleRule, rule) {\n\t\treturn resource, false\n\t}\n\tresource = unversioned.GroupResource{Group: rule.APIGroups[0], Resource: rule.Resources.List()[0]}\n\treturn resource, true\n}"} {"input": "package errors \n\nimport (\n\t\"strconv\"\n)\n\n\n\ntype StructuralError string\n\nfunc (s StructuralError) Error() string {\n\treturn \"openpgp: invalid data: \" + string(s)\n}\n\n\n\ntype UnsupportedError string\n\n\n\n\n\ntype InvalidArgumentError string\n\nfunc (i InvalidArgumentError) Error() string {\n\treturn \"openpgp: invalid argument: \" + string(i)\n}\n\n\n\ntype SignatureError string\n\nfunc (b SignatureError) Error() string {\n\treturn \"openpgp: invalid signature: \" + string(b)\n}\n\ntype keyIncorrectError int\n\nfunc (ki keyIncorrectError) Error() string {\n\treturn \"openpgp: incorrect key\"\n}\n\nvar ErrKeyIncorrect error = keyIncorrectError(0)\n\ntype unknownIssuerError int\n\nfunc (unknownIssuerError) Error() string {\n\treturn \"openpgp: signature made by unknown entity\"\n}\n\nvar ErrUnknownIssuer error = unknownIssuerError(0)\n\ntype keyRevokedError int\n\nfunc (keyRevokedError) Error() string {\n\treturn \"openpgp: signature made by revoked key\"\n}\n\nvar ErrKeyRevoked error = keyRevokedError(0)\n\ntype UnknownPacketTypeError uint8\n\nfunc (upte UnknownPacketTypeError) Error() string {\n\treturn \"openpgp: unknown packet type: \" + strconv.Itoa(int(upte))\n}\n\nfunc (s UnsupportedError) Error() string ", "output": "{\n\treturn \"openpgp: unsupported feature: \" + string(s)\n}"} {"input": "package ldapserver\n\ntype CompareRequest struct {\n\tentry LDAPDN\n\tava AttributeValueAssertion\n}\n\n\n\nfunc (r *CompareRequest) GetAttributeValueAssertion() *AttributeValueAssertion {\n\treturn &r.ava\n}\n\ntype CompareResponse struct {\n\tldapResult\n}\n\nfunc NewCompareResponse(resultCode int) *CompareResponse {\n\tr := &CompareResponse{}\n\tr.ResultCode = resultCode\n\treturn r\n}\n\nfunc (r *CompareRequest) GetEntry() LDAPDN ", "output": "{\n\treturn r.entry\n}"} {"input": "package next\n\nimport (\n \"gopkg.in/mgo.v2\"\n \"gopkg.in/mgo.v2/bson\"\n)\n\ntype MongoDB struct {\n session *mgo.Session\n db string\n}\n\n\n\nfunc (mongo *MongoDB) Open(url string, db string) {\n s, err := mgo.Dial(url)\n if err != nil {\n panic(err.Error())\n }\n\n mongo.session = s\n mongo.db = db\n}\n\nfunc (mongo *MongoDB) Close() {\n mongo.session.Close()\n}\n\nfunc (mongo *MongoDB) Session() *mgo.Session {\n s := mongo.session.Copy()\n s.SetMode(mgo.Strong, true)\n return s\n}\n\nfunc (mongo *MongoDB) InsertOrUpdate(collection string, buziKey string, buziValue interface{}, d interface{}, result interface{}) (error) {\n s := mongo.Session()\n defer s.Close()\n\n c := s.DB(mongo.db).C(collection)\n\n change := mgo.Change{\n Update: bson.M{\"$set\": d},\n Upsert: true,\n Remove: false,\n ReturnNew: true,\n }\n\n _, err := c.Find(bson.M{buziKey: buziValue}).Apply(change, result)\n return err\n}\n\nfunc NewMongoDB() *MongoDB ", "output": "{\n return &MongoDB{}\n}"} {"input": "package mcore\n\nimport (\n\t\"log\"\n)\n\ntype StringKeyValueMap map[string]string\n\nfunc NewStringKeyValueMap() StringKeyValueMap {\n\treturn make(map[string]string)\n}\n\n\n\n\nfunc (c StringKeyValueMap) IsContain(key string) bool {\n\t_, ok := c[key]\n\treturn ok\n}\n\nfunc (c StringKeyValueMap) GetString(key string) string {\n\treturn c.GetStringWithDefault(key, \"\")\n}\n\nfunc (c StringKeyValueMap) GetStringWithDefault(key, defaultValue string) string {\n\tif c.IsContain(key) {\n\t\treturn c[key]\n\t}\n\tlog.Printf(\"Error: not contains key: %s\", key)\n\treturn defaultValue\n}\n\nfunc (c StringKeyValueMap) GetInt(key string) int {\n\treturn String(c.GetString(key)).ToIntNoError()\n}\n\nfunc (c StringKeyValueMap) GetBool(key string) bool {\n\treturn String(c.GetString(key)).ToBool()\n}\n\nfunc (c StringKeyValueMap) Put(key, value string) ", "output": "{\n\tc[key] = value\n}"} {"input": "package dbinterface\n\nimport _ \"github.com/go-sql-driver/mysql\" \n\n\n\n\n\nfunc Create(db DB) error ", "output": "{\n\tif _, err := db.Exec(\"CREATE TABLE example (name VARCHAR(20), created DATETIME)\"); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := db.Exec(`INSERT INTO example (name, created) values (\"Aaron\", NOW())`); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package perffile\n\nimport \"strconv\"\n\nconst _CPUMode_name = \"CPUModeUnknownCPUModeKernelCPUModeUserCPUModeHypervisorCPUModeGuestKernelCPUModeGuestUser\"\n\nvar _CPUMode_index = [...]uint8{0, 14, 27, 38, 55, 73, 89}\n\n\n\nfunc (i CPUMode) String() string ", "output": "{\n\tif i >= CPUMode(len(_CPUMode_index)-1) {\n\t\treturn \"CPUMode(\" + strconv.FormatInt(int64(i), 10) + \")\"\n\t}\n\treturn _CPUMode_name[_CPUMode_index[i]:_CPUMode_index[i+1]]\n}"} {"input": "package audioplayer\n\nimport (\n \"govkmedia/dialogboxes\"\n \"govkmedia/requestwrapper\"\n \"strconv\"\n \"time\"\n)\n\nfunc (e *Engine) StartPlay() {\n mwroot:=e.mainWindow.Root()\n playerobj:=mwroot.ObjectByName(\"mplayer\")\n curplaying:=e.playlist[e.currentPlaying]\n playerobj.Set(\"source\",curplaying.Url)\n time.Sleep(time.Second) \n context:=e.qmlEngine.Context()\n context.SetVar(\"vkartist\",curplaying.Artist)\n context.SetVar(\"vktitle\",curplaying.Title)\n context.SetVar(\"vkduration\",curplaying.Duration)\n e.LoadLyrics()\n playerobj.Call(\"resetProgress\")\n playerobj.Call(\"play\")\n}\n\n\n\nfunc (e *Engine) Next() {\n if e.currentPlaying+1==len(e.playlist) { return }\n e.currentPlaying++\n e.StartPlay()\n}\n\nfunc (e *Engine) Prev() {\n if e.currentPlaying==0 { return }\n e.currentPlaying--\n e.StartPlay()\n}\n\nfunc (e *Engine) LoadLyrics() ", "output": "{\n curplaying:=e.playlist[e.currentPlaying]\n if curplaying.LyricsId==0 { return }\n ra:=requestwrapper.RequestAccesser{Token: e.accessToken}\n parms:=map[string]string{\"lyrics_id\":strconv.FormatFloat(curplaying.LyricsId,'f',-1,64)}\n resp,err:=ra.MakeRequest(\"audio.getLyrics\",parms)\n if err!=nil {\n dialogboxes.ShowErrorDialog(err.Error())\n return\n }\n lyricsfield:=e.mainWindow.Root().ObjectByName(\"lyrics\")\n lyrics:=resp[\"response\"].(map[string]interface{})[\"text\"].(string)\n lyricsfield.Set(\"text\",lyrics)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"log\"\n\t\"strconv\"\n\t\"github.com/stvndall/languagetechstats/src/go/services/factors\"\n\t\"github.com/gorilla/mux\"\n)\nfunc main(){\n\trouter := mux.NewRouter().StrictSlash(true)\n\trouter.HandleFunc(\"/{numbers}\", factorise)\n\tlog.Fatal(http.ListenAndServe(\":2500\", router))\n}\n\n\n\nfunc factorise(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tnumber, err := strconv.Atoi(mux.Vars(r)[\"numbers\"])\n\tif(err != nil){\n\t\tfmt.Fprintf(w,\"%v\",err)\n\t\treturn\n\t}\n\tfmt.Fprintf(w, \"%v\",factors.PrimeFactors(number) )\n}"} {"input": "package oci\n\nimport \"io/fs\"\n\n\n\n\n\ntype dirInfo struct {\n\tfileInfo fs.FileInfo\n}\n\nfunc (di dirInfo) IsDir() bool {\n\treturn di.fileInfo.IsDir()\n}\n\n\n\nfunc (di dirInfo) Info() (fs.FileInfo, error) {\n\treturn di.fileInfo, nil\n}\n\nfunc (di dirInfo) Name() string {\n\treturn di.fileInfo.Name()\n}\n\n\n\nfunc fileInfoToDirEntry(info fs.FileInfo) fs.DirEntry {\n\tif info == nil {\n\t\treturn nil\n\t}\n\treturn dirInfo{fileInfo: info}\n}\n\nfunc (di dirInfo) Type() fs.FileMode ", "output": "{\n\treturn di.fileInfo.Mode().Type()\n}"} {"input": "package safepackets\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\n\t\"github.com/mark-rushakoff/go_tftpd/packets\"\n)\n\ntype SafeError struct {\n\tCode packets.ErrorCode\n\tMessage string\n}\n\nfunc NewFileNotFoundError() *SafeError {\n\treturn &SafeError{\n\t\tCode: packets.FileNotFound,\n\t\tMessage: \"File not found\",\n\t}\n}\n\nfunc NewAccessViolationError(message string) *SafeError {\n\treturn &SafeError{\n\t\tCode: packets.AccessViolation,\n\t\tMessage: message,\n\t}\n}\n\n\n\nfunc (e *SafeError) Equals(other *SafeError) bool {\n\treturn e.Code == other.Code && e.Message == other.Message\n}\n\nfunc (e *SafeError) Bytes() []byte {\n\tbuf := &bytes.Buffer{}\n\tbinary.Write(buf, binary.BigEndian, packets.ErrorOpcode)\n\tbinary.Write(buf, binary.BigEndian, e.Code)\n\tbuf.WriteString(e.Message)\n\tbuf.WriteByte(0)\n\treturn buf.Bytes()\n}\n\nfunc NewAncientAckError() *SafeError ", "output": "{\n\treturn &SafeError{\n\t\tCode: packets.Undefined,\n\t\tMessage: \"Received unexpectedly old Ack\",\n\t}\n}"} {"input": "package connlimit\n\nimport (\n\t\"testing\"\n\n\t\"github.com/codegangsta/cli\"\n\t\"github.com/timelinelabs/vulcand/plugin\"\n\t. \"gopkg.in/check.v1\"\n)\n\nfunc TestCL(t *testing.T) { TestingT(t) }\n\ntype ConnLimitSuite struct {\n}\n\nvar _ = Suite(&ConnLimitSuite{})\n\n\n\nfunc (s *ConnLimitSuite) TestSpecIsOK(c *C) {\n\tc.Assert(plugin.NewRegistry().AddSpec(GetSpec()), IsNil)\n}\n\nfunc (s *ConnLimitSuite) TestNewConnLimitSuccess(c *C) {\n\tcl, err := NewConnLimit(10, \"client.ip\")\n\tc.Assert(cl, NotNil)\n\tc.Assert(err, IsNil)\n\n\tc.Assert(cl.String(), Not(Equals), \"\")\n\n\tout, err := cl.NewHandler(nil)\n\tc.Assert(out, NotNil)\n\tc.Assert(err, IsNil)\n}\n\nfunc (s *ConnLimitSuite) TestNewConnLimitBadParams(c *C) {\n\t_, err := NewConnLimit(10, \"client ip\")\n\tc.Assert(err, NotNil)\n\n\t_, err = NewConnLimit(-10, \"client.ip\")\n\tc.Assert(err, NotNil)\n}\n\nfunc (s *ConnLimitSuite) TestNewConnLimitFromOther(c *C) {\n\tcl, err := NewConnLimit(10, \"client.ip\")\n\tc.Assert(cl, NotNil)\n\tc.Assert(err, IsNil)\n\n\tout, err := FromOther(*cl)\n\tc.Assert(err, IsNil)\n\tc.Assert(out, DeepEquals, cl)\n}\n\n\n\nfunc (s *ConnLimitSuite) TestNewConnLimitFromCli(c *C) ", "output": "{\n\tapp := cli.NewApp()\n\tapp.Name = \"test\"\n\texecuted := false\n\tapp.Action = func(ctx *cli.Context) {\n\t\texecuted = true\n\t\tout, err := FromCli(ctx)\n\t\tc.Assert(out, NotNil)\n\t\tc.Assert(err, IsNil)\n\n\t\tcl := out.(*ConnLimit)\n\t\tc.Assert(cl.Variable, Equals, \"client.ip\")\n\t\tc.Assert(cl.Connections, Equals, int64(10))\n\t}\n\tapp.Flags = CliFlags()\n\tapp.Run([]string{\"test\", \"--var=client.ip\", \"--connections=10\"})\n\tc.Assert(executed, Equals, true)\n}"} {"input": "package vaquita\n\nimport \"sync\"\n\ntype MapConfig struct {\n\tvalues map[string]string\n\tlock *sync.RWMutex\n\n\t*EventHandler\n}\n\nfunc NewEmptyMapConfig() *MapConfig {\n\treturn &MapConfig{\n\t\tvalues: make(map[string]string),\n\t\tlock: new(sync.RWMutex),\n\t\tEventHandler: NewEventHandler(),\n\t}\n}\n\nfunc NewMapConfig(values map[string]string) *MapConfig {\n\tcfg := NewEmptyMapConfig()\n\tfor k, v := range values {\n\t\tcfg.values[k] = v\n\t}\n\treturn cfg\n}\n\n\n\nfunc (c *MapConfig) setProperty(name, value string) bool {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\thasProperty := c.hasProperty(name)\n\tc.values[name] = value\n\treturn hasProperty\n}\n\nfunc (c *MapConfig) HasProperty(name string) bool {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\treturn c.hasProperty(name)\n}\n\nfunc (c *MapConfig) hasProperty(name string) bool {\n\t_, ok := c.values[name]\n\treturn ok\n}\n\nfunc (c *MapConfig) GetProperty(name string) (string, bool) {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\tv, ok := c.values[name]\n\treturn v, ok\n}\n\nfunc (c *MapConfig) RemoveProperty(name string) {\n\tremoved := c.removeProperty(name)\n\tif removed {\n\t\tc.Notify(NewChangeEvent(c, PropertyRemoved, name, \"\"))\n\t}\n}\n\nfunc (c *MapConfig) removeProperty(name string) bool {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\thasProperty := c.hasProperty(name)\n\tdelete(c.values, name)\n\treturn hasProperty\n}\n\nfunc (c *MapConfig) SetProperty(name, value string) ", "output": "{\n\tchanged := c.setProperty(name, value)\n\tvar event Event\n\tif changed {\n\t\tevent = PropertyChanged\n\t} else {\n\t\tevent = PropertySet\n\t}\n\tc.Notify(NewChangeEvent(c, event, name, value))\n}"} {"input": "package antibody\n\nimport (\n\t\"testing\"\n\n\t\"github.com/caarlos0/antibody/doubles\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestClonesValidRepo(t *testing.T) {\n\thome := doubles.TempHome()\n\tbundle := NewGitBundle(\"caarlos0/zsh-pg\", home)\n\terr := bundle.Download()\n\texpected := home + \"caarlos0-zsh-pg\"\n\n\tassert.Equal(t, expected, bundle.Folder())\n\tassert.NoError(t, err)\n\tassertBundledPlugins(t, 1, home)\n}\n\n\n\nfunc TestClonesInvalidRepo(t *testing.T) {\n\thome := doubles.TempHome()\n\terr := NewGitBundle(\"this-doesnt-exist\", home).Download()\n\tassert.Error(t, err)\n}\n\nfunc TestPullsRepo(t *testing.T) {\n\thome := doubles.TempHome()\n\tbundle := NewGitBundle(\"caarlos0/zsh-pg\", home)\n\tbundle.Download()\n\terr := bundle.Update()\n\tassert.NoError(t, err)\n}\n\nfunc TestSourceablesDotPluginZsh(t *testing.T) {\n\thome := doubles.TempHome()\n\tbundle := NewGitBundle(\"caarlos0/zsh-pg\", home)\n\tbundle.Download()\n\tsrcs := bundle.Sourceables()\n\tassert.Len(t, srcs, 1)\n}\n\nfunc TestSourceablesDotSh(t *testing.T) {\n\thome := doubles.TempHome()\n\tbundle := NewGitBundle(\"rupa/z\", home)\n\tbundle.Download()\n\tsrcs := bundle.Sourceables()\n\tassert.Len(t, srcs, 1)\n}\n\nfunc TestClonesValidRepoTwoTimes(t *testing.T) ", "output": "{\n\thome := doubles.TempHome()\n\tbundle := NewGitBundle(\"caarlos0/zsh-pg\", home)\n\tbundle.Download()\n\terr := bundle.Download()\n\texpected := home + \"caarlos0-zsh-pg\"\n\tassert.Equal(t, expected, bundle.Folder())\n\tassert.NoError(t, err)\n\tassertBundledPlugins(t, 1, home)\n}"} {"input": "package cursor\n\nimport (\n\t\"fmt\"\n\t\"github.com/autovelop/playthos\"\n)\n\n\n\nfunc init() ", "output": "{\n\tengine.RegisterPackage(&engine.Package{\"cursor\", []string{\"window_context\"}, []string{\"cursor_input\"}, []string{\"windows\", \"linux\", \"darwin\"}})\n\tfmt.Println(\"> Cursor: Initializing\")\n}"} {"input": "package profile\n\nimport (\n\t\"math/rand\"\n\t\"testing\"\n\t\"time\"\n\t\"unsafe\"\n\n\t\"github.com/pingcap/tidb/util/kvcache\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\n\n\ntype mockCacheKey struct {\n\thash []byte\n\tkey int64\n}\n\nfunc (mk *mockCacheKey) Hash() []byte {\n\tif mk.hash != nil {\n\t\treturn mk.hash\n\t}\n\tmk.hash = make([]byte, 8)\n\tfor i := uint(0); i < 8; i++ {\n\t\tmk.hash[i] = byte((mk.key >> ((i - 1) * 8)) & 0xff)\n\t}\n\treturn mk.hash\n}\n\nfunc newMockHashKey(key int64) *mockCacheKey {\n\treturn &mockCacheKey{\n\t\tkey: key,\n\t}\n}\n\nfunc getRandomString(l int) string {\n\tstr := \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\tbytes := []byte(str)\n\tresult := []byte{}\n\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tfor i := 0; i < l; i++ {\n\t\tresult = append(result, bytes[r.Intn(len(bytes))])\n\t}\n\treturn string(result)\n}\n\nfunc TestHeapProfileRecorder(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\tnum := 60000\n\tlru := kvcache.NewSimpleLRUCache(uint(num), 0, 0)\n\n\tkeys := make([]*mockCacheKey, num)\n\tfor i := 0; i < num; i++ {\n\t\tkeys[i] = newMockHashKey(int64(i))\n\t\tv := getRandomString(10)\n\t\tlru.Put(keys[i], v)\n\t}\n\tbytes, err := col.getFuncMemUsage(kvcache.ProfileName)\n\trequire.Nil(t, err)\n\n\tvalueSize := int(unsafe.Sizeof(getRandomString(10)))\n\tassert.LessOrEqual(t, int64(valueSize*num), bytes)\n\tfor _, k := range lru.Keys() {\n\t\tassert.Len(t, k.Hash(), 8)\n\t}\n\tfor _, v := range lru.Values() {\n\t\tassert.Len(t, v.(string), 10)\n\t}\n}"} {"input": "package models\n\n\ntype IssueLockOptions struct {\n\tDoer *User\n\tIssue *Issue\n\tReason string\n}\n\n\n\n\n\n\nfunc UnlockIssue(opts *IssueLockOptions) error {\n\treturn updateIssueLock(opts, false)\n}\n\nfunc updateIssueLock(opts *IssueLockOptions, lock bool) error {\n\tif opts.Issue.IsLocked == lock {\n\t\treturn nil\n\t}\n\n\topts.Issue.IsLocked = lock\n\tvar commentType CommentType\n\tif opts.Issue.IsLocked {\n\t\tcommentType = CommentTypeLock\n\t} else {\n\t\tcommentType = CommentTypeUnlock\n\t}\n\n\tsess := x.NewSession()\n\tdefer sess.Close()\n\tif err := sess.Begin(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := updateIssueCols(sess, opts.Issue, \"is_locked\"); err != nil {\n\t\treturn err\n\t}\n\n\tvar opt = &CreateCommentOptions{\n\t\tDoer: opts.Doer,\n\t\tIssue: opts.Issue,\n\t\tRepo: opts.Issue.Repo,\n\t\tType: commentType,\n\t\tContent: opts.Reason,\n\t}\n\tif _, err := createComment(sess, opt); err != nil {\n\t\treturn err\n\t}\n\n\treturn sess.Commit()\n}\n\nfunc LockIssue(opts *IssueLockOptions) error ", "output": "{\n\treturn updateIssueLock(opts, true)\n}"} {"input": "package restinspectorhandler\n\nimport (\n\tlog \"github.com/cihub/seelog\"\n\t. \"github.com/osrg/earthquake/earthquake/entity\"\n\t. \"github.com/osrg/earthquake/earthquake/inspectorhandler/restinspectorhandler/queue\"\n\t. \"github.com/osrg/earthquake/earthquake/signal\"\n)\n\n\n\nfunc sendEventToMain(entity *TransitionEntity, event Event) {\n\tlog.Debugf(\"Handler[%s]->Main: sending an event %s\", entity.ID, event)\n\tsentToEntityCh := make(chan bool)\n\tsentToMainCh := make(chan bool)\n\tgo func() {\n\t\tentity.EventToMain <- event\n\t\tsentToEntityCh <- true\n\t}()\n\tgo func() {\n\t\tmainReadyEntityCh <- entity\n\t\tsentToMainCh <- true\n\t}()\n\t<-sentToEntityCh\n\t<-sentToMainCh\n\tlog.Debugf(\"Handler[%s]->Main: sent event %s\", entity.ID, event)\n}\n\nfunc propagateActionFromMain(entity *TransitionEntity, queue *ActionQueue) {\n\tlog.Debugf(\"Handler[%s]<-Main: receiving an action\", entity.ID)\n\taction := <-entity.ActionFromMain\n\tlog.Debugf(\"Handler[%s]<-Main: received an action %s\", entity.ID, action)\n\tqueue.Put(action)\n}\n\nfunc registerNewEntity(entityID string) (*TransitionEntity, *ActionQueue, error) ", "output": "{\n\tlog.Debugf(\"Registering entity: %s\", entityID)\n\tentity := TransitionEntity{\n\t\tID: entityID,\n\t\tActionFromMain: make(chan Action),\n\t\tEventToMain: make(chan Event),\n\t}\n\tif err := RegisterTransitionEntity(&entity); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tqueue, err := RegisterNewQueue(entityID)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tgo func() {\n\t\tfor {\n\t\t\tpropagateActionFromMain(&entity, queue)\n\t\t}\n\t}()\n\tlog.Debugf(\"Registered entity: %s\", entityID)\n\treturn &entity, queue, nil\n}"} {"input": "package personal\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n)\n\ntype FriendsArray []Friend\n\n\n\ntype FriendsList struct {\n\tXMLName xml.Name `xml:\"oschina\"`\n\tFriends Friends `xml:\"friends\"`\n}\n\ntype Friends struct {\n\tFriendsArray FriendsArray `xml:\"friend\"`\n}\n\nfunc (self FriendsList) StringFriendsArray() (s string) {\n\treturn self.Friends.FriendsArray.String()\n}\n\ntype Friend struct {\n\tExpertise string `xml:\"expertise\"`\n\tName string `xml:\"name\"`\n\tUserId int `xml:\"userid\"`\n\tGender int `xml:\"gender\"` \n\tPortrait string `xml:\"portrait\"`\n}\n\nfunc (self Friend) String() (s string) {\n\tjson, _ := xml.Marshal(&self)\n\ts = string(json)\n\treturn\n}\n\nfunc (self FriendsArray) String() (s string) ", "output": "{\n\ts = \"[\"\n\ti := 0\n\tm := len(self)\n\tfor _, f := range self {\n\t\tt := fmt.Sprintf(\n\t\t\t`{\"expertise\":\"%s\", \"name\":\"%s\", \"userid\":%d, \"gender\":%d, \"portrait\" : \"%s\"}`,\n\t\t\tf.Expertise, f.Name, f.UserId, f.Gender, f.Portrait)\n\t\ts += t\n\t\tif i != m-1 {\n\t\t\ts += \",\"\n\t\t}\n\t\ti++\n\t}\n\ts += \"]\"\n\n\treturn\n}"} {"input": "package model\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"google.golang.org/protobuf/proto\"\n\t\"google.golang.org/protobuf/types/known/timestamppb\"\n\n\t\"go.chromium.org/luci/common/clock\"\n\tds \"go.chromium.org/luci/gae/service/datastore\"\n\n\tdm \"go.chromium.org/luci/dm/api/service/v1\"\n)\n\n\n\n\n\nfunc NewQuest(c context.Context, desc *dm.Quest_Desc) *Quest {\n\treturn &Quest{ID: desc.QuestID(), Desc: *desc, Created: clock.Now(c).UTC()}\n}\n\n\n\ntype Quest struct {\n\tID string `gae:\"$id\"`\n\n\tDesc dm.Quest_Desc `gae:\",noindex\"`\n\tBuiltBy TemplateInfo `gae:\",noindex\"`\n\n\tCreated time.Time `gae:\",noindex\"`\n}\n\n\nfunc (q *Quest) Equals(a *Quest) bool {\n\treturn q == a || (q.ID == a.ID &&\n\t\tproto.Equal(&q.Desc, &a.Desc) &&\n\t\tq.BuiltBy.Equals(a.BuiltBy) &&\n\t\tq.Created.Equal(a.Created))\n}\n\n\nfunc QueryAttemptsForQuest(c context.Context, qid string) *ds.Query {\n\tfrom := ds.MakeKey(c, \"Attempt\", qid+\"|\")\n\tto := ds.MakeKey(c, \"Attempt\", qid+\"~\")\n\treturn ds.NewQuery(\"Attempt\").Gt(\"__key__\", from).Lt(\"__key__\", to)\n}\n\n\nfunc (q *Quest) ToProto() *dm.Quest {\n\treturn &dm.Quest{\n\t\tId: dm.NewQuestID(q.ID),\n\t\tData: q.DataProto(),\n\t}\n}\n\n\n\n\nfunc (q *Quest) DataProto() *dm.Quest_Data ", "output": "{\n\tspec := make([]*dm.Quest_TemplateSpec, len(q.BuiltBy))\n\tfor i := range q.BuiltBy {\n\t\tspec[i] = &q.BuiltBy[i]\n\t}\n\n\treturn &dm.Quest_Data{\n\t\tCreated: timestamppb.New(q.Created),\n\t\tDesc: &q.Desc,\n\t\tBuiltBy: spec,\n\t}\n}"} {"input": "package console\n\nimport (\n\t\"github.com/cgrates/cgrates/apier/v1\"\n\t\"github.com/cgrates/cgrates/utils\"\n)\n\nfunc init() {\n\tc := &CmdRemoveBalance{\n\t\tname: \"balance_remove\",\n\t\trpcMethod: \"ApierV1.RemoveBalances\",\n\t}\n\tcommands[c.Name()] = c\n\tc.CommandExecuter = &CommandExecuter{c}\n}\n\n\ntype CmdRemoveBalance struct {\n\tname string\n\trpcMethod string\n\trpcParams *v1.AttrAddBalance\n\t*CommandExecuter\n}\n\n\n\nfunc (self *CmdRemoveBalance) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\nfunc (self *CmdRemoveBalance) RpcParams(reset bool) interface{} {\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrAddBalance{BalanceType: utils.MONETARY, Overwrite: false}\n\t}\n\treturn self.rpcParams\n}\n\nfunc (self *CmdRemoveBalance) PostprocessRpcParams() error {\n\treturn nil\n}\n\nfunc (self *CmdRemoveBalance) RpcResult() interface{} {\n\tvar s string\n\treturn &s\n}\n\nfunc (self *CmdRemoveBalance) Name() string ", "output": "{\n\treturn self.name\n}"} {"input": "package packer\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"testing\"\n\n\t\"golang.org/x/sync/errgroup\"\n)\n\n\n\n\n\nfunc TestProgressTracking_multi_open_close(t *testing.T) {\n\tvar bar *uiProgressBar\n\tg := errgroup.Group{}\n\n\tfor i := 0; i < 100; i++ {\n\t\tg.Go(func() error {\n\t\t\ttracker := bar.TrackProgress(\"file,\", 1, 42, ioutil.NopCloser(nil))\n\t\t\treturn tracker.Close()\n\t\t})\n\t}\n\tif err := g.Wait(); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestProgressTracking_races(t *testing.T) {\n\tvar bar *uiProgressBar\n\tg := errgroup.Group{}\n\n\tfor i := 0; i < 100; i++ {\n\t\tg.Go(func() error {\n\t\t\ttxt := []byte(\"foobarbaz dolores\")\n\t\t\tb := bytes.NewReader(txt)\n\t\t\ttracker := bar.TrackProgress(\"file,\", 1, 42, ioutil.NopCloser(b))\n\n\t\t\tfor i := 0; i < 42; i++ {\n\t\t\t\ttracker.Read([]byte(\"i\"))\n\t\t\t}\n\t\t\treturn tracker.Close()\n\t\t})\n\t}\n\n\tif err := g.Wait(); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestProgressTracking_open_close(t *testing.T) ", "output": "{\n\tvar bar *uiProgressBar\n\n\ttracker := bar.TrackProgress(\"1,\", 1, 42, ioutil.NopCloser(nil))\n\ttracker.Close()\n\n\ttracker = bar.TrackProgress(\"2,\", 1, 42, ioutil.NopCloser(nil))\n\ttracker.Close()\n}"} {"input": "package stack\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\n\t\"github.com/appcelerator/amp/docker/cli/cli/command/bundlefile\"\n\t\"github.com/pkg/errors\"\n\t\"github.com/spf13/pflag\"\n)\n\n\n\nfunc addBundlefileFlag(opt *string, flags *pflag.FlagSet) {\n\tflags.StringVar(opt, \"bundle-file\", \"\", \"Path to a Distributed Application Bundle file\")\n\tflags.SetAnnotation(\"bundle-file\", \"experimental\", nil)\n}\n\nfunc addRegistryAuthFlag(opt *bool, flags *pflag.FlagSet) {\n\tflags.BoolVar(opt, \"with-registry-auth\", false, \"Send registry authentication details to Swarm agents\")\n}\n\nfunc loadBundlefile(stderr io.Writer, namespace string, path string) (*bundlefile.Bundlefile, error) {\n\tdefaultPath := fmt.Sprintf(\"%s.dab\", namespace)\n\n\tif path == \"\" {\n\t\tpath = defaultPath\n\t}\n\tif _, err := os.Stat(path); err != nil {\n\t\treturn nil, errors.Errorf(\n\t\t\t\"Bundle %s not found. Specify the path with --file\",\n\t\t\tpath)\n\t}\n\n\tfmt.Fprintf(stderr, \"Loading bundle from %s\\n\", path)\n\treader, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer reader.Close()\n\n\tbundle, err := bundlefile.LoadFile(reader)\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"Error reading %s: %v\\n\", path, err)\n\t}\n\treturn bundle, err\n}\n\nfunc addComposefileFlag(opt *string, flags *pflag.FlagSet) ", "output": "{\n\tflags.StringVarP(opt, \"compose-file\", \"c\", \"\", \"Path to a Compose file\")\n\tflags.SetAnnotation(\"compose-file\", \"version\", []string{\"1.25\"})\n}"} {"input": "package engine\n\nimport \"fmt\"\nimport \"github.com/aws/amazon-ecs-agent/agent/api\"\n\ntype ContainerNotFound struct {\n\tTaskArn string\n\tContainerName string\n}\n\n\n\ntype DockerContainerChangeEvent struct {\n\tStatus api.ContainerStatus\n\n\tDockerContainerMetadata\n}\n\ntype DockerContainerMetadata struct {\n\tDockerId string\n\tExitCode *int\n\tPortBindings []api.PortBinding\n\tError error\n\tVolumes map[string]string\n}\n\n\n\ntype ListContainersResponse struct {\n\tDockerIds []string\n\tError error\n}\n\nfunc (cnferror ContainerNotFound) Error() string ", "output": "{\n\treturn fmt.Sprintf(\"Could not find container '%s' in task '%s'\", cnferror.ContainerName, cnferror.TaskArn)\n}"} {"input": "package time\n\nimport (\n\t\"fmt\"\n\t\"github.com/iotaledger/iota.go/account/deposit\"\n\t\"github.com/iotaledger/iota.go/account/oracle\"\n\t\"github.com/iotaledger/iota.go/account/timesrc\"\n\t\"time\"\n)\n\nconst dateFormat = \"2006-02-01 15:04:05\"\n\n\n\n\n\n\ntype timedecider struct {\n\ttimesource timesrc.TimeSource\n\tremainingTimeThreshold time.Duration\n}\n\nfunc (td *timedecider) Ok(conds *deposit.CDA) (bool, string, error) {\n\tnow, err := td.timesource.Time()\n\tif err != nil {\n\t\treturn false, \"\", err\n\t}\n\n\tif now.After(*conds.TimeoutAt) {\n\t\tmsg := fmt.Sprintf(\"conditions expired on %s, it's currently %s\", conds.TimeoutAt.Format(dateFormat), now.Format(dateFormat))\n\t\treturn false, msg, nil\n\t}\n\n\tif now.Add(td.remainingTimeThreshold).After(*conds.TimeoutAt) {\n\t\tformatted := conds.TimeoutAt.Format(dateFormat)\n\t\tnowFormatted := now.Add(td.remainingTimeThreshold).Format(dateFormat)\n\t\tmsg := fmt.Sprintf(\"conditions will have expired before the remaining time threshold (%s < %s)\", formatted, nowFormatted)\n\t\treturn false, msg, nil\n\t}\n\treturn true, \"\", nil\n}\n\nfunc NewTimeDecider(timesource timesrc.TimeSource, remainingTimeThreshold time.Duration) oracle.OracleSource ", "output": "{\n\treturn &timedecider{timesource, remainingTimeThreshold}\n}"} {"input": "package testing\n\nimport \"k8s.io/kubernetes/pkg/util/iptables\"\n\n\ntype fake struct{}\n\nfunc NewFake() *fake {\n\treturn &fake{}\n}\n\nfunc (*fake) EnsureChain(table iptables.Table, chain iptables.Chain) (bool, error) {\n\treturn true, nil\n}\n\nfunc (*fake) FlushChain(table iptables.Table, chain iptables.Chain) error {\n\treturn nil\n}\n\nfunc (*fake) DeleteChain(table iptables.Table, chain iptables.Chain) error {\n\treturn nil\n}\n\nfunc (*fake) EnsureRule(position iptables.RulePosition, table iptables.Table, chain iptables.Chain, args ...string) (bool, error) {\n\treturn true, nil\n}\n\nfunc (*fake) DeleteRule(table iptables.Table, chain iptables.Chain, args ...string) error {\n\treturn nil\n}\n\nfunc (*fake) IsIpv6() bool {\n\treturn false\n}\n\nfunc (*fake) Save(table iptables.Table) ([]byte, error) {\n\treturn make([]byte, 0), nil\n}\n\n\n\nfunc (*fake) Restore(table iptables.Table, data []byte, flush iptables.FlushFlag, counters iptables.RestoreCountersFlag) error {\n\treturn nil\n}\n\nfunc (*fake) RestoreAll(data []byte, flush iptables.FlushFlag, counters iptables.RestoreCountersFlag) error {\n\treturn nil\n}\nfunc (*fake) AddReloadFunc(reloadFunc func()) {}\n\nfunc (*fake) Destroy() {}\n\nvar _ = iptables.Interface(&fake{})\n\nfunc (*fake) SaveAll() ([]byte, error) ", "output": "{\n\treturn make([]byte, 0), nil\n}"} {"input": "package downloader\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/WhaleCoinOrg/WhaleCoin/core/types\"\n)\n\n\ntype peerDropFn func(id string)\n\n\ntype dataPack interface {\n\tPeerId() string\n\tItems() int\n\tStats() string\n}\n\n\ntype headerPack struct {\n\tpeerId string\n\theaders []*types.Header\n}\n\nfunc (p *headerPack) PeerId() string { return p.peerId }\nfunc (p *headerPack) Items() int { return len(p.headers) }\nfunc (p *headerPack) Stats() string { return fmt.Sprintf(\"%d\", len(p.headers)) }\n\n\ntype bodyPack struct {\n\tpeerId string\n\ttransactions [][]*types.Transaction\n\tuncles [][]*types.Header\n}\n\nfunc (p *bodyPack) PeerId() string { return p.peerId }\nfunc (p *bodyPack) Items() int {\n\tif len(p.transactions) <= len(p.uncles) {\n\t\treturn len(p.transactions)\n\t}\n\treturn len(p.uncles)\n}\nfunc (p *bodyPack) Stats() string { return fmt.Sprintf(\"%d:%d\", len(p.transactions), len(p.uncles)) }\n\n\ntype receiptPack struct {\n\tpeerId string\n\treceipts [][]*types.Receipt\n}\n\n\nfunc (p *receiptPack) Items() int { return len(p.receipts) }\nfunc (p *receiptPack) Stats() string { return fmt.Sprintf(\"%d\", len(p.receipts)) }\n\n\ntype statePack struct {\n\tpeerId string\n\tstates [][]byte\n}\n\nfunc (p *statePack) PeerId() string { return p.peerId }\nfunc (p *statePack) Items() int { return len(p.states) }\nfunc (p *statePack) Stats() string { return fmt.Sprintf(\"%d\", len(p.states)) }\n\nfunc (p *receiptPack) PeerId() string ", "output": "{ return p.peerId }"} {"input": "package parser\n\ntype sField struct {\n\tName string\n\tType string\n\tTag string\n\tStruct sStruct\n\tInitialName string\n\n\tattr bool\n\tpointer bool\n\tarray bool\n\trequired bool\n\tnillable bool\n}\n\ntype mapofFields map[string]sField\n\n\n\nfunc (s *sField) resolveName(i string) {\n\tif s.Name == \"\" {\n\t\treturn\n\t}\n\ts.InitialName = makeExported(normalize(removeNS(i)))\n\ts.Name = makeExported(lintName(normalize(removeNS(i))))\n}\n\nfunc (s *sField) resolveType() {\n\tif s.nillable && s.required {\n\t\ts.Type = toGoType(makeUnexported(lintName(removeNS(s.Type + \"ReqNil\"))))\n\t\treturn\n\t}\n\n\ttn := makeUnexported(lintName(removeNS(s.Type)))\n\tif s.array {\n\t\ts.Type = \"[]\" + toGoType(tn)\n\t\treturn\n\t}\n\tif s.pointer {\n\t\ts.Type = toGoPointerType(tn)\n\t\treturn\n\t}\n\ts.Type = toGoPointerType(tn)\n}\n\nfunc (s *sField) resolveTag() {\n\tif s.Name == \"\" {\n\t\treturn\n\t}\n\n\tif s.attr {\n\t\ts.Tag = \"`\" + `xml:\"` + s.Name + `,attr\"` + \"`\"\n\t\treturn\n\t}\n\n\ts.Tag = \"`\" + `xml:\"` + s.Name + `\"` + \"`\"\n}\n\nfunc (m mapofFields) add(i string, s sField) bool ", "output": "{\n\tif i == \"\" || s.Type == \"\" {\n\t\treturn false\n\t}\n\n\ts.resolveType()\n\ts.resolveTag()\n\ts.resolveName(i)\n\tm[s.Name] = s\n\n\treturn true\n}"} {"input": "package mqtt\n\nimport (\n\t\"encoding/binary\"\n\t\"encoding/json\"\n\t\"io\"\n)\n\ntype ConnackMessage struct {\n\tFixedHeader\n\tReserved uint8\n\tReturnCode uint8\n}\n\nfunc (self *ConnackMessage) decode(reader io.Reader) error {\n\tbinary.Read(reader, binary.BigEndian, &self.Reserved)\n\tbinary.Read(reader, binary.BigEndian, &self.ReturnCode)\n\n\treturn nil\n}\n\nfunc (self ConnackMessage) WriteTo(w io.Writer) (int64, error) {\n\tvar fsize = 2\n\tsize, err := self.FixedHeader.writeTo(fsize, w)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tbinary.Write(w, binary.BigEndian, self.Reserved)\n\tbinary.Write(w, binary.BigEndian, self.ReturnCode)\n\n\treturn int64(fsize) + size, nil\n}\n\n\n\nfunc (self *ConnackMessage) String() string ", "output": "{\n\tb, _ := json.Marshal(self)\n\treturn string(b)\n}"} {"input": "package x11\n\nimport (\n\t\"C\"\n\t\"unsafe\"\n)\n\ntype SelectionEvent C.XSelectionEvent\n\nfunc (evt *SelectionEvent) Requestor() Window {\n\treturn Window(evt.requestor)\n}\n\nfunc (evt *SelectionEvent) Selection() Atom {\n\treturn Atom(evt.selection)\n}\n\nfunc (evt *SelectionEvent) Target() Atom {\n\treturn Atom(evt.target)\n}\n\nfunc (evt *SelectionEvent) Property() Atom {\n\treturn Atom(evt.property)\n}\n\n\n\nfunc (evt *SelectionEvent) ToEvent() *Event {\n\treturn (*Event)(unsafe.Pointer(evt))\n}\n\nfunc (evt *SelectionEvent) When() C.Time ", "output": "{\n\treturn evt.time\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\n\t\"gopkg.in/pivo.v2/ws\"\n)\n\nconst websocketChatUri = `/`\n\ntype websocket struct {\n\tconn *ws.Conn\n}\n\nfunc (ws *websocket) OnClose(why error) error {\n\tchat.hub.Leave(ws.conn)\n\treturn nil\n}\n\nfunc (ws *websocket) OnBinaryRead(data []byte) error {\n\treturn ErrProtocolViolation\n}\n\n\n\nfunc (chat *Hub) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tconn := ws.DefaultConn()\n\tif err := conn.Upgrade(w, r, nil); err != nil {\n\t\tlog.Printf(\"websocket: %s: failed to upgrade: %s\",\n\t\t\tr.RemoteAddr, err)\n\t\treturn\n\t}\n\tgo conn.Sender()\n\tgo conn.Receiver(&websocket{conn})\n\tchat.sub <- conn\n}\n\nfunc init() {\n\thttp.Handle(websocketChatUri, chat)\n}\n\nfunc (ws *websocket) OnTextRead(text string) error ", "output": "{\n\tchat.pub <- ws.conn.TextMessage(formatMessage(ws.conn, text))\n\treturn nil\n}"} {"input": "package objects\n\nimport \"strings\"\n\nconst (\n\tPREFIX_FADERDATATYPE = \"application/fader.datatypes.\"\n\n\tInvalidObject ObjectType = \"\"\n\tBlobObject ObjectType = \"blob\"\n\tUserObject ObjectType = \"user\"\n)\n\n\n\ntype ObjectType string\n\nfunc (t ObjectType) String() string {\n\treturn string(t)\n}\n\n\n\n\n\ntype ContentType string\n\nvar (\n\tTUnknown ContentType = \"application/fader.dt.unknown\"\n\tTString ContentType = \"application/fader.dt.string\"\n\tTNumber ContentType = \"application/fader.dt.number\"\n\tTBool ContentType = \"application/fader.dt.bool\"\n\tTArray ContentType = \"application/fader.dt.array\"\n\tTMap ContentType = \"application/fader.dt.map\"\n\tTCustom ContentType = \"application/fader.dt.custom.\"\n)\n\nfunc TypeFrom(v interface{}) (t ContentType) {\n\tswitch v.(type) {\n\tcase float32, float64, int, int32, int64:\n\t\treturn TNumber\n\tcase string:\n\t\treturn TString\n\tcase bool:\n\t\treturn TBool\n\tcase []interface{}:\n\t\treturn TArray\n\tcase map[string]interface{}:\n\t\treturn TMap\n\t}\n\n\treturn TUnknown\n}\n\nfunc (t ContentType) String() string {\n\treturn string(t)\n}\n\nfunc (t ContentType) Valid() bool {\n\treturn strings.HasPrefix(t.String(), PREFIX_FADERDATATYPE)\n}\n\nfunc (t ContentType) Equal(v ContentType) bool {\n\treturn t == v\n}\n\nfunc (t ObjectType) Bytes() []byte ", "output": "{\n\treturn []byte(t.String())\n}"} {"input": "package minecraft\n\nimport (\n\t\"io\"\n\t\"github.com/LilyPad/GoLilyPad/packet\"\n)\n\ntype PacketServerLoginStart struct {\n\tName string\n}\n\nfunc NewPacketServerLoginStart(name string) (this *PacketServerLoginStart) {\n\tthis = new(PacketServerLoginStart)\n\tthis.Name = name\n\treturn\n}\n\n\n\ntype packetServerLoginStartCodec struct {\n\n}\n\nfunc (this *packetServerLoginStartCodec) Decode(reader io.Reader) (decode packet.Packet, err error) {\n\tpacketServerLoginStart := new(PacketServerLoginStart)\n\tpacketServerLoginStart.Name, err = packet.ReadString(reader)\n\tif err != nil {\n\t\treturn\n\t}\n\tdecode = packetServerLoginStart\n\treturn\n}\n\nfunc (this *packetServerLoginStartCodec) Encode(writer io.Writer, encode packet.Packet) (err error) {\n\tpacketServerLoginStart := encode.(*PacketServerLoginStart)\n\terr = packet.WriteString(writer, packetServerLoginStart.Name)\n\treturn\n}\n\nfunc (this *PacketServerLoginStart) Id() int ", "output": "{\n\treturn PACKET_SERVER_LOGIN_START\n}"} {"input": "package services\n\nimport (\n\t\"log\"\n\n\t\"cjdavis.me/elysium/library\"\n\t\"cjdavis.me/elysium/repositories\"\n)\n\ntype BookService struct {\n}\n\n\n\nfunc (self *BookService) GetAllBooks() []library.Book {\n\tbooks, err := repositories.GetBookRepository().GetAllBooks()\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\treturn books\n}\n\nfunc (self *BookService) GetBooksByAuthor(authorID int) []library.Book {\n\tbooks, err := repositories.GetBookRepository().GetBooksByAuthor(authorID)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\treturn books\n}\n\nfunc NewBookService() *BookService ", "output": "{\n\treturn &BookService{}\n}"} {"input": "package pg\n\nimport \"strings\"\n\nconst (\n\tcreateTmpl = `\n// Create%[1]s inserts an entry into DB\nfunc Create%[1]s(db cruderQueryRower, x %[2]s) (*%[2]s, error) {\n\tvar y %[2]s\n\terr := db.QueryRow(\n\t\t` + \"`\" + `INSERT INTO %s (%s) VALUES (%s)\n\t\tRETURNING %s` + \"`\" + `,\n\t\t%s,\n\t).Scan(%s)\n\n\treturn &y, err\n}\n`\n)\n\n\n\n\nfunc (g *PG) GenerateCreate() ", "output": "{\n\tg.GenerateType(typeQueryRowerInterface)\n\n\tvar suffix string\n\tif !g.SkipSuffix {\n\t\tsuffix = g.structModel\n\t}\n\n\tg.Printf(createTmpl,\n\t\tsuffix,\n\t\tg.structModel,\n\t\tg.TableName,\n\t\tstrings.Join(g.writeFieldDBNames(\"\"), \", \"),\n\t\tstrings.Join(g.placeholderStrings(len(g.writeFieldDBNames(\"\"))), \", \"),\n\t\tstrings.Join(g.readFieldDBNames(\"\"), \", \"),\n\t\tstrings.Join(g.writeFieldNames(\"x.\"), \", \"),\n\t\tstrings.Join(g.readFieldNames(\"&y.\"), \", \"),\n\t)\n}"} {"input": "package config\n\nimport (\n\t\"time\"\n\n\t\"github.com/mexisme/go-config/settings\"\n)\n\n\nfunc AddConfigItems(configKeys []string) {\n\tsettings.AddConfigItems(configKeys)\n}\n\n\nfunc AddConfigItemsWithPFlags(configKeys []string) error {\n\treturn settings.AddConfigItemsWithPFlags(configKeys)\n}\n\n\n\n\n\nfunc Get(key string) interface{} {\n\treturn settings.Get(key)\n}\n\n\nfunc GetBool(key string) bool {\n\treturn settings.GetBool(key)\n}\n\n\nfunc GetFloat64(key string) float64 {\n\treturn settings.GetFloat64(key)\n}\n\n\nfunc GetInt(key string) int {\n\treturn settings.GetInt(key)\n}\n\n\nfunc GetString(key string) string {\n\treturn settings.GetString(key)\n}\n\n\nfunc GetStringMap(key string) map[string]interface{} {\n\treturn settings.GetStringMap(key)\n}\n\n\nfunc GetStringMapString(key string) map[string]string {\n\treturn settings.GetStringMapString(key)\n}\n\n\nfunc GetStringSlice(key string) []string {\n\treturn settings.GetStringSlice(key)\n}\n\n\nfunc GetTime(key string) time.Time {\n\treturn settings.GetTime(key)\n}\n\n\nfunc GetDuration(key string) time.Duration {\n\treturn settings.GetDuration(key)\n}\n\n\nfunc IsSet(key string) bool {\n\treturn settings.IsSet(key)\n}\n\n\nfunc AllSettings() map[string]interface{} {\n\treturn settings.AllSettings()\n}\n\nfunc ApplyWith(key string, f func(interface{})) ", "output": "{\n\tsettings.ApplyWith(key, f)\n}"} {"input": "package chshare\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\n\ntype Logger struct {\n\tprefix string\n\tlogger *log.Logger\n\tInfo, Debug bool\n}\n\n\n\nfunc NewLoggerFlag(prefix string, flag int) *Logger {\n\tl := &Logger{\n\t\tprefix: prefix,\n\t\tlogger: log.New(os.Stdout, \"\", flag),\n\t\tInfo: false,\n\t\tDebug: false,\n\t}\n\treturn l\n}\n\nfunc (l *Logger) Infof(f string, args ...interface{}) {\n\tif l.Info {\n\t\tl.logger.Printf(l.prefix+\": \"+f, args...)\n\t}\n}\n\nfunc (l *Logger) Debugf(f string, args ...interface{}) {\n\tif l.Debug {\n\t\tl.logger.Printf(l.prefix+\": \"+f, args...)\n\t}\n}\n\nfunc (l *Logger) Errorf(f string, args ...interface{}) error {\n\treturn fmt.Errorf(l.prefix+\": \"+f, args...)\n}\n\nfunc (l *Logger) Fork(prefix string, args ...interface{}) *Logger {\n\targs = append([]interface{}{l.prefix}, args...)\n\tll := NewLogger(fmt.Sprintf(\"%s: \"+prefix, args...))\n\tll.Info = l.Info\n\tll.Debug = l.Debug\n\treturn ll\n}\n\nfunc (l *Logger) Prefix() string {\n\treturn l.prefix\n}\n\nfunc NewLogger(prefix string) *Logger ", "output": "{\n\treturn NewLoggerFlag(prefix, log.Ldate|log.Ltime)\n}"} {"input": "package frame\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com/go-git/go-git/v5/utils/merkletrie/noder\"\n)\n\n\n\ntype Frame struct {\n\tstack []noder.Noder\n}\n\ntype byName []noder.Noder\n\nfunc (a byName) Len() int { return len(a) }\nfunc (a byName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a byName) Less(i, j int) bool {\n\treturn strings.Compare(a[i].Name(), a[j].Name()) < 0\n}\n\n\nfunc New(n noder.Noder) (*Frame, error) {\n\tchildren, err := n.Children()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsort.Sort(sort.Reverse(byName(children)))\n\treturn &Frame{\n\t\tstack: children,\n\t}, nil\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (f *Frame) First() (noder.Noder, bool) {\n\tif f.Len() == 0 {\n\t\treturn nil, false\n\t}\n\n\ttop := f.Len() - 1\n\n\treturn f.stack[top], true\n}\n\n\n\nfunc (f *Frame) Drop() {\n\tif f.Len() == 0 {\n\t\treturn\n\t}\n\n\ttop := f.Len() - 1\n\tf.stack[top] = nil\n\tf.stack = f.stack[:top]\n}\n\n\nfunc (f *Frame) Len() int {\n\treturn len(f.stack)\n}\n\nfunc (f *Frame) String() string ", "output": "{\n\tvar buf bytes.Buffer\n\t_ = buf.WriteByte('[')\n\n\tsep := \"\"\n\tfor i := f.Len() - 1; i >= 0; i-- {\n\t\t_, _ = buf.WriteString(sep)\n\t\tsep = \", \"\n\t\t_, _ = buf.WriteString(fmt.Sprintf(\"%q\", f.stack[i].Name()))\n\t}\n\n\t_ = buf.WriteByte(']')\n\n\treturn buf.String()\n}"} {"input": "package rpc\n\nimport (\n\t\"cgl.tideland.biz/asserts\"\n\t\"github.com/mitchellh/packer/packer\"\n\t\"net/rpc\"\n\t\"testing\"\n)\n\ntype testHook struct {\n\trunCalled bool\n\trunUi packer.Ui\n}\n\n\n\nfunc TestHookRPC(t *testing.T) {\n\tassert := asserts.NewTestingAsserts(t, true)\n\n\th := new(testHook)\n\n\tserver := rpc.NewServer()\n\tRegisterHook(server, h)\n\taddress := serveSingleConn(server)\n\n\tclient, err := rpc.Dial(\"tcp\", address)\n\tassert.Nil(err, \"should be able to connect\")\n\n\thClient := Hook(client)\n\n\tui := &testUi{}\n\thClient.Run(\"foo\", ui, nil, 42)\n\tassert.True(h.runCalled, \"run should be called\")\n}\n\nfunc TestHook_Implements(t *testing.T) {\n\tassert := asserts.NewTestingAsserts(t, true)\n\n\tvar r packer.Hook\n\th := &hook{nil}\n\n\tassert.Implementor(h, &r, \"should be a Hook\")\n}\n\nfunc (h *testHook) Run(name string, ui packer.Ui, comm packer.Communicator, data interface{}) error ", "output": "{\n\th.runCalled = true\n\treturn nil\n}"} {"input": "package local\n\nimport (\n\t\"time\"\n\n\t\"github.com/prometheus/prometheus/util/testutil\"\n)\n\ntype testStorageCloser struct {\n\tstorage Storage\n\tdirectory testutil.Closer\n}\n\nfunc (t *testStorageCloser) Close() {\n\tt.storage.Stop()\n\tt.directory.Close()\n}\n\n\n\n\n\n\nfunc NewTestStorage(t testutil.T, encoding chunkEncoding) (*memorySeriesStorage, testutil.Closer) ", "output": "{\n\tDefaultChunkEncoding = encoding\n\tdirectory := testutil.NewTemporaryDirectory(\"test_storage\", t)\n\to := &MemorySeriesStorageOptions{\n\t\tMemoryChunks: 1000000,\n\t\tMaxChunksToPersist: 1000000,\n\t\tPersistenceRetentionPeriod: 24 * time.Hour * 365 * 100, \n\t\tPersistenceStoragePath: directory.Path(),\n\t\tCheckpointInterval: time.Hour,\n\t\tSyncStrategy: Adaptive,\n\t}\n\tstorage := NewMemorySeriesStorage(o)\n\tif err := storage.Start(); err != nil {\n\t\tdirectory.Close()\n\t\tt.Fatalf(\"Error creating storage: %s\", err)\n\t}\n\n\tcloser := &testStorageCloser{\n\t\tstorage: storage,\n\t\tdirectory: directory,\n\t}\n\n\treturn storage.(*memorySeriesStorage), closer\n}"} {"input": "package cleanpath\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"strings\"\n)\n\n\nfunc RemoveGoPath(path string) string {\n\tdirs := filepath.SplitList(os.Getenv(\"GOPATH\"))\n\tsort.Stable(longestFirst(dirs))\n\tfor _, dir := range dirs {\n\t\tsrcdir := filepath.Join(dir, \"src\")\n\t\trel, err := filepath.Rel(srcdir, path)\n\t\tif err == nil && !strings.HasPrefix(rel, \"..\"+string(filepath.Separator)) {\n\t\t\treturn rel\n\t\t}\n\t}\n\treturn path\n}\n\ntype longestFirst []string\n\n\nfunc (strs longestFirst) Less(i, j int) bool { return len(strs[i]) > len(strs[j]) }\nfunc (strs longestFirst) Swap(i, j int) { strs[i], strs[j] = strs[j], strs[i] }\n\nfunc (strs longestFirst) Len() int ", "output": "{ return len(strs) }"} {"input": "package text\n\nimport \"fmt\"\n\nconst (\n\tredCode = \"\\x1b[31m\"\n\tgreenCode = \"\\x1b[32m\"\n\tyellowCode = \"\\x1b[33m\"\n\tblueCode = \"\\x1b[34m\"\n\tmagentaCode = \"\\x1b[35m\"\n\tCyanCode = \"\\x1b[36m\"\n\tboldCode = \"\\x1b[1m\"\n\n\tResetCode = \"\\x1b[0m\"\n)\n\n\nvar UseColor = true\n\nfunc stylize(startCode, in string) string {\n\tif UseColor {\n\t\treturn startCode + in + ResetCode\n\t}\n\n\treturn in\n}\n\nfunc Red(in string) string {\n\treturn stylize(redCode, in)\n}\n\n\n\nfunc yellow(in string) string {\n\treturn stylize(yellowCode, in)\n}\n\nfunc Cyan(in string) string {\n\treturn stylize(CyanCode, in)\n}\n\nfunc Magenta(in string) string {\n\treturn stylize(magentaCode, in)\n}\n\nfunc Blue(in string) string {\n\treturn stylize(blueCode, in)\n}\n\nfunc Bold(in string) string {\n\treturn stylize(boldCode, in)\n}\n\n\n\nfunc ColorHash(name string) (output string) {\n\tif !UseColor {\n\t\treturn name\n\t}\n\n\tvar hash uint = 5381\n\n\tfor i := 0; i < len(name); i++ {\n\t\thash = uint(name[i]) + ((hash << 5) + (hash))\n\t}\n\n\treturn fmt.Sprintf(\"\\x1b[%dm%s\\x1b[0m\", hash%6+31, name)\n}\n\nfunc Green(in string) string ", "output": "{\n\treturn stylize(greenCode, in)\n}"} {"input": "package servicecontrol\n\nimport (\n\t\"log\"\n\t\"os\"\n)\n\nvar (\n\tsshServiceName = \"ssh\"\n\tdisableSshFilename = \"/etc/ssh/sshd_not_to_be_run\"\n)\n\ntype SshService struct {\n\tdefaults *ServiceControlSettings\n}\n\nfunc getSshSettings() *ServiceControlSettings {\n\tis_enabled := true\n\tinfo, _ := os.Stat(disableSshFilename)\n\tif info != nil {\n\t\tis_enabled = false\n\t}\n\n\treturn &ServiceControlSettings{\n\t\tEnabled: is_enabled,\n\t}\n}\n\nfunc NewSshService() *SshService {\n\treturn &SshService{\n\t\tdefaults: getSshSettings(),\n\t}\n}\n\nfunc (s *SshService) IsAvailable() bool {\n\treturn true\n}\n\nfunc (s *SshService) GetDefaults() *ServiceControlSettings {\n\treturn s.defaults\n}\n\nfunc (s *SshService) ApplySettings(settings *ServiceControlSettings) error {\n\tvar action string\n\trunning, statusErr := isServiceRunning(sshServiceName)\n\tif settings.Enabled {\n\t\tif running && statusErr == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\taction = \"start\"\n\t\tif err := removeFile(disableSshFilename); err != nil {\n\t\t\tlog.Println(\"Could not enable ssh service\", err)\n\t\t}\n\t} else {\n\t\tif !running && statusErr == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\taction = \"stop\"\n\t\tif err := touchFile(disableSshFilename); err != nil {\n\t\t\tlog.Println(\"Could not disable ssh service\", err)\n\t\t}\n\t}\n\n\treturn runServiceCommand(sshServiceName, action)\n}\n\n\n\nfunc init() {\n\tRegisterService(\"ssh\", NewSshService())\n}\n\nfunc (s *SshService) QuerySettings() (*ServiceControlSettings, error) ", "output": "{\n\treturn getSshSettings(), nil\n}"} {"input": "package in\n\nimport (\n\t\"github.com/hashicorp/go-version\"\n\t\"github.com/jamiemonserrate/bintray-resource/bintrayresource\"\n)\n\ntype InRequest struct {\n\tSource bintrayresource.Source `json:\"source\"`\n\tRawVersion bintrayresource.Version `json:\"version\"`\n}\n\ntype InResponse struct {\n\tVersion bintrayresource.Version\n\tMetadata []bintrayresource.Metadata\n}\n\n\n\nfunc (inRequest *InRequest) IsValid() (bool, string) ", "output": "{\n\tif isValid, errMssg := inRequest.Source.IsValid(); !isValid {\n\t\treturn false, errMssg\n\t}\n\tif _, err := version.NewVersion(inRequest.RawVersion.Number); err != nil {\n\t\treturn false, err.Error()\n\t}\n\n\treturn true, \"\"\n}"} {"input": "package servicecontrol\n\nimport (\n\t\"log\"\n\t\"os\"\n)\n\nvar (\n\tsshServiceName = \"ssh\"\n\tdisableSshFilename = \"/etc/ssh/sshd_not_to_be_run\"\n)\n\ntype SshService struct {\n\tdefaults *ServiceControlSettings\n}\n\nfunc getSshSettings() *ServiceControlSettings {\n\tis_enabled := true\n\tinfo, _ := os.Stat(disableSshFilename)\n\tif info != nil {\n\t\tis_enabled = false\n\t}\n\n\treturn &ServiceControlSettings{\n\t\tEnabled: is_enabled,\n\t}\n}\n\n\n\nfunc (s *SshService) IsAvailable() bool {\n\treturn true\n}\n\nfunc (s *SshService) GetDefaults() *ServiceControlSettings {\n\treturn s.defaults\n}\n\nfunc (s *SshService) ApplySettings(settings *ServiceControlSettings) error {\n\tvar action string\n\trunning, statusErr := isServiceRunning(sshServiceName)\n\tif settings.Enabled {\n\t\tif running && statusErr == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\taction = \"start\"\n\t\tif err := removeFile(disableSshFilename); err != nil {\n\t\t\tlog.Println(\"Could not enable ssh service\", err)\n\t\t}\n\t} else {\n\t\tif !running && statusErr == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\taction = \"stop\"\n\t\tif err := touchFile(disableSshFilename); err != nil {\n\t\t\tlog.Println(\"Could not disable ssh service\", err)\n\t\t}\n\t}\n\n\treturn runServiceCommand(sshServiceName, action)\n}\n\nfunc (s *SshService) QuerySettings() (*ServiceControlSettings, error) {\n\treturn getSshSettings(), nil\n}\n\nfunc init() {\n\tRegisterService(\"ssh\", NewSshService())\n}\n\nfunc NewSshService() *SshService ", "output": "{\n\treturn &SshService{\n\t\tdefaults: getSshSettings(),\n\t}\n}"} {"input": "package peco\n\nimport \"github.com/nsf/termbox-go\"\n\n\n\nfunc (t Termbox) PostInit() error ", "output": "{\n\ttermbox.SetInputMode(termbox.InputEsc | termbox.InputAlt)\n\n\treturn nil\n}"} {"input": "package dax\n\n\ntype Grapher interface {\n\tGetParent() Grapher\n\tAddChild(child Grapher)\n\tGetChildren() []Grapher\n}\n\ntype nodeStack struct {\n\tnodes []Grapher\n}\n\nfunc (s *nodeStack) Init() {\n\ts.nodes = make([]Grapher, 0, 16)\n}\n\nfunc (s *nodeStack) Empty() bool {\n\treturn len(s.nodes) == 0\n}\n\n\n\nfunc (s *nodeStack) Pop() Grapher {\n\ti := len(s.nodes) - 1\n\tn := s.nodes[i]\n\ts.nodes[i] = nil\n\ts.nodes = s.nodes[:i]\n\treturn n\n}\n\ntype SceneGraph struct {\n\tNode\n}\n\nfunc NewSceneGraph() *SceneGraph {\n\tsg := new(SceneGraph)\n\tsg.Init()\n\treturn sg\n}\n\nfunc (sg *SceneGraph) Init() {\n\tsg.Node.Init()\n}\n\nfunc (sg *SceneGraph) updateWorldTransform() {\n\tsg.Node.updateWorldTransform(false)\n}\n\nfunc (sg *SceneGraph) Update(time float64) {\n\tsg.updateWorldTransform()\n}\n\n\nfunc (sg *SceneGraph) Traverse() <-chan Grapher {\n\tch := make(chan Grapher)\n\n\tgo func() {\n\t\tvar stack nodeStack\n\n\t\tstack.Init()\n\t\tstack.Push(sg)\n\n\t\tfor !stack.Empty() {\n\t\t\tn := stack.Pop()\n\t\t\tch <- n\n\t\t\tchildren := n.GetChildren()\n\t\t\tfor i := len(children) - 1; i >= 0; i-- {\n\t\t\t\tstack.Push(children[i])\n\t\t\t}\n\t\t}\n\t\tclose(ch)\n\t}()\n\n\treturn ch\n}\n\nfunc (sg *SceneGraph) Draw(fb Framebuffer) {\n\tfb.render().drawSceneGraph(fb, sg)\n}\n\nfunc (s *nodeStack) Push(n Grapher) ", "output": "{\n\ts.nodes = append(s.nodes, n)\n}"} {"input": "package types\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\n\n\nfunc scanMapStringStringValue(v reflect.Value, rd Reader, n int) error {\n\tm, err := scanMapStringString(rd, n)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tv.Set(reflect.ValueOf(m))\n\treturn nil\n}\n\nfunc scanMapStringString(rd Reader, n int) (map[string]string, error) {\n\tif n == -1 {\n\t\treturn nil, nil\n\t}\n\n\tp := newHstoreParser(rd)\n\tm := make(map[string]string)\n\tfor {\n\t\tkey, err := p.NextKey()\n\t\tif err != nil {\n\t\t\tif err == errEndOfHstore {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvalue, err := p.NextValue()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tm[string(key)] = string(value)\n\t}\n\treturn m, nil\n}\n\nfunc HstoreScanner(typ reflect.Type) ScannerFunc ", "output": "{\n\tif typ.Key() == stringType && typ.Elem() == stringType {\n\t\treturn scanMapStringStringValue\n\t}\n\treturn func(v reflect.Value, rd Reader, n int) error {\n\t\treturn fmt.Errorf(\"pg.Hstore(unsupported %s)\", v.Type())\n\t}\n}"} {"input": "package bloomfilter\n\nimport (\n\t\"testing\"\n)\n\n\n\n\nfunc Benchmark_Add(b *testing.B) {\n\tb.ReportAllocs()\n\n\tloadStrings := []string{\n\t\t\"cat\", \"dog\", \"mate\", \"frog\", \"moose\",\n\t\t\"el capitan\", \"spruce goose\"}\n\n\tf := NewBloomFilter(15)\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\tfor _, j := range loadStrings {\n\t\t\tf.Add(j)\n\t\t}\n\t}\n}\n\nfunc Benchmark_Exists(b *testing.B) {\n\tb.ReportAllocs()\n\n\tcheckStrings := []string{\n\t\t\"klingon\", \"frog\", \"donkey\",\n\t\t\"tame\", \"spruce goose\", \"light speed\",\n\t}\n\n\tf := NewBloomFilter(15)\n\n\tloadStrings := []string{\n\t\t\"cat\", \"dog\", \"mate\", \"frog\", \"moose\",\n\t\t\"el capitan\", \"spruce goose\"}\n\n\tfor _, j := range loadStrings {\n\t\tf.Add(j)\n\t}\n\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\tfor _, j := range checkStrings {\n\t\t\t_ = f.Exists(j)\n\t\t}\n\t}\n\n}\n\nfunc Test_Exists(t *testing.T) ", "output": "{\n\tloadStrings := []string{\n\t\t\"cat\", \"dog\", \"mate\", \"frog\", \"moose\",\n\t\t\"el capitan\", \"spruce goose\"}\n\n\ttype TestCase struct {\n\t\tInput string\n\t\tExpected bool\n\t}\n\n\ttestcases := []TestCase{\n\t\t{\"klingon\", false},\n\t\t{\"frog\", true},\n\t\t{\"donkey\", true},\n\t\t{\"tame\", true},\n\t\t{\"spruce goose\", true},\n\t\t{\"light speed\", false},\n\t}\n\n\tb := NewBloomFilter(15)\n\tfor _, j := range loadStrings {\n\t\tb.Add(j)\n\t}\n\n\tfor _, j := range testcases {\n\t\tactual := b.Exists(j.Input)\n\t\tif actual != j.Expected {\n\t\t\tt.Error(\"\\nExpected:\", j.Expected, \"\\nGot:\", actual, \"\\nFor:\", j.Input)\n\t\t}\n\t}\n}"} {"input": "package registry\n\nimport (\n \"github.com/twitchyliquid64/CNC/plugin/exec\"\n)\n\n\nvar dispatchMethod func(string, interface{})bool = nil\nvar deregisterPluginMethod func (plugin *exec.Plugin) = nil\n\n\n\nfunc SetupDeregisterMethod(in func (plugin *exec.Plugin)){\n deregisterPluginMethod = in\n}\n\nfunc DeregisterPluginMethod(plugin *exec.Plugin){\n if deregisterPluginMethod == nil{\n panic(\"deregisterPluginMethod == nil\")\n }\n deregisterPluginMethod(plugin)\n}\n\nfunc DispatchEvent(typ string, data interface{})bool{\n if dispatchMethod != nil {\n return dispatchMethod(typ, data)\n }\n return false\n}\n\nfunc SetupDispatchMethod(in func(string, interface{})bool) ", "output": "{\n dispatchMethod = in\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/gorilla/mux\"\n\t\"net/http\"\n)\n\n\n\nfunc TestIndex(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintln(w, \"Test Index!\")\n\n\ttodos := Todos{\n\t\tTodo{Name: \"Write presentation\"},\n\t\tTodo{Name: \"Host meetup\"},\n\t}\n\n\tif err := json.NewEncoder(w).Encode(todos); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc TestShow(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\ttestId := vars[\"testId\"]\n\tfmt.Fprintln(w, \"Test show:\", testId)\n}\n\nfunc Index(w http.ResponseWriter, r *http.Request) ", "output": "{\n\n\tfmt.Fprintln(w, \"Welcome!\")\n}"} {"input": "package web\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"github.com/hellofresh/janus/pkg/render\"\n\tlog \"github.com/sirupsen/logrus\"\n)\n\n\n\n\n\nfunc RedirectHTTPS(port int) http.HandlerFunc {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\thost, _, _ := net.SplitHostPort(req.Host)\n\n\t\ttarget := url.URL{\n\t\t\tScheme: \"https\",\n\t\t\tHost: fmt.Sprintf(\"%s:%v\", host, port),\n\t\t\tPath: req.URL.Path,\n\t\t}\n\t\tif len(req.URL.RawQuery) > 0 {\n\t\t\ttarget.RawQuery += \"?\" + req.URL.RawQuery\n\t\t}\n\t\tlog.Printf(\"redirect to: %s\", target.String())\n\t\thttp.Redirect(w, req, target.String(), http.StatusTemporaryRedirect)\n\t})\n}\n\nfunc Home() http.HandlerFunc ", "output": "{\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\trender.JSON(w, http.StatusOK, \"Welcome to Janus\")\n\t}\n}"} {"input": "package cpf\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\nfunc Valid(digits string) (bool, error) {\n\treturn valid(digits)\n}\n\nfunc sanitize(data string) string {\n\tdata = strings.Replace(data, \".\", \"\", -1)\n\tdata = strings.Replace(data, \"-\", \"\", -1)\n\treturn data\n}\n\nfunc valid(data string) (bool, error) {\n\tdata = sanitize(data)\n\n\tif len(data) != 11 {\n\t\treturn false, errors.New(\"Invalid length\")\n\t}\n\n\tif strings.Contains(blacklist, data) || !check(data) {\n\t\treturn false, errors.New(\"Invalid value\")\n\t}\n\n\treturn true, nil\n}\n\nconst blacklist = `00000000000\n11111111111\n22222222222\n33333333333\n44444444444\n55555555555\n66666666666\n77777777777\n88888888888\n99999999999\n12345678909`\n\nfunc stringToIntSlice(data string) (res []int) {\n\tfor _, d := range data {\n\t\tx, err := strconv.Atoi(string(d))\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tres = append(res, x)\n\t}\n\treturn\n}\n\n\n\nfunc check(data string) bool {\n\treturn checkEach(data, 9) && checkEach(data, 10)\n}\n\nfunc checkEach(data string, n int) bool {\n\tfinal := verify(stringToIntSlice(data), n)\n\n\tx, err := strconv.Atoi(string(data[n]))\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn final == x\n}\n\nfunc verify(data []int, n int) int ", "output": "{\n\tvar total int\n\n\tfor i := 0; i < n; i++ {\n\t\ttotal += data[i] * (n + 1 - i)\n\t}\n\n\ttotal = total % 11\n\tif total < 2 {\n\t\treturn 0\n\t}\n\treturn 11 - total\n}"} {"input": "package ocvp\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype ListWorkRequestsRequest struct {\n\n\tCompartmentId *string `mandatory:\"true\" contributesTo:\"query\" name:\"compartmentId\"`\n\n\tResourceId *string `mandatory:\"false\" contributesTo:\"query\" name:\"resourceId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tPage *string `mandatory:\"false\" contributesTo:\"query\" name:\"page\"`\n\n\tLimit *int `mandatory:\"false\" contributesTo:\"query\" name:\"limit\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request ListWorkRequestsRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request ListWorkRequestsRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request ListWorkRequestsRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\n\n\n\ntype ListWorkRequestsResponse struct {\n\n\tRawResponse *http.Response\n\n\tWorkRequestCollection `presentIn:\"body\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n\n\tOpcNextPage *string `presentIn:\"header\" name:\"opc-next-page\"`\n}\n\nfunc (response ListWorkRequestsResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\nfunc (response ListWorkRequestsResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ListWorkRequestsRequest) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package main\n\nimport (\n\t\"math\"\n\t\"sort\"\n)\n\ntype NaiveSieve struct {\n\tsieve map[int]bool\n}\n\n\n\nfunc (self *NaiveSieve) Contains(n int) bool {\n\t_, ok := self.sieve[n]\n\treturn ok\n}\n\nfunc (self *NaiveSieve) Primes() []int {\n\tprimes := make([]int, 0, len(self.sieve))\n\tfor n, _ := range self.sieve {\n\t\tprimes = append(primes, n)\n\t}\n\tsort.Ints(primes)\n\treturn primes\n}\n\nfunc IsNaivePrime(n int) bool {\n\tswitch {\n\tcase n == 1:\n\t\treturn false\n\tcase n == 2:\n\t\treturn true\n\tcase n%2 == 0:\n\t\treturn false\n\t}\n\n\tlimit := int(math.Sqrt(float64(n)))\n\n\tfor i := 3; i <= limit; i += 2 {\n\t\tif n%i == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc NewNaiveSieve(limit int) NaiveSieve ", "output": "{\n\n\tprimes := make(map[int]bool)\n\n\tprimes[2] = true\n\n\tfor n := 3; n < limit; n += 2 {\n\t\tif IsNaivePrime(n) {\n\t\t\tprimes[n] = true\n\t\t}\n\t}\n\n\treturn NaiveSieve{primes}\n}"} {"input": "package editor\n\nimport (\n\t\"math\"\n\n\t\"github.com/therecipe/qt/gui\"\n)\n\n\ntype Font struct {\n\tfontNew *gui.QFont\n\tfontMetrics *gui.QFontMetricsF\n\tdefaultFont *gui.QFont\n\tdefaultFontMetrics *gui.QFontMetricsF\n\twidth int\n\ttruewidth float64\n\tascent float64\n\theight int\n\tlineHeight int\n\tlineSpace int\n\tshift int\n}\n\nfunc fontSizeNew(font *gui.QFont) (int, int, float64, float64) {\n\tfontMetrics := gui.NewQFontMetricsF(font)\n\th := fontMetrics.Height()\n\tw := fontMetrics.Width(\"W\")\n\tascent := fontMetrics.Ascent()\n\twidth := int(math.Ceil(w))\n\theight := int(math.Ceil(h))\n\treturn width, height, w, ascent\n}\n\n\n\nfunc (f *Font) change(family string, size int) {\n\tf.fontNew.SetFamily(family)\n\tf.fontNew.SetPointSize(size)\n\tf.fontMetrics = gui.NewQFontMetricsF(f.fontNew)\n\twidth, height, truewidth, ascent := fontSizeNew(f.fontNew)\n\tf.width = width\n\tf.height = height\n\tf.truewidth = truewidth\n\tf.lineHeight = height + f.lineSpace\n\tf.ascent = ascent\n\tf.shift = int(float64(f.lineSpace)/2 + ascent)\n}\n\nfunc (f *Font) changeLineSpace(lineSpace int) {\n\tf.lineSpace = lineSpace\n\tf.lineHeight = f.height + lineSpace\n\tf.shift = int(float64(lineSpace)/2 + f.ascent)\n}\n\nfunc initFontNew(family string, size int, lineSpace int) *Font ", "output": "{\n\tfont := gui.NewQFont2(family, size, int(gui.QFont__Normal), false)\n\twidth, height, truewidth, ascent := fontSizeNew(font)\n\tdefaultFont := gui.NewQFont()\n\treturn &Font{\n\t\tfontNew: font,\n\t\tfontMetrics: gui.NewQFontMetricsF(font),\n\t\tdefaultFont: defaultFont,\n\t\tdefaultFontMetrics: gui.NewQFontMetricsF(defaultFont),\n\t\twidth: width,\n\t\ttruewidth: truewidth,\n\t\theight: height,\n\t\tlineHeight: height + lineSpace,\n\t\tlineSpace: lineSpace,\n\t\tshift: int(float64(lineSpace)/2 + ascent),\n\t\tascent: ascent,\n\t}\n}"} {"input": "package gluster\n\nimport (\n\t\"testing\"\n\n\t\"github.com/jarcoal/httpmock\"\n)\n\nfunc init() {\n\tExecRunner = TestRunner{}\n}\n\nfunc TestGetMountPath_FirstVolume(t *testing.T) {\n\tBasePath = \"/gluster/project\"\n\tmountPath := getMountPath(\"vol_some-project_pv1\")\n\tequals(t, \"/gluster/project/some-project/pv1\", mountPath)\n}\n\nfunc TestGetMountPath_SecondVolume(t *testing.T) {\n\tBasePath = \"/gluster/project\"\n\tmountPath := getMountPath(\"vol_another-project_pv2\")\n\tequals(t, \"/gluster/project/another-project/pv2\", mountPath)\n}\n\nfunc TestDeleteVolume_Empty(t *testing.T) {\n\terr := deleteVolume(\"\")\n\tassert(t, err != nil, \"Not all input values provided\")\n}\n\nfunc TestDeleteGlusterVolume(t *testing.T) {\n\tcommands = nil\n\tdeleteGlusterVolume(\"vol_my-project_pv1\")\n\tequals(t, \"bash -c gluster volume stop vol_my-project_pv1 --mode=script\", commands[0])\n\tequals(t, \"bash -c gluster volume delete vol_my-project_pv1 --mode=script\", commands[1])\n}\n\n\n\nfunc TestDeleteLvOnOtherServers(t *testing.T) {\n\thttpmock.Activate()\n\tdefer httpmock.DeactivateAndReset()\n\n\thttpmock.RegisterResponder(\"POST\", \"http://192.168.125.236:0/sec/lv/delete\",\n\t\thttpmock.NewStringResponder(200, \"\"))\n\n\toutput = []string{\"Hostname: 192.168.125.236\"}\n\n\tdeleteLvOnOtherServers(\"vol_my-project_pv1\")\n\n\tequals(t, 1, httpmock.GetTotalCallCount())\n}\n\nfunc TestDeleteLvLocally(t *testing.T) ", "output": "{\n\tcommands = nil\n\tBasePath = \"/gluster/project\"\n\tVgName = \"vgname\"\n\tdeleteLvLocally(\"vol_my-project_pv1\")\n\tequals(t, \"bash -c sed -i '\\\\#/dev/vgname/lv_my-project_pv1#d' /etc/fstab\", commands[0])\n\tequals(t, \"bash -c umount /gluster/project/my-project/pv1\", commands[1])\n\tequals(t, \"bash -c lvremove --yes /dev/vgname/lv_my-project_pv1\", commands[2])\n\tequals(t, \"bash -c rmdir --parents --ignore-fail-on-non-empty /gluster/project/my-project/pv1\", commands[3])\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc main() {\n\n\tnextInt := intSeq()\n\n\tfmt.Println(nextInt())\n\tfmt.Println(nextInt())\n\tfmt.Println(nextInt())\n\n\tnewInts := intSeq()\n\tfmt.Println(newInts())\n}\n\nfunc intSeq() func() int ", "output": "{\n\ti := 0\n\treturn func() int {\n\t\ti += 1\n\t\treturn i\n\t}\n}"} {"input": "package validator\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\tga4gh \"github.com/googlegenomics/ga4gh-identity\"\n)\n\n\n\n\ntype Or []ga4gh.Validator\n\n\n\n\nfunc (or Or) Validate(ctx context.Context, identity *ga4gh.Identity) (bool, error) {\n\tfor i, v := range or {\n\t\tok, err := v.Validate(ctx, identity)\n\t\tif err != nil {\n\t\t\treturn false, fmt.Errorf(\"nested validator at index %d: %v\", i, err)\n\t\t}\n\t\tif ok {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}\n\n\n\n\ntype And []ga4gh.Validator\n\n\n\n\n\nfunc (and And) Validate(ctx context.Context, identity *ga4gh.Identity) (bool, error) ", "output": "{\n\tfor i, v := range and {\n\t\tok, err := v.Validate(ctx, identity)\n\t\tif err != nil {\n\t\t\treturn false, fmt.Errorf(\"nested validator at index %d: %v\", i, err)\n\t\t}\n\t\tif !ok {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\treturn true, nil\n}"} {"input": "package money_test\n\nimport (\n\t\"github.com/reiver/go-money\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestUSDNickel(t *testing.T) {\n\n\tvar expected money.USD = money.USDCents(5)\n\tvar actual money.USD = money.USDNickel()\n\n\tif expected != actual {\n\t\tt.Error(\"The actual value is not equal to the expected value.\")\n\t\tt.Logf(\"EXPECTED: %q (%#v)\", expected, expected)\n\t\tt.Logf(\"ACTUAL: %q (%#v)\", actual, actual)\n\t\treturn\n\t}\n}\n\nfunc TestCADNickel(t *testing.T) ", "output": "{\n\n\tvar expected money.CAD = money.CADCents(5)\n\tvar actual money.CAD = money.CADNickel()\n\n\tif expected != actual {\n\t\tt.Error(\"The actual value is not equal to the expected value.\")\n\t\tt.Logf(\"EXPECTED: %q (%#v)\", expected, expected)\n\t\tt.Logf(\"ACTUAL: %q (%#v)\", actual, actual)\n\t\treturn\n\t}\n}"} {"input": "package zap\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\tjaeger \"github.com/uber/jaeger-client-go\"\n\n\topentracing \"github.com/opentracing/opentracing-go\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n)\n\n\n\n\n\n\n\n\n\ntype trace struct {\n\tctx context.Context\n}\n\nfunc (t trace) MarshalLogObject(enc zapcore.ObjectEncoder) error {\n\tspan := opentracing.SpanFromContext(t.ctx)\n\tif span == nil {\n\t\treturn nil\n\t}\n\tj, ok := span.Context().(jaeger.SpanContext)\n\tif !ok {\n\t\treturn nil\n\t}\n\tif !j.IsValid() {\n\t\treturn fmt.Errorf(\"invalid span: %v\", j.SpanID())\n\t}\n\tenc.AddString(\"span\", j.SpanID().String())\n\tenc.AddString(\"trace\", j.TraceID().String())\n\treturn nil\n}\n\nfunc Trace(ctx context.Context) zapcore.Field ", "output": "{\n\tif ctx == nil {\n\t\treturn zap.Skip()\n\t}\n\treturn zap.Object(\"trace\", trace{ctx})\n}"} {"input": "package commands\n\nimport (\n\t\"context\"\n\t\"errors\"\n)\n\n\n\nfunc cmdAttrib(ctx context.Context, cmd Param) (int, error) ", "output": "{\n\treturn 1, errors.New(\"not supported\")\n}"} {"input": "package steps\n\nimport (\n\t\"time\"\n\n\t\"github.com/intel-hpdd/lemur/uat/harness\"\n)\n\nfunc init() {\n\taddStep(`^I configure the (posix|s3) data mover$`, iConfigureADataMover)\n\taddStep(`^the (posix|s3) data mover should be (running|stopped)$`, theDataMoverShouldBe)\n}\n\nfunc iConfigureADataMover(dmType string) error {\n\treturn harness.AddConfiguredMover(ctx, harness.HsmPluginPrefix+dmType+\".race\")\n}\n\n\n\nfunc theDataMoverShouldBe(dmType, state string) error ", "output": "{\n\ttime.Sleep(1 * time.Second)\n\n\tdmStatus := func() error {\n\t\treturn checkProcessState(harness.HsmPluginPrefix+dmType+\".race\", state, -1)\n\t}\n\treturn waitFor(dmStatus, DefaultTimeout)\n}"} {"input": "package zookeeper\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/magneticio/vamp-router/haproxy\"\n\tgologger \"github.com/op/go-logging\"\n\t\"github.com/samuel/go-zookeeper/zk\"\n\t\"strings\"\n\t\"time\"\n)\n\n\ntype ZkClient struct {\n\tconn *zk.Conn\n\thaConfig *haproxy.Config\n\tlog *gologger.Logger\n}\n\nfunc (z *ZkClient) Init(conString string, conf *haproxy.Config, log *gologger.Logger) error {\n\n\tz.log = log\n\tz.haConfig = conf\n\terr := z.connect(conString)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\n\n\n\nfunc (z *ZkClient) Watch(path string) {\n\n\tgo z.watcher(path)\n\n}\n\nfunc (z *ZkClient) watcher(path string) error {\n\n\tfor {\n\t\tpayload, _, watch, err := z.conn.GetW(path)\n\n\t\tif err != nil {\n\t\t\tz.log.Error(\"Error from Zookeeper: \" + err.Error())\n\t\t}\n\n\t\terr = json.Unmarshal(payload, &z.haConfig)\n\t\tif err != nil {\n\t\t\tz.log.Error(\"Error parsing config from Zookeeper: \" + err.Error())\n\t\t}\n\n\t\tevent := <-watch\n\n\t\tz.log.Notice(\"Received Zookeeper event: \" + event.Type.String())\n\n\t\terr = json.Unmarshal(payload, &z.haConfig)\n\t\tif err != nil {\n\t\t\tz.log.Error(\"Error parsing config from Zookeeper: \" + err.Error())\n\t\t}\n\n\t}\n\n}\n\nfunc (z *ZkClient) connect(conString string) error ", "output": "{\n\tzks := strings.Split(conString, \",\")\n\tconn, _, err := zk.Connect(zks, (60 * time.Second))\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tz.conn = conn\n\treturn nil\n}"} {"input": "package test_utils\n\nimport (\n\t\"fmt\"\n\t\"simplejsondb/dbio\"\n)\n\n\n\ntype InMemoryDataFile struct {\n\tBlocks [][]byte\n\tCloseFunc func() error\n\tReadBlockFunc func(uint16, []byte) error\n\tWriteBlockFunc func(uint16, []byte) error\n}\n\n\n\nfunc NewFakeDataFileWithBlocks(blocks [][]byte) *InMemoryDataFile {\n\treturn &InMemoryDataFile{\n\t\tBlocks: blocks,\n\t\tCloseFunc: func() error {\n\t\t\treturn nil \n\t\t},\n\t\tWriteBlockFunc: func(id uint16, data []byte) error {\n\t\t\tblock := blocks[id]\n\t\t\tfor i := range block {\n\t\t\t\tblock[i] = data[i]\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t\tReadBlockFunc: func(id uint16, data []byte) error {\n\t\t\tif id < 0 || id >= uint16(len(blocks)) {\n\t\t\t\treturn fmt.Errorf(\"Invalid datablock requested: %d\", id)\n\t\t\t}\n\t\t\tblock := blocks[id]\n\t\t\tfor i := 0; i < len(block); i++ {\n\t\t\t\tdata[i] = block[i]\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n}\n\nfunc (df *InMemoryDataFile) Close() error {\n\treturn df.CloseFunc()\n}\nfunc (df *InMemoryDataFile) ReadBlock(id uint16, data []byte) error {\n\treturn df.ReadBlockFunc(id, data)\n}\nfunc (df *InMemoryDataFile) WriteBlock(id uint16, data []byte) error {\n\treturn df.WriteBlockFunc(id, data)\n}\n\nfunc NewFakeDataFile(blocksCount int) *InMemoryDataFile ", "output": "{\n\tblocks := [][]byte{}\n\tfor i := 0; i < blocksCount; i++ {\n\t\tblocks = append(blocks, make([]byte, dbio.DATABLOCK_SIZE))\n\t}\n\treturn NewFakeDataFileWithBlocks(blocks)\n}"} {"input": "package chart\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\tassert \"github.com/blendlabs/go-assert\"\n)\n\n\n\nfunc TestSequenceMarketHours(t *testing.T) {\n\tassert := assert.New(t)\n\n\ttoday := time.Date(2016, 07, 01, 12, 0, 0, 0, Date.Eastern())\n\tmh := Sequence.MarketHours(today, today, NYSEOpen, NYSEClose, Date.IsNYSEHoliday)\n\tassert.Len(mh, 8)\n\tassert.Equal(Date.Eastern(), mh[0].Location())\n}\n\nfunc TestSequenceMarketQuarters(t *testing.T) {\n\tassert := assert.New(t)\n\ttoday := time.Date(2016, 07, 01, 12, 0, 0, 0, Date.Eastern())\n\tmh := Sequence.MarketHourQuarters(today, today, NYSEOpen, NYSEClose, Date.IsNYSEHoliday)\n\tassert.Len(mh, 4)\n\tassert.Equal(9, mh[0].Hour())\n\tassert.Equal(30, mh[0].Minute())\n\tassert.Equal(Date.Eastern(), mh[0].Location())\n\n\tassert.Equal(12, mh[1].Hour())\n\tassert.Equal(00, mh[1].Minute())\n\tassert.Equal(Date.Eastern(), mh[1].Location())\n\n\tassert.Equal(14, mh[2].Hour())\n\tassert.Equal(00, mh[2].Minute())\n\tassert.Equal(Date.Eastern(), mh[2].Location())\n}\n\nfunc TestSequenceFloat64(t *testing.T) ", "output": "{\n\tassert := assert.New(t)\n\n\tasc := Sequence.Float64(1.0, 10.0)\n\tassert.Len(asc, 10)\n\n\tdesc := Sequence.Float64(10.0, 1.0)\n\tassert.Len(desc, 10)\n}"} {"input": "package cron\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestGenerateCronID(t *testing.T) ", "output": "{\n\tfmt.Println(generateCronID())\n}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/aws/aws-lambda-go/events\"\n\t\"github.com/aws/aws-lambda-go/lambda\"\n)\n\n\n\nfunc main() {\n\tlambda.Start(handleRequest)\n}\n\nfunc handleRequest(ctx context.Context, event events.S3Event) (string, error) ", "output": "{\n\tfmt.Println(ctx)\n\n\tfmt.Println(event)\n\n\treturn \"Hello World!\", nil\n}"} {"input": "package types\n\nimport \"fmt\"\n\ntype KeywordValue struct {\n\tValue string\n}\n\nfunc (v *KeywordValue) ToString() string {\n\treturn fmt.Sprint(v.Value)\n}\n\n\n\nfunc (v *KeywordValue) IsValue() bool {\n\treturn false\n}\n\nfunc (v *KeywordValue) ConvertTo(t string) (ValueType, error) {\n\treturn nil, fmt.Errorf(\"cannot convert keyword to %s: does not implement yet\", t)\n}\n\nfunc (v *KeywordValue) EqualTo(t ValueType) bool {\n\tif v2, ok := t.(*KeywordValue); ok {\n\t\tif v2.Value == v.Value {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc NewKeywordValue(v string) *KeywordValue {\n\treturn &KeywordValue{Value: v}\n}\n\nfunc (v *KeywordValue) GetType() string ", "output": "{\n\treturn \"keyword\"\n}"} {"input": "package v1alpha1\n\nimport (\n\tv1alpha1 \"k8s.io/api/scheduling/v1alpha1\"\n\tserializer \"k8s.io/apimachinery/pkg/runtime/serializer\"\n\t\"github.com/hyperhq/client-go/kubernetes/scheme\"\n\trest \"github.com/hyperhq/client-go/rest\"\n)\n\ntype SchedulingV1alpha1Interface interface {\n\tRESTClient() rest.Interface\n\tPriorityClassesGetter\n}\n\n\ntype SchedulingV1alpha1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *SchedulingV1alpha1Client) PriorityClasses() PriorityClassInterface {\n\treturn newPriorityClasses(c)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*SchedulingV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &SchedulingV1alpha1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *SchedulingV1alpha1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *SchedulingV1alpha1Client {\n\treturn &SchedulingV1alpha1Client{c}\n}\n\nfunc setConfigDefaults(config *rest.Config) error {\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}\n\n\n\n\n\nfunc (c *SchedulingV1alpha1Client) RESTClient() rest.Interface ", "output": "{\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}"} {"input": "package gostarter\n\nimport \"github.com/codegangsta/cli\"\n\n\n\n\n\nfunc Echo(e string) string {\n\treturn e\n}\n\nfunc App() *cli.App ", "output": "{\n\tapp := cli.NewApp()\n\tapp.Name = \"gostarter\"\n\tapp.Usage = \"make an explosive entrance\"\n\tapp.Action = func(c *cli.Context) {\n\t\tprintln(\"boom! I say!\")\n\t}\n\n\treturn app\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\n\n\nfunc NewWorker(id int, workerQueue chan chan WorkRequest) Worker {\n\tworker := Worker{\n\t\tID: id,\n\t\tWork: make(chan WorkRequest),\n\t\tWorkerQueue: workerQueue,\n\t\tQuitChan: make(chan bool)}\n\n\treturn worker\n}\n\ntype Worker struct {\n\tID int\n\tWork chan WorkRequest\n\tWorkerQueue chan chan WorkRequest\n\tQuitChan chan bool\n}\n\n\n\nfunc (w *Worker) Start() {\n\tgo func() {\n\t\tfor {\n\t\t\tw.WorkerQueue <- w.Work\n\n\t\t\tselect {\n\t\t\tcase work := <-w.Work:\n\t\t\t\tfmt.Printf(\"worker%d: Received work request %s\\n\", w.ID, work.URL)\n\n\t\t\t\tstatus, err := MakeRequest(work)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Printf(\"%s: %s\\n\", work.URL, err.Error())\n\t\t\t\t}\n\n\t\t\t\tfmt.Printf(\"worker%d: %s: %s\\n\", w.ID, status, work.URL)\n\n\t\t\t\tfmt.Println(\"removing from wait group\")\n\t\t\t\tBatchWaitGroup.Done()\n\t\t\t\ttime.Sleep(time.Duration(*PostRequestPause) * time.Second)\n\n\t\t\tcase <-w.QuitChan:\n\t\t\t\tfmt.Printf(\"worker%d stopping\\n\", w.ID)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t}\n\t}()\n}\n\n\n\n\nfunc (w *Worker) Stop() {\n\tgo func() {\n\t\tw.QuitChan <- true\n\t}()\n}\n\n\n\nfunc Workers(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tif r.Method != \"POST\" {\n\t\tw.Header().Set(\"Allow\", \"POST\")\n\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\tworkerCount := r.FormValue(\"workers\")\n\n\ti, err := strconv.Atoi(workerCount)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t} else if i > 0 {\n\t\tfmt.Println(\"Adjusting worker count\")\n\t\tAdjustWorkers(i)\n\t\tw.WriteHeader(http.StatusOK)\n\t} else {\n\t\thttp.Error(w, \"Worker Count must be positive\", http.StatusBadRequest)\n\t}\n\n\treturn\n}"} {"input": "package nodes\n\nimport (\n\t\"encoding/json\"\n\t\"sync\"\n)\n\n\ntype Name struct {\n\tTaxID string `json:\"TaxID\"`\n\tNames []NameItem `json:\"Names\"`\n}\n\n\ntype NameItem struct {\n\tName string `json:\"Name\"`\n\tUniqueName string `json:\"UniqueName\"`\n\tNameClass string `json:\"NameClass\"`\n}\n\n\nfunc (name Name) ToJSON() (string, error) {\n\ts, err := json.Marshal(name)\n\treturn string(s), err\n}\n\n\nfunc NameFromJSON(s string) (Name, error) {\n\tvar name Name\n\terr := json.Unmarshal([]byte(s), &name)\n\treturn name, err\n}\n\n\nfunc NameFromArgs(items []string) Name {\n\tif len(items) != 4 {\n\t\treturn Name{}\n\t}\n\n\treturn Name{\n\t\tTaxID: items[0],\n\t\tNames: []NameItem{\n\t\t\tNameItem{\n\t\t\t\tName: items[1],\n\t\t\t\tUniqueName: items[2],\n\t\t\t\tNameClass: items[3],\n\t\t\t}},\n\t}\n}\n\n\n\n\n\nvar Names map[string]Name\n\nvar mutex1 = &sync.Mutex{}\n\n\nfunc SetNames(names map[string]Name) {\n\tmutex1.Lock()\n\tNames = names\n\tmutex1.Unlock()\n}\n\nfunc MergeNames(names ...Name) Name ", "output": "{\n\tif len(names) < 2 {\n\t\treturn names[0]\n\t}\n\tname := names[0]\n\tfor _, another := range names[1:] {\n\t\tif another.TaxID != name.TaxID {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, anotherNameItem := range another.Names {\n\t\t\tname.Names = append(name.Names, anotherNameItem)\n\t\t}\n\t}\n\treturn name\n}"} {"input": "package generator\n\nimport (\n\t\"go/ast\"\n\t\"go/token\"\n)\n\nfunc makeBasicLit(kind token.Token, value string) *ast.BasicLit {\n\treturn &ast.BasicLit{Kind: kind, Value: value}\n}\n\n\n\nfunc makeCompositeLit(typ ast.Expr, elements []ast.Expr) *ast.CompositeLit {\n\treturn &ast.CompositeLit{\n\t\tType: typ,\n\t\tElts: elements,\n\t}\n}\n\nfunc makeVector(typ ast.Expr, elements []ast.Expr) *ast.CompositeLit ", "output": "{\n\treturn makeCompositeLit(&ast.ArrayType{Elt: typ}, elements)\n}"} {"input": "package conformance\n\nfunc stringGet(s string, index int) byte {\n\treturn s[index]\n}\n\n\n\nfunc substring(s string, low, high int) string {\n\tswitch {\n\tcase low >= 0 && high >= 0:\n\t\treturn s[low:high]\n\tcase low >= 0:\n\t\treturn s[low:]\n\tcase high >= 0:\n\t\treturn s[:high]\n\tdefault:\n\t\treturn s\n\t}\n}\n\nfunc stringLen(s string) int ", "output": "{\n\treturn len(s)\n}"} {"input": "package memstats\n\nimport (\n\t\"github.com/mono83/slf\"\n\t\"sync\"\n)\n\n\n\n\n\n\n\ntype MemStats struct {\n\tm sync.Mutex\n\n\tvalues map[string]int64\n}\n\n\nfunc (m *MemStats) Receive(e slf.Event) {\n\tif e.Type == slf.TypeInc {\n\t\tm.m.Lock()\n\t\tprev, _ := m.values[e.Content]\n\t\tm.values[e.Content] = prev + e.I64\n\t\tm.m.Unlock()\n\t} else if e.Type == slf.TypeGauge {\n\t\tm.m.Lock()\n\t\tm.values[e.Content] = e.I64\n\t\tm.m.Unlock()\n\t}\n}\n\n\nfunc (m *MemStats) Get(key string) (value int64, found bool) {\n\tm.m.Lock()\n\tdefer m.m.Unlock()\n\n\tvalue, found = m.values[key]\n\treturn\n}\n\n\nfunc (m *MemStats) Values() map[string]int64 {\n\tm.m.Lock()\n\tdefer m.m.Unlock()\n\n\tclone := make(map[string]int64, len(m.values))\n\tfor k, v := range m.values {\n\t\tclone[k] = v\n\t}\n\n\treturn clone\n}\n\nfunc New() *MemStats ", "output": "{\n\treturn &MemStats{\n\t\tvalues: map[string]int64{},\n\t}\n}"} {"input": "package master\n\nimport ()\n\n\n\ntype frame struct {\n\tjob *job\n\tslaveName string\n\tframe int\n\tdata []byte\n\tprogress byte\n\tcompleted bool\n}\n\n\n\n\n\n\n\nfunc (f *frame) Job() *job {\n\treturn f.job\n}\n\nfunc (f *frame) SlaveName() string {\n\treturn f.slaveName\n}\n\nfunc (f *frame) Frame() int {\n\treturn f.frame\n}\n\nfunc (f *frame) AlignedFrame() int {\n\treturn f.frame + f.Job().Start()\n}\n\nfunc (f *frame) Data() []byte {\n\treturn f.data\n}\n\nfunc (f *frame) Progress() byte {\n\treturn f.progress\n}\n\nfunc (f *frame) Completed() bool {\n\treturn f.completed\n}\n\nfunc (f *frame) File() []byte {\n\treturn f.Job().File()\n}\n\n\n\nfunc (f *frame) SetSlaveName(slaveName string) {\n\tf.slaveName = slaveName\n}\n\nfunc (f *frame) SetData(data []byte) {\n\tf.data = data\n}\n\nfunc (f *frame) SetProgress(progress byte) {\n\tf.progress = progress\n}\n\nfunc (f *frame) SetCompleted(completed bool) {\n\tf.completed = completed\n\tif completed {\n\t\tf.SetProgress(100)\n\t}\n}\n\n\n\nfunc (f *frame) Reset() {\n\tf.SetSlaveName(\"\")\n\tf.SetData(nil)\n\tf.SetProgress(0)\n\tf.SetCompleted(false)\n}\n\nfunc NewFrame(job *job, fr int) *frame ", "output": "{\n\treturn &frame{\n\t\tjob: job,\n\t\tslaveName: \"\",\n\t\tframe: fr,\n\t\tdata: nil,\n\t\tprogress: 0,\n\t\tcompleted: false,\n\t}\n}"} {"input": "package provider\n\nimport (\n\t\"strings\"\n)\n\n\ntype DomainFilter struct {\n\tfilters []string\n\texclude []string\n}\n\n\nfunc prepareFilters(filters []string) []string {\n\tfs := make([]string, len(filters))\n\tfor i, domain := range filters {\n\t\tfs[i] = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(domain), \".\"))\n\t}\n\treturn fs\n}\n\n\nfunc NewDomainFilterWithExclusions(domainFilters []string, excludeDomains []string) DomainFilter {\n\treturn DomainFilter{prepareFilters(domainFilters), prepareFilters(excludeDomains)}\n}\n\n\nfunc NewDomainFilter(domainFilters []string) DomainFilter {\n\treturn DomainFilter{prepareFilters(domainFilters), []string{}}\n}\n\n\n\n\n\n\n\nfunc matchFilter(filters []string, domain string, emptyval bool) bool {\n\tif len(filters) == 0 {\n\t\treturn emptyval\n\t}\n\n\tfor _, filter := range filters {\n\t\tstrippedDomain := strings.ToLower(strings.TrimSuffix(domain, \".\"))\n\n\t\tif filter == \"\" {\n\t\t\treturn emptyval\n\t\t} else if strings.HasPrefix(filter, \".\") && strings.HasSuffix(strippedDomain, filter) {\n\t\t\treturn true\n\t\t} else if strings.Count(strippedDomain, \".\") == strings.Count(filter, \".\") {\n\t\t\tif strippedDomain == filter {\n\t\t\t\treturn true\n\t\t\t}\n\t\t} else if strings.HasSuffix(strippedDomain, \".\"+filter) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc (df DomainFilter) IsConfigured() bool {\n\tif len(df.filters) == 1 {\n\t\treturn df.filters[0] != \"\"\n\t}\n\treturn len(df.filters) > 0\n}\n\nfunc (df DomainFilter) Match(domain string) bool ", "output": "{\n\treturn matchFilter(df.filters, domain, true) && !matchFilter(df.exclude, domain, false)\n}"} {"input": "package dexcom\n\nimport (\n\t\"log\"\n\t\"time\"\n)\n\n\nfunc (cgm *CGM) ReadHistory(pageType PageType, since time.Time) Records {\n\tfirst, last := cgm.ReadPageRange(pageType)\n\tif cgm.Error() != nil {\n\t\treturn nil\n\t}\n\tvar results Records\n\tproc := func(r Record) error {\n\t\tt := r.Time()\n\t\tif !t.After(since) {\n\t\t\tlog.Printf(\"stopping %v scan at %s\", pageType, t.Format(UserTimeLayout))\n\t\t\treturn IterationDone\n\t\t}\n\t\tresults = append(results, r)\n\t\treturn nil\n\t}\n\tcgm.IterRecords(pageType, first, last, proc)\n\treturn results\n}\n\n\n\n\n\n\nfunc MergeHistory(slices ...Records) Records {\n\tn := len(slices)\n\tif n == 0 {\n\t\treturn nil\n\t}\n\tif n == 1 {\n\t\treturn slices[0]\n\t}\n\tlength := make([]int, n)\n\ttotal := 0\n\tfor i, v := range slices {\n\t\tlength[i] = len(v)\n\t\ttotal += len(v)\n\t}\n\tresults := make(Records, total)\n\tindex := make([]int, n)\n\tfor next := range results {\n\t\twhich := -1\n\t\tmax := time.Time{}\n\t\tfor i, v := range slices {\n\t\t\tif index[i] < len(v) {\n\t\t\t\tt := v[index[i]].Time()\n\t\t\t\tif t.After(max) {\n\t\t\t\t\twhich = i\n\t\t\t\t\tmax = t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tresults[next] = slices[which][index[which]]\n\t\tindex[which]++\n\t}\n\treturn results\n}\n\nfunc (cgm *CGM) ReadCount(pageType PageType, count int) Records ", "output": "{\n\tfirst, last := cgm.ReadPageRange(pageType)\n\tif cgm.Error() != nil {\n\t\treturn nil\n\t}\n\tresults := make(Records, 0, count)\n\tproc := func(r Record) error {\n\t\tresults = append(results, r)\n\t\tif len(results) == count {\n\t\t\treturn IterationDone\n\t\t}\n\t\treturn nil\n\t}\n\tcgm.IterRecords(pageType, first, last, proc)\n\treturn results\n}"} {"input": "package command\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/xeb/etcdrepl/third_party/github.com/codegangsta/cli\"\n\t\"github.com/xeb/etcdrepl/third_party/github.com/coreos/go-etcd/etcd\"\n)\n\nfunc NewLsCommand() cli.Command {\n\treturn cli.Command{\n\t\tName:\t\"ls\",\n\t\tUsage:\t\"retrieve a directory\",\n\t\tFlags: []cli.Flag{\n\t\t\tcli.BoolFlag{\"recursive\", \"returns all values for key and child keys\"},\n\t\t},\n\t\tAction: func(c *cli.Context) {\n\t\t\thandleLs(c, lsCommandFunc)\n\t\t},\n\t}\n}\n\n\n\n\n\n\nfunc printLs(resp *etcd.Response, format string) {\n\tif !resp.Node.Dir {\n\t\tfmt.Println(resp.Node.Key)\n\t}\n\tfor _, node := range resp.Node.Nodes {\n\t\trPrint(&node)\n\t}\n}\n\n\nfunc lsCommandFunc(c *cli.Context, client *etcd.Client) (*etcd.Response, error) {\n\tkey := \"/\"\n\tif len(c.Args()) != 0 {\n\t\tkey = c.Args()[0]\n\t}\n\trecursive := c.Bool(\"recursive\")\n\n\treturn client.Get(key, false, recursive)\n}\n\n\nfunc rPrint(n *etcd.Node) {\n\tfmt.Println(n.Key)\n\tfor _, node := range n.Nodes {\n\t\trPrint(&node)\n\t}\n}\n\nfunc handleLs(c *cli.Context, fn handlerFunc) ", "output": "{\n\thandlePrint(c, fn, printLs)\n}"} {"input": "package socketio\n\nimport \"errors\"\n\n\ntype BroadcastAdaptor interface {\n\n\tJoin(room string, socket Socket) error\n\n\tLeave(room string, socket Socket) error\n\n\tSend(ignore Socket, room, event string, args ...interface{}) error\n\n\tGetAllClients(room string) (map[string]Socket, error)\n}\n\nvar newBroadcast = newBroadcastDefault\n\ntype Broadcast map[string]map[string]Socket\n\nfunc newBroadcastDefault() BroadcastAdaptor {\n\treturn make(Broadcast)\n}\n\n\n\nfunc (b Broadcast) Leave(room string, socket Socket) error {\n\tsockets, ok := b[room]\n\tif !ok {\n\t\treturn nil\n\t}\n\tdelete(sockets, socket.Id())\n\tif len(sockets) == 0 {\n\t\tdelete(b, room)\n\t\treturn nil\n\t}\n\tb[room] = sockets\n\treturn nil\n}\n\nfunc (b Broadcast) Send(ignore Socket, room, event string, args ...interface{}) error {\n\tsockets := b[room]\n\tfor id, s := range sockets {\n\t\tif ignore != nil && ignore.Id() == id {\n\t\t\tcontinue\n\t\t}\n\t\ts.Emit(event, args...)\n\t}\n\treturn nil\n}\n\nfunc (b Broadcast) GetAllClients(room string) (map[string]Socket, error) {\n\tsockets, ok := b[room]\n\tif !ok {\n\t\treturn nil, errors.New(\"没有此房间\")\n\t}\n\treturn sockets, nil\n}\n\nfunc (b Broadcast) Join(room string, socket Socket) error ", "output": "{\n\tsockets, ok := b[room]\n\tif !ok {\n\t\tsockets = make(map[string]Socket)\n\t}\n\tsockets[socket.Id()] = socket\n\tb[room] = sockets\n\treturn nil\n}"} {"input": "package demo_server\n\nimport (\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/http/cookiejar\"\n\t\"net/http/httptest\"\n\t\"os\"\n\t\"testing\"\n)\n\n\nfunc TestServer(t *testing.T) {\n\tf, err := ioutil.TempFile(\"/tmp\", \"hijinks\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.Remove(f.Name())\n\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\thandler := NewRootHandler(wd+\"/..\", []byte(\"12345678901234567890123456789012\"))\n\n\tserver := httptest.NewUnstartedServer(handler)\n\tserver.Start()\n\tdefer server.Close()\n\n\t*handler.URL = server.URL\n\turl := server.URL\n\n\tclient := newClient(t, url)\n\tread(t, client, url)\n}\n\n\n\nfunc read(t *testing.T, client *http.Client, url string) []byte {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(body) == 0 {\n\t\tt.Error(\"empty response\")\n\t}\n\treturn body\n}\n\nfunc newClient(t *testing.T, host string) *http.Client ", "output": "{\n\tjar, err := cookiejar.New(nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\ttransport := http.DefaultTransport.(*http.Transport)\n\tc := &http.Client{Jar: jar, Transport: transport}\n\n\treturn c\n}"} {"input": "package loadbalancer\n\nimport (\n\t\"github.com/sacloud/libsacloud/v2/helper/service\"\n\t\"github.com/sacloud/libsacloud/v2/helper/validate\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud\"\n\t\"github.com/sacloud/libsacloud/v2/sacloud/types\"\n)\n\ntype ApplyRequest struct {\n\tID types.ID \n\tZone string `validate:\"required\"`\n\n\tName string `validate:\"required\"`\n\tDescription string `validate:\"min=0,max=512\"`\n\tTags types.Tags\n\tIconID types.ID\n\tSwitchID types.ID `validate:\"required\"`\n\tPlanID types.ID `validate:\"required\"`\n\tVRID int\n\tIPAddresses []string `validate:\"required,min=1,max=2,dive,ipv4\"`\n\tNetworkMaskLen int `validate:\"required\"`\n\tDefaultRoute string `validate:\"omitempty,ipv4\"`\n\tVirtualIPAddresses sacloud.LoadBalancerVirtualIPAddresses\n\n\tSettingsHash string \n\tNoWait bool\n}\n\n\n\nfunc (req *ApplyRequest) Builder(caller sacloud.APICaller) (*Builder, error) {\n\tb := &Builder{Client: sacloud.NewLoadBalancerOp(caller)}\n\tif err := service.RequestConvertTo(req, b); err != nil {\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}\n\nfunc (req *ApplyRequest) Validate() error ", "output": "{\n\treturn validate.Struct(req)\n}"} {"input": "package se\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/kemokemo/kuronan-dash/assets/music\"\n)\n\nfunc TestMain(m *testing.M) {\n\terr := music.LoadAudioContext()\n\tif err != nil {\n\t\tfmt.Println(\"failed to LoadAudioContext:\", err)\n\t\treturn\n\t}\n\n\terr = LoadSE()\n\tif err != nil {\n\t\tfmt.Println(\"failed to LoadSE:\", err)\n\t\treturn\n\t}\n\tdefer func() {\n\t\te := CloseSE()\n\t\tfmt.Println(\"failed to CloseSE:\", e)\n\t}()\n\n\tos.Exit(m.Run())\n}\n\n\n\nfunc TestPlayer(t *testing.T) ", "output": "{\n\ttests := []struct {\n\t\tname string\n\t\tplayer *Player\n\t}{\n\t\t{\"Jump\", Jump},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif tt.player == nil {\n\t\t\t\tt.Errorf(\"SE Player '%v' is nil, loading error\", tt.name)\n\t\t\t}\n\t\t})\n\t}\n}"} {"input": "package variant\n\nimport (\n\t\"github.com/go-ole/com/errors\"\n\t\"github.com/go-ole/com/types\"\n)\n\nfunc VariantInit(v *types.Variant) error {\n\treturn errors.NotImplementedError\n}\n\nfunc VariantClear(v *types.Variant) error {\n\treturn errors.NotImplementedError\n}\n\nfunc VariantChangeType(source *types.Variant, flags uint16, vt types.VariantType) *types.Variant {\n\treturn source\n}\n\nfunc VariantChangeTypeEx(source *types.Variant, locale uint32, flags uint16, vt types.VariantType) *types.Variant {\n\treturn source\n}\n\nfunc VariantCopy(source *types.Variant) *types.Variant {\n\treturn source\n}\n\n\n\nfunc VariantCopyIndirect(source *types.Variant) *types.Variant ", "output": "{\n\treturn source\n}"} {"input": "package main\n\nimport (\n \"bufio\"\n \"fmt\"\n \"os\"\n \"math/rand\"\n \"strconv\"\n)\n\nfunc computer(inputChannel chan int, resultChannel chan string){\n for human_choice := range inputChannel {\n \tcomputer_choice := rand.Intn(3)\n \tevaluation(computer_choice, human_choice, resultChannel)\n }\n}\n\n\n\nfunc main() {\n\tcomputerChannel := make(chan int)\n\tresultChannel := make(chan string)\n\tgo computer(computerChannel, resultChannel)\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Println(\"Choose: \\n 0 = rock\\n 1 = paper\\n 2 = scissors\")\n\ttext, _ := reader.ReadString('\\n')\n\tchoice, _ := strconv.Atoi(text)\n\tcomputerChannel <- choice\n\tclose(computerChannel)\n\tfor message := range resultChannel {\n fmt.Println(\"Result:\", message)\n }\n}\n\nfunc evaluation(computer_choice int, human_choice int, resultChannel chan string)", "output": "{\n\tswitch human_choice {\n\tcase 0:\n\t\tswitch computer_choice {\n\t\tcase 0:\n\t\t\tresultChannel <- \"draw\"\n\t\tcase 1:\n\t\t\tresultChannel <- \"loss\"\n\t\tcase 2:\n\t\t\tresultChannel <- \"win\"\n\t\t}\n\tcase 1:\n\t\tswitch computer_choice {\n\t\tcase 0:\n\t\t\tresultChannel <- \"win\"\n\t\tcase 1:\n\t\t\tresultChannel <- \"draw\"\n\t\tcase 2:\n\t\t\tresultChannel <- \"loss\"\n\t\t}\n\tcase 2:\n\t\tswitch computer_choice {\n\t\tcase 0:\n\t\t\tresultChannel <- \"loss\"\n\t\tcase 1:\n\t\t\tresultChannel <- \"win\"\n\t\tcase 2:\n\t\t\tresultChannel <- \"draw\"\n\t\t}\n\tdefault:\n\t\tresultChannel <- \"Only numbers between 0 and 2 are valid!\"\n\t}\n\tclose(resultChannel)\n}"} {"input": "package objects\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"time\"\n)\n\n\ntype Logger interface {\n\tWriteLog(log string, writer io.Writer, output bool) error\n}\n\n\n\n\nfunc WriteLog(log string, writer io.Writer, timestamp bool, objects ...Logger) error ", "output": "{\n\tif timestamp == true {\n\t\tlog = fmt.Sprintf(\"[%d] %s\", time.Now().Unix(), log)\n\t}\n\n\tfor i, obj := range objects {\n\t\tif i == 0 {\n\t\t\tif err := obj.WriteLog(log, writer, true); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tif err := obj.WriteLog(log, writer, false); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}"} {"input": "package iso20022\n\n\ntype ConfirmationRejectedStatus1 struct {\n\n\tReason *RejectedConfirmationStatusReason1Code `xml:\"Rsn\"`\n\n\tExtendedReason *Extended350Code `xml:\"XtndedRsn\"`\n\n\tDataSourceScheme *GenericIdentification1 `xml:\"DataSrcSchme\"`\n}\n\nfunc (c *ConfirmationRejectedStatus1) SetReason(value string) {\n\tc.Reason = (*RejectedConfirmationStatusReason1Code)(&value)\n}\n\n\n\nfunc (c *ConfirmationRejectedStatus1) AddDataSourceScheme() *GenericIdentification1 {\n\tc.DataSourceScheme = new(GenericIdentification1)\n\treturn c.DataSourceScheme\n}\n\nfunc (c *ConfirmationRejectedStatus1) SetExtendedReason(value string) ", "output": "{\n\tc.ExtendedReason = (*Extended350Code)(&value)\n}"} {"input": "package pgxlog\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/flynn/flynn/pkg/sirenia/xlog\"\n)\n\nconst Zero xlog.Position = \"0/00000000\"\n\ntype PgXLog struct{}\n\nfunc (p PgXLog) Zero() xlog.Position {\n\treturn Zero\n}\n\n\nfunc (p PgXLog) Increment(pos xlog.Position, increment int) (xlog.Position, error) {\n\tparts, err := parse(pos)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn makePosition(parts[0], parts[1]+increment), nil\n}\n\n\n\nfunc (p PgXLog) Compare(xlog1, xlog2 xlog.Position) (int, error) {\n\tp1, err := parse(xlog1)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tp2, err := parse(xlog2)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif p1[0] == p2[0] && p1[1] == p2[1] {\n\t\treturn 0, nil\n\t}\n\tif p1[0] > p2[0] || p1[0] == p2[0] && p1[1] > p2[1] {\n\t\treturn 1, nil\n\t}\n\treturn -1, nil\n}\n\n\n\n\n\n\n\n\n\nfunc makePosition(filepart int, offset int) xlog.Position {\n\treturn xlog.Position(fmt.Sprintf(\"%X/%08X\", filepart, offset))\n}\n\nfunc parseHex(s string) (int, error) {\n\tres, err := strconv.ParseInt(s, 16, 64)\n\treturn int(res), err\n}\n\nfunc parse(xlog xlog.Position) (res [2]int, err error) ", "output": "{\n\tparts := strings.SplitN(string(xlog), \"/\", 2)\n\tif len(parts) != 2 {\n\t\terr = fmt.Errorf(\"malformed xlog position %q\", xlog)\n\t\treturn\n\t}\n\n\tres[0], err = parseHex(parts[0])\n\tif err != nil {\n\t\treturn\n\t}\n\tres[1], err = parseHex(parts[1])\n\n\treturn\n}"} {"input": "package router\n\nimport \"net/http\"\n\n\ntype Response struct {\n\tResult interface{}\n\n\tRawResponse []byte\n\n\tHTTPResponse *http.Response\n}\n\n\n\nfunc (r *Response) reset() ", "output": "{\n\tr.RawResponse = []byte{}\n\tr.HTTPResponse = nil\n}"} {"input": "package reuseport\n\nimport (\n\t\"context\"\n\t\"net\"\n\t\"syscall\"\n\n\t\"github.com/inverse-inc/packetfence/go/coredns/plugin/pkg/log\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\nfunc control(network, address string, c syscall.RawConn) error {\n\tc.Control(func(fd uintptr) {\n\t\tif err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1); err != nil {\n\t\t\tlog.Warningf(\"Failed to set SO_REUSEPORT on socket: %s\", err)\n\t\t}\n\t})\n\treturn nil\n}\n\n\n\nfunc Listen(network, addr string) (net.Listener, error) {\n\tlc := net.ListenConfig{Control: control}\n\treturn lc.Listen(context.Background(), network, addr)\n}\n\n\n\n\n\nfunc ListenPacket(network, addr string) (net.PacketConn, error) ", "output": "{\n\tlc := net.ListenConfig{Control: control}\n\treturn lc.ListenPacket(context.Background(), network, addr)\n}"} {"input": "package grains\n\nimport \"errors\"\n\n\nconst numSquares = 64\n\n\nconst testVersion = 1\n\n\nfunc pow(a uint64, b uint64) (uint64, error) {\n\tif b == 0 {\n\t\treturn 1, nil\n\t} else if b < 0 {\n\t\treturn 0, errors.New(\"Negative exponent not legal\")\n\t}\n\n\tvar y uint64 = uint64(1)\n\tfor b > 1 {\n\t\tif b%2 == 0 {\n\t\t\ta *= a\n\t\t\tb /= 2\n\t\t} else {\n\t\t\ty = a * y\n\t\t\ta *= a\n\t\t\tb = (b - 1) / 2\n\t\t}\n\t}\n\treturn a * y, nil\n}\n\n\n\n\n\nfunc Total() uint64 {\n\tvar total uint64\n\tfor i := 1; i <= numSquares; i++ {\n\t\tres, _ := Square(i)\n\t\ttotal += res\n\t}\n\treturn total\n}\n\nfunc Square(n int) (uint64, error) ", "output": "{\n\tif n < 1 || n > numSquares {\n\t\treturn 0, errors.New(\"Attempted to access square out of bounds\")\n\t}\n\n\tres, _ := pow(2, uint64(n-1))\n\n\treturn res, nil\n}"} {"input": "package api\n\nimport (\n\t\"errors\"\n\t\"net\"\n\t\"net/http\"\n\n\t\"github.com/coreos/fleet/log\"\n)\n\nvar unavailable = &unavailableHdlr{}\n\nfunc NewServer(listeners []net.Listener, hdlr http.Handler) *Server {\n\treturn &Server{\n\t\tlisteners: listeners,\n\t\tapi: hdlr,\n\t\tcur: unavailable,\n\t}\n}\n\ntype Server struct {\n\tlisteners []net.Listener\n\tapi http.Handler\n\tcur http.Handler\n}\n\n\n\nfunc (s *Server) Serve() {\n\tfor i, _ := range s.listeners {\n\t\tl := s.listeners[i]\n\t\tgo func() {\n\t\t\terr := http.Serve(l, s)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Failed serving HTTP on listener: %s\", l.Addr)\n\t\t\t}\n\t\t}()\n\t}\n}\n\n\n\n\nfunc (s *Server) Available(stop chan bool) {\n\ts.cur = s.api\n\t<-stop\n\ts.cur = unavailable\n}\n\ntype unavailableHdlr struct{}\n\nfunc (uh *unavailableHdlr) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\tsendError(rw, http.StatusServiceUnavailable, errors.New(\"fleet server currently unavailable\"))\n}\n\nfunc (s *Server) ServeHTTP(rw http.ResponseWriter, req *http.Request) ", "output": "{\n\ts.cur.ServeHTTP(rw, req)\n}"} {"input": "package lib\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc benchmarkReduceToDiff(modulesCount, deltaCount int, b *testing.B) {\n\tclean()\n\tdefer clean()\n\n\trepo := NewTestRepoForBench(b, \".tmp/repo\")\n\n\tfor i := 0; i < modulesCount; i++ {\n\t\terr := repo.InitModule(fmt.Sprintf(\"app-%v\", i))\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"%v\", err)\n\t\t}\n\t}\n\n\terr := repo.Commit(\"first\")\n\tif err != nil {\n\t\tb.Fatalf(\"%v\", err)\n\t}\n\n\tc1 := repo.LastCommit\n\n\tfor i := 0; i < deltaCount; i++ {\n\t\terr = repo.WriteContent(fmt.Sprintf(\"content/file-%v\", i), \"sample content\")\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"%v\", err)\n\t\t}\n\t}\n\n\trepo.Commit(\"second\")\n\tc2 := repo.LastCommit\n\n\tworld := NewBenchmarkWorld(b, \".tmp/repo\")\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\t_, err = world.System.ManifestByDiff(c1.String(), c2.String())\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"%v\", err)\n\t\t}\n\n\t}\n\n\tb.StopTimer()\n}\n\n\nfunc BenchmarkReduceToDiff100(b *testing.B) {\n\tbenchmarkReduceToDiff(100, 100, b)\n}\n\nfunc BenchmarkReduceToDiff1000(b *testing.B) {\n\tbenchmarkReduceToDiff(1000, 1000, b)\n}\n\nfunc BenchmarkReduceToDiff10000(b *testing.B) {\n\tbenchmarkReduceToDiff(10000, 10000, b)\n}\n\nfunc BenchmarkReduceToDiff10(b *testing.B) ", "output": "{\n\tbenchmarkReduceToDiff(10, 10, b)\n}"} {"input": "package throttled\n\n\ntype WaitGroup struct {\n\tthrottle int\n\tcompleted chan bool\n\toutstanding int\n}\n\n\nfunc NewWaitGroup(throttle int) *WaitGroup {\n\treturn &WaitGroup{\n\t\toutstanding: 0,\n\t\tthrottle: throttle,\n\t\tcompleted: make(chan bool, throttle),\n\t}\n}\n\n\nfunc (w *WaitGroup) PeekThrottled() bool {\n\treturn w.outstanding+1 > w.throttle\n}\n\n\n\nfunc (w *WaitGroup) Add() {\n\tw.outstanding++\n\tif w.outstanding > w.throttle {\n\t\tselect {\n\t\tcase <-w.completed:\n\t\t\tw.outstanding--\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n\n\n\n\nfunc (w *WaitGroup) Wait() {\n\tif w.outstanding == 0 {\n\t\treturn\n\t}\n\tfor w.outstanding > 0 {\n\t\tselect {\n\t\tcase <-w.completed:\n\t\t\tw.outstanding--\n\t\t}\n\t}\n}\n\nfunc (w *WaitGroup) Done() ", "output": "{\n\tw.completed <- true\n}"} {"input": "package classfile\n\nimport (\n\t\"github.com/zxh0/jvm.go/jvmgo/util/bigendian\"\n)\n\ntype ClassReader struct {\n\tdata []byte\n}\n\nfunc newClassReader(data []byte) *ClassReader {\n\treturn &ClassReader{data}\n}\n\nfunc (self *ClassReader) readUint8() uint8 {\n\tval := self.data[0]\n\tself.data = self.data[1:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint16() uint16 {\n\tval := bigendian.Uint16(self.data)\n\tself.data = self.data[2:]\n\treturn val\n}\n\nfunc (self *ClassReader) readUint32() uint32 {\n\tval := bigendian.Int32(self.data)\n\tself.data = self.data[4:]\n\treturn uint32(val)\n}\nfunc (self *ClassReader) readInt32() int32 {\n\tval := bigendian.Int32(self.data)\n\tself.data = self.data[4:]\n\treturn val\n}\n\nfunc (self *ClassReader) readInt64() int64 {\n\tval := bigendian.Int64(self.data)\n\tself.data = self.data[8:]\n\treturn val\n}\n\n\n\nfunc (self *ClassReader) readFloat64() float64 {\n\tval := bigendian.Float64(self.data)\n\tself.data = self.data[8:]\n\treturn val\n}\n\nfunc (self *ClassReader) readBytes(length uint32) []byte {\n\tbytes := self.data[:length]\n\tself.data = self.data[length:]\n\treturn bytes\n}\n\n\nfunc (self *ClassReader) readString() string {\n\tlength := uint32(self.readUint16())\n\tbytes := self.readBytes(length)\n\treturn string(bytes)\n}\n\nfunc (self *ClassReader) readFloat32() float32 ", "output": "{\n\tval := bigendian.Float32(self.data)\n\tself.data = self.data[4:]\n\treturn val\n}"} {"input": "package gooh\n\ntype MemoryContext struct {\n\tdata map[string]interface{}\n}\n\n\n\nfunc (c *MemoryContext) Set(k string, d interface{}) error {\n\tif c.data == nil {\n\t\tc.data = make(map[string]interface{})\n\t}\n\tc.data[k] = d\n\treturn nil\n}\n\nfunc (c *MemoryContext) Exists(k string) (bool, error) {\n\t_, ok := c.data[k]\n\treturn ok, nil\n}\n\nfunc (c *MemoryContext) Get(k string) (interface{}, error) ", "output": "{\n\treturn c.data[k], nil\n}"} {"input": "package testutil\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n)\n\n\n\nfunc WithTmpdir(fn func(tmpDir string)) {\n\ttmpBase := \"/tmp/hitch-test/\"\n\terr := os.MkdirAll(tmpBase, os.FileMode(0755)|os.ModeSticky)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\ttmpDir, err := ioutil.TempDir(tmpBase, \"\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer os.RemoveAll(tmpDir)\n\tfn(tmpDir)\n}\n\n\n\n\n\nfunc WithChdirTmpdir(fn func()) ", "output": "{\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tWithTmpdir(func(tmpDir string) {\n\t\tif err := os.Chdir(tmpDir); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tdefer os.Chdir(cwd)\n\t\tfn()\n\t})\n}"} {"input": "package trace\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/zrepl/zrepl/util/chainlock\"\n)\n\ntype SpanInfo interface {\n\tStartedAt() time.Time\n\tEndedAt() time.Time\n\tTaskAndSpanStack(kind *StackKind) string\n}\n\ntype Callback struct {\n\tOnBegin func(ctx context.Context)\n\tOnEnd func(ctx context.Context, spanInfo SpanInfo)\n}\n\nvar callbacks struct {\n\tmtx chainlock.L\n\tcs []Callback\n}\n\n\n\nfunc callbackBeginSpan(ctx context.Context) func(SpanInfo) {\n\n\n\tvar cbs []Callback\n\tcallbacks.mtx.HoldWhile(func() {\n\t\tcbs = callbacks.cs\n\t})\n\tfor _, cb := range cbs {\n\t\tif cb.OnBegin != nil {\n\t\t\tcb.OnBegin(ctx)\n\t\t}\n\t}\n\treturn func(spanInfo SpanInfo) {\n\t\tfor _, cb := range cbs {\n\t\t\tif cb.OnEnd != nil {\n\t\t\t\tcb.OnEnd(ctx, spanInfo)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc RegisterCallback(c Callback) ", "output": "{\n\tcallbacks.mtx.HoldWhile(func() {\n\t\tcallbacks.cs = append(callbacks.cs, c)\n\t})\n}"} {"input": "package main\n\nimport (\n\t\"github.com/jjyr/ringo\"\n\t\"github.com/jjyr/ringo/middleware\"\n)\n\n\n\ntype user struct {\n\tName string `json:\"name\" validate:\"required\"`\n}\n\nvar users []user\n\n\ntype Users struct {\n\tringo.Controller\n}\n\nfunc (_ *Users) Get(c ringo.Context) {\n\tc.JSON(200, ringo.H{\"users\": users})\n}\n\n\n\nfunc DisplayList(c ringo.Context) {\n\tc.HTML(200, \"list.html\", users)\n}\n\ntype User struct {\n\tringo.Controller\n}\n\nfunc (ctl *User) Delete(c ringo.Context) {\n\tidx := -1\n\tname := c.Params().ByName(\"id\")\n\tfor i, u := range users {\n\t\tif name == u.Name {\n\t\t\tidx = i\n\t\t\tbreak\n\t\t}\n\t}\n\tif idx >= 0 {\n\t\tusers = append(users[:idx], users[idx+1:]...)\n\t\tc.JSON(200, ringo.H{\"message\": \"ok\"})\n\t} else {\n\t\tc.JSON(404, ringo.H{\"message\": \"not found\"})\n\t}\n}\n\nfunc main() {\n\tapp := ringo.NewApp()\n\n\tapp.Add(\"/users\", &Users{})\n\tapp.GET(\"/users-list\", DisplayList)\n\tapp.Add(\"/user/:id\", &User{})\n\tapp.Use(middleware.Recover())\n\tapp.SetTemplatePath(\"templates\")\n\tapp.Run(\"localhost:8000\")\n}\n\nfunc (ctl *Users) Post(c ringo.Context) ", "output": "{\n\tu := user{}\n\tif err := c.BindJSON(&u); err == nil {\n\t\tusers = append(users, u)\n\t\tc.JSON(200, u)\n\t} else {\n\t\tc.JSON(400, ringo.H{\"message\": \"format error\"})\n\t}\n}"} {"input": "package ovnmodel\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/skydive-project/skydive/graffiti/getter\"\n\t\"github.com/skydive-project/skydive/graffiti/graph\"\n)\n\n\n\n\ntype LoadBalancerHealthCheck struct {\n\tUUID string `ovsdb:\"_uuid\" json:\",omitempty\" `\n\tExternalIDs map[string]string `ovsdb:\"external_ids\" json:\",omitempty\" `\n\tOptions map[string]string `ovsdb:\"options\" json:\",omitempty\" `\n\tVip string `ovsdb:\"vip\" json:\",omitempty\" `\n\n\tExternalIDsMeta graph.Metadata `json:\",omitempty\" field:\"Metadata\"`\n\tOptionsMeta graph.Metadata `json:\",omitempty\" field:\"Metadata\"`\n}\n\nfunc (t *LoadBalancerHealthCheck) Metadata() graph.Metadata {\n\tt.ExternalIDsMeta = graph.NormalizeValue(t.ExternalIDs).(map[string]interface{})\n\tt.OptionsMeta = graph.NormalizeValue(t.Options).(map[string]interface{})\n\n\treturn graph.Metadata{\n\t\t\"Type\": \"LoadBalancerHealthCheck\",\n\t\t\"Manager\": \"ovn\",\n\t\t\"UUID\": t.GetUUID(),\n\t\t\"Name\": t.GetName(),\n\t\t\"OVN\": t,\n\t}\n}\n\nfunc (t *LoadBalancerHealthCheck) GetUUID() string {\n\treturn t.UUID\n}\n\nfunc (t *LoadBalancerHealthCheck) GetName() string {\n\tif name := t.UUID; name != \"\" {\n\t\treturn name\n\t}\n\treturn t.GetUUID()\n}\n\n\n\n\nfunc LoadBalancerHealthCheckDecoder(raw json.RawMessage) (getter.Getter, error) ", "output": "{\n\tvar t LoadBalancerHealthCheck\n\tif err := json.Unmarshal(raw, &t); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to unmarshal LoadBalancerHealthCheck metadata %s: %s\", string(raw), err)\n\t}\n\treturn &t, nil\n}"} {"input": "package replication\n\nimport (\n\t\"github.com/golang/glog\"\n\t\"k8s.io/kubernetes/pkg/api\"\n\tclient \"k8s.io/kubernetes/pkg/client/unversioned\"\n)\n\n\nfunc updateReplicaCount(rcClient client.ReplicationControllerInterface, controller api.ReplicationController, numReplicas int) (updateErr error) {\n\tif controller.Status.Replicas == numReplicas &&\n\t\tcontroller.Generation == controller.Status.ObservedGeneration {\n\t\treturn nil\n\t}\n\tgeneration := controller.Generation\n\n\tvar getErr error\n\tfor i, rc := 0, &controller; ; i++ {\n\t\tglog.V(4).Infof(\"Updating replica count for rc: %v, %d->%d (need %d), sequence No: %v->%v\",\n\t\t\tcontroller.Name, controller.Status.Replicas, numReplicas, controller.Spec.Replicas, controller.Status.ObservedGeneration, generation)\n\n\t\trc.Status = api.ReplicationControllerStatus{Replicas: numReplicas, ObservedGeneration: generation}\n\t\t_, updateErr = rcClient.UpdateStatus(rc)\n\t\tif updateErr == nil || i >= statusUpdateRetries {\n\t\t\treturn updateErr\n\t\t}\n\t\tif rc, getErr = rcClient.Get(controller.Name); getErr != nil {\n\t\t\treturn getErr\n\t\t}\n\t}\n}\n\n\ntype OverlappingControllers []api.ReplicationController\n\nfunc (o OverlappingControllers) Len() int { return len(o) }\n\n\nfunc (o OverlappingControllers) Less(i, j int) bool {\n\tif o[i].CreationTimestamp.Equal(o[j].CreationTimestamp) {\n\t\treturn o[i].Name < o[j].Name\n\t}\n\treturn o[i].CreationTimestamp.Before(o[j].CreationTimestamp)\n}\n\nfunc (o OverlappingControllers) Swap(i, j int) ", "output": "{ o[i], o[j] = o[j], o[i] }"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc parseM3uPlaylist(data string) (songs []*SongRecord) {\n\tvar songIndex int\n\tvar newSong *SongRecord\n\n\tfor _, line := range strings.Split(data, \"\\n\") {\n\t\tline = strings.TrimSpace(line)\n\t\tif !isSongRecord(line) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif isSongRecordHeader(line) {\n\t\t\tsongIndex += 1\n\t\t\tnewSong = extractSongRecordHeader(songIndex, line)\n\t\t} else {\n\t\t\tnewSong.setFilepath(line)\n\t\t\tsongs = append(songs, newSong)\n\t\t}\n\t}\n\treturn songs\n}\n\n\n\nfunc isSongRecordHeader(input string) bool {\n\treturn strings.HasPrefix(input, \"#EXTINF:\")\n}\n\nfunc extractSongRecordHeader(index int, line string) (s *SongRecord) {\n\tvar title, duration string\n\tif i := strings.IndexAny(line, \"-0123456789\"); i > -1 {\n\t\tconst separator = \",\"\n\t\tline = line[i:]\n\t\tif j := strings.Index(line, separator); j > -1 {\n\t\t\ttitle = line[j+len(separator):]\n\t\t\tduration = line[:j]\n\t\t}\n\t}\n\n\treturn NewSongRecord(index, \"\", title, duration)\n}\n\nfunc writePlsPlaylist(songs []*SongRecord) error {\n\tfmt.Println(\"[playlist]\")\n\tfor _, song := range songs {\n\t\tif pls, err := song.ToPls(); err != nil {\n\t\t\treturn err\n\t\t} else {\n\t\t\tfmt.Printf(pls)\n\t\t}\n\t}\n\tfmt.Printf(\"NumberOfEntries=%d\\nVersion=2\\n\", len(songs))\n\treturn nil\n}\n\nfunc isSongRecord(input string) bool ", "output": "{\n\treturn input != \"\" && !strings.HasPrefix(input, \"#EXTM3U\")\n}"} {"input": "package sdk\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\nfunc init() {\n\tNowTime = time.Now\n\tSleep = time.Sleep\n\tSleepWithContext = sleepWithContext\n}\n\n\n\nvar NowTime func() time.Time\n\n\n\nvar Sleep func(time.Duration)\n\n\n\n\n\n\nvar SleepWithContext func(context.Context, time.Duration) error\n\n\n\n\nfunc sleepWithContext(ctx context.Context, dur time.Duration) error {\n\tt := time.NewTimer(dur)\n\tdefer t.Stop()\n\n\tselect {\n\tcase <-t.C:\n\t\tbreak\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n\n\treturn nil\n}\n\n\nfunc noOpSleepWithContext(context.Context, time.Duration) error {\n\treturn nil\n}\n\nfunc noOpSleep(time.Duration) {}\n\n\n\nfunc TestingUseNopSleep() func() {\n\tSleepWithContext = noOpSleepWithContext\n\tSleep = noOpSleep\n\n\treturn func() {\n\t\tSleepWithContext = sleepWithContext\n\t\tSleep = time.Sleep\n\t}\n}\n\n\n\n\n\nfunc TestingUseReferenceTime(referenceTime time.Time) func() ", "output": "{\n\tNowTime = func() time.Time {\n\t\treturn referenceTime\n\t}\n\treturn func() {\n\t\tNowTime = time.Now\n\t}\n}"} {"input": "package types\n\nimport \"fmt\"\n\ntype KeywordValue struct {\n\tValue string\n}\n\nfunc (v *KeywordValue) ToString() string {\n\treturn fmt.Sprint(v.Value)\n}\n\nfunc (v *KeywordValue) GetType() string {\n\treturn \"keyword\"\n}\n\nfunc (v *KeywordValue) IsValue() bool {\n\treturn false\n}\n\nfunc (v *KeywordValue) ConvertTo(t string) (ValueType, error) {\n\treturn nil, fmt.Errorf(\"cannot convert keyword to %s: does not implement yet\", t)\n}\n\nfunc (v *KeywordValue) EqualTo(t ValueType) bool {\n\tif v2, ok := t.(*KeywordValue); ok {\n\t\tif v2.Value == v.Value {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\n\nfunc NewKeywordValue(v string) *KeywordValue ", "output": "{\n\treturn &KeywordValue{Value: v}\n}"} {"input": "package databus\n\nimport (\n\t\"context\"\n\t\"strconv\"\n\n\t\"go-common/app/interface/main/app-show/conf\"\n\t\"go-common/library/log\"\n\t\"go-common/library/queue/databus\"\n)\n\n\ntype Dao struct {\n\tdataBus *databus.Databus\n}\n\nfunc New(c *conf.Config) (d *Dao) {\n\td = &Dao{\n\t\tdataBus: databus.New(c.DislikeDataBus),\n\t}\n\treturn\n}\n\n\n\nfunc (d *Dao) Pub(ctx context.Context, buvid, gt string, id, mid int64) (err error) ", "output": "{\n\tkey := strconv.FormatInt(mid, 10)\n\tmsg := struct {\n\t\tBuvid string `json:\"buvid\"`\n\t\tGoto string `json:\"goto\"`\n\t\tID int64 `json:\"id\"`\n\t\tMid int64 `json:\"mid\"`\n\t}{Buvid: buvid, Goto: gt, ID: id, Mid: mid}\n\tif err = d.dataBus.Send(ctx, key, msg); err != nil {\n\t\tlog.Error(\"d.dataBus.Pub(%s,%v) error (%v)\", key, msg, err)\n\t}\n\treturn\n}"} {"input": "package github\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/hashicorp/vault/api\"\n)\n\ntype CLIHandler struct{}\n\nfunc (h *CLIHandler) Auth(c *api.Client, m map[string]string) (string, error) {\n\tmount, ok := m[\"mount\"]\n\tif !ok {\n\t\tmount = \"github\"\n\t}\n\n\ttoken, ok := m[\"token\"]\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"'token' var must be set\")\n\t}\n\n\tpath := fmt.Sprintf(\"auth/%s/login\", mount)\n\tsecret, err := c.Logical().Write(path, map[string]interface{}{\n\t\t\"token\": token,\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif secret == nil {\n\t\treturn \"\", fmt.Errorf(\"empty response from credential provider\")\n\t}\n\n\treturn secret.Auth.ClientToken, nil\n}\n\n\n\nfunc (h *CLIHandler) Help() string ", "output": "{\n\thelp := `\nThe GitHub credential provider allows you to authenticate with GitHub.\nTo use it, specify the \"token\" var with the \"-var\" flag. The value should\nbe a personal access token for your GitHub account. You can generate a personal\naccess token on your account settings page on GitHub.\n\n Example: vault auth -method=github -var=\"token=\"\n\n\t`\n\n\treturn strings.TrimSpace(help)\n}"} {"input": "package path\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n\n\n\n\n\n\ntype P []string\n\n\nfunc New(path string) P {\n\treturn strings.Split(path, \".\")\n}\n\n\n\nfunc Newf(path string, args ...interface{}) P {\n\treturn New(fmt.Sprintf(path, args...))\n}\n\n\nfunc (path P) String() string {\n\tbuffer := new(bytes.Buffer)\n\n\tfor i, item := range path {\n\t\tbuffer.WriteString(item)\n\n\t\tif i < len(path)-1 {\n\t\t\tbuffer.WriteString(\".\")\n\t\t}\n\t}\n\n\treturn buffer.String()\n}\n\n\n\n\nfunc (path P) Last() string ", "output": "{ return path[len(path)-1] }"} {"input": "package mqtt\n\nimport (\n\t\"encoding/binary\"\n\t\"encoding/json\"\n\t\"io\"\n)\n\ntype ConnackMessage struct {\n\tFixedHeader\n\tReserved uint8\n\tReturnCode uint8\n}\n\n\n\nfunc (self ConnackMessage) WriteTo(w io.Writer) (int64, error) {\n\tvar fsize = 2\n\tsize, err := self.FixedHeader.writeTo(fsize, w)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tbinary.Write(w, binary.BigEndian, self.Reserved)\n\tbinary.Write(w, binary.BigEndian, self.ReturnCode)\n\n\treturn int64(fsize) + size, nil\n}\n\nfunc (self *ConnackMessage) String() string {\n\tb, _ := json.Marshal(self)\n\treturn string(b)\n}\n\nfunc (self *ConnackMessage) decode(reader io.Reader) error ", "output": "{\n\tbinary.Read(reader, binary.BigEndian, &self.Reserved)\n\tbinary.Read(reader, binary.BigEndian, &self.ReturnCode)\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/cross-dev/script-server/Godeps/_workspace/src/github.com/onsi/ginkgo/config\"\n)\n\n\n\nfunc printVersion([]string, []string) {\n\tfmt.Printf(\"Ginkgo Version %s\\n\", config.VERSION)\n}\n\nfunc BuildVersionCommand() *Command ", "output": "{\n\treturn &Command{\n\t\tName: \"version\",\n\t\tFlagSet: flag.NewFlagSet(\"version\", flag.ExitOnError),\n\t\tUsageCommand: \"ginkgo version\",\n\t\tUsage: []string{\n\t\t\t\"Print Ginkgo's version\",\n\t\t},\n\t\tCommand: printVersion,\n\t}\n}"} {"input": "package xmpp\n\nimport (\n\t\"encoding/xml\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/rmmmmpl/tcp_testserver\"\n)\n\nconst (\n\ttestUser = \"milton.waddams\"\n\ttestPassword = \"secret\"\n\ttestResource = \"basement\"\n\ttestHost = \"localhost\"\n\ttestPort = \"5552\"\n\ttestJID = JID(testUser + \"@\" + testHost + \"/\" + testResource)\n)\n\nvar s *tcp_testserver.Server\nvar c *Client\n\n\n\nfunc TestMain(m *testing.M) {\n\tvar err error\n\ts, err = tcp_testserver.NewServer(testHost + \":\" + testPort)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tos.Exit(-1)\n\t}\n\n\tr := m.Run()\n\n\tif c != nil {\n\t\tc.Close()\n\t}\n\ts.Close()\n\tos.Exit(r)\n}\n\nfunc printErr(t *testing.T, shouldBe, is interface{}) {\n\tt.Log(\"Should be:\", shouldBe)\n\tt.Fatal(\"Is:\", is)\n}\n\nfunc presenceRequestHandler(t *testing.T, conn net.Conn) {\n\tvar p Presence\n\tif err := xml.NewDecoder(conn).Decode(&p); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tvar retP Presence\n\tretP.SetID(p.ID())\n\tretP.SetFrom(p.To())\n\tretP.SetTo(p.From())\n\tretP.SetType(Result)\n\n\tif err := xml.NewEncoder(conn).Encode(&retP); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc serverErrHandler(t *testing.T) chan<- bool ", "output": "{\n\tch := make(chan bool)\n\tgo func() {\n\t\tselect {\n\t\tcase err := <-s.ErrCh:\n\t\t\tt.Fatal(err)\n\t\tcase <-ch:\n\t\t\treturn\n\t\t}\n\t}()\n\treturn ch\n}"} {"input": "package undertaker\n\nimport (\n\t\"github.com/juju/errors\"\n\t\"gopkg.in/juju/names.v2\"\n\n\t\"github.com/juju/juju/environs/config\"\n\t\"github.com/juju/juju/state\"\n)\n\n\n\ntype State interface {\n\tstate.EntityFinder\n\n\tModel() (Model, error)\n\n\tIsController() bool\n\n\tProcessDyingModel() (err error)\n\n\tRemoveAllModelDocs() error\n\n\tAllMachines() ([]Machine, error)\n\n\tAllApplications() ([]Service, error)\n\n\tModelConfig() (*config.Config, error)\n}\n\ntype stateShim struct {\n\t*state.State\n}\n\n\n\n\n\ntype Machine interface {\n\tWatch() state.NotifyWatcher\n}\n\nfunc (s *stateShim) AllApplications() ([]Service, error) {\n\tstateServices, err := s.State.AllApplications()\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\tservices := make([]Service, len(stateServices))\n\tfor i := range stateServices {\n\t\tservices[i] = stateServices[i]\n\t}\n\n\treturn services, nil\n}\n\n\n\ntype Service interface {\n\tWatch() state.NotifyWatcher\n}\n\nfunc (s *stateShim) Model() (Model, error) {\n\treturn s.State.Model()\n}\n\n\n\ntype Model interface {\n\n\tOwner() names.UserTag\n\n\tLife() state.Life\n\n\tName() string\n\n\tUUID() string\n\n\tDestroy() error\n}\n\nfunc (s *stateShim) AllMachines() ([]Machine, error) ", "output": "{\n\tstateMachines, err := s.State.AllMachines()\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\tmachines := make([]Machine, len(stateMachines))\n\tfor i := range stateMachines {\n\t\tmachines[i] = stateMachines[i]\n\t}\n\n\treturn machines, nil\n}"} {"input": "package instructions\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/bongo227/goory/types\"\n\n\t\"github.com/bongo227/goory/value\"\n)\n\n\ntype CondBr struct {\n\tblock value.Value\n\tname string\n\tcondition value.Value\n\ttrueBlock value.Value\n\tfalseBlock value.Value\n}\n\nfunc NewCondBr(block value.Value, name string, condition value.Value, trueBlock value.Value, falseBlock value.Value) *CondBr {\n\tif !condition.Type().Equal(types.NewBoolType()) {\n\t\tpanic(\"condition is not a bool type\")\n\t}\n\n\tif !trueBlock.Type().Equal(types.NewBlockType()) {\n\t\tpanic(\"trueBlock is not a block type\")\n\t}\n\n\tif !falseBlock.Type().Equal(types.NewBlockType()) {\n\t\tpanic(\"falseBlock is not a block type\")\n\t}\n\n\treturn &CondBr{block, name, condition, trueBlock, falseBlock}\n}\n\n\n\nfunc (i *CondBr) IsTerminator() bool {\n\treturn true\n}\n\nfunc (i *CondBr) Type() types.Type {\n\treturn types.VOID\n}\n\nfunc (i *CondBr) Ident() string {\n\treturn \"%\" + i.name\n}\n\nfunc (i *CondBr) Llvm() string {\n\treturn fmt.Sprintf(\"br i1 %s, label %%%s, label %%%s\",\n\t\ti.condition.Ident(),\n\t\ti.trueBlock.Ident(),\n\t\ti.falseBlock.Ident())\n}\n\nfunc (i *CondBr) Block() value.Value ", "output": "{\n\treturn i.block\n}"} {"input": "package chunkstore\n\nimport (\n\t\"errors\"\n\n\t. \"github.com/huin/chunkymonkey/types\"\n)\n\n\n\n\n\ntype MultiStore struct {\n\treadStores []IChunkStore\n\twriteStore IChunkStore\n}\n\nfunc NewMultiStore(readStores []IChunkStore, writeStore IChunkStore) *MultiStore {\n\ts := &MultiStore{\n\t\treadStores: readStores,\n\t\twriteStore: writeStore,\n\t}\n\n\treturn s\n}\n\nfunc (s *MultiStore) ReadChunk(chunkLoc ChunkXz) (reader IChunkReader, err error) {\n\tfor _, store := range s.readStores {\n\t\tresult := <-store.ReadChunk(chunkLoc)\n\n\t\tif result.Err == nil {\n\t\t\treturn result.Reader, result.Err\n\t\t} else {\n\t\t\tif _, ok := result.Err.(NoSuchChunkError); ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil, result.Err\n\t\t}\n\t}\n\n\treturn nil, NoSuchChunkError(false)\n}\n\n\n\nfunc (s *MultiStore) Writer() IChunkWriter {\n\tif s.writeStore != nil {\n\t\treturn s.writeStore.Writer()\n\t}\n\treturn nil\n}\n\nfunc (s *MultiStore) WriteChunk(writer IChunkWriter) error {\n\tif s.writeStore == nil {\n\t\treturn errors.New(\"writes not supported\")\n\t}\n\ts.writeStore.WriteChunk(writer)\n\treturn nil\n}\n\nfunc (s *MultiStore) SupportsWrite() bool ", "output": "{\n\treturn s.writeStore != nil && s.writeStore.SupportsWrite()\n}"} {"input": "package api\n\nimport (\n\t\"testing\"\n)\n\nfunc TestAPI_StatusLeader(t *testing.T) {\n\tt.Parallel()\n\tc, s := makeClient(t)\n\tdefer s.Stop()\n\n\tstatus := c.Status()\n\n\tleader, err := status.Leader()\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\tif leader == \"\" {\n\t\tt.Fatalf(\"Expected leader\")\n\t}\n}\n\n\n\nfunc TestAPI_StatusPeers(t *testing.T) ", "output": "{\n\tt.Parallel()\n\tc, s := makeClient(t)\n\tdefer s.Stop()\n\n\tstatus := c.Status()\n\n\tpeers, err := status.Peers()\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\tif len(peers) == 0 {\n\t\tt.Fatalf(\"Expected peers \")\n\t}\n}"} {"input": "package require\n\ntype Assertions struct {\n\tt TestingT\n}\n\n\n\nfunc New(t TestingT) *Assertions ", "output": "{\n\treturn &Assertions{\n\t\tt: t,\n\t}\n}"} {"input": "package server\n\nimport (\n\t\"github.com/uniqush/uniqush-conn/msgcache\"\n\t\"github.com/uniqush/uniqush-conn/proto\"\n\t\"github.com/uniqush/uniqush-conn/rpc\"\n)\n\ntype messageRetriever struct {\n\tconn *serverConn\n\tcache msgcache.Cache\n}\n\n\n\nfunc (self *messageRetriever) ProcessCommand(cmd *proto.Command) (msg *rpc.Message, err error) ", "output": "{\n\tif cmd == nil || cmd.Type != proto.CMD_MSG_RETRIEVE || self.conn == nil || self.cache == nil {\n\t\treturn\n\t}\n\tif len(cmd.Params) < 1 {\n\t\terr = proto.ErrBadPeerImpl\n\t\treturn\n\t}\n\tid := cmd.Params[0]\n\tmc, err := self.cache.Get(self.conn.Service(), self.conn.Username(), id)\n\tif err != nil {\n\t\treturn\n\t}\n\tif mc == nil || mc.Message == nil {\n\t\terr = self.conn.SendMessage(nil, id, nil, false)\n\t\treturn\n\t}\n\tif mc.FromServer() {\n\t\terr = self.conn.SendMessage(mc.Message, id, nil, false)\n\t} else {\n\t\terr = self.conn.ForwardMessage(mc.Sender, mc.SenderService, mc.Message, id, false)\n\t}\n\treturn\n}"} {"input": "package describe\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl\"\n\t\"github.com/openshift/origin/pkg/client\"\n)\n\ntype describeClient struct {\n\tT *testing.T\n\tNamespace string\n\tErr error\n\t*client.Fake\n}\n\n\n\nfunc TestDescribers(t *testing.T) {\n\tfake := &client.Fake{}\n\tc := &describeClient{T: t, Namespace: \"foo\", Fake: fake}\n\n\ttestDescriberList := []kubectl.Describer{\n\t\t&BuildDescriber{c},\n\t\t&BuildConfigDescriber{c, \"\"},\n\t\t&DeploymentDescriber{c},\n\t\t&DeploymentConfigDescriber{c},\n\t\t&ImageDescriber{c},\n\t\t&ImageRepositoryDescriber{c},\n\t\t&RouteDescriber{c},\n\t\t&ProjectDescriber{c},\n\t}\n\n\tfor _, d := range testDescriberList {\n\t\tout, err := d.Describe(\"foo\", \"bar\")\n\t\tif err != nil {\n\t\t\tt.Errorf(\"unexpected error for %v: %v\", d, err)\n\t\t}\n\t\tif !strings.Contains(out, \"Name:\") || !strings.Contains(out, \"Annotations\") {\n\t\t\tt.Errorf(\"unexpected out: %s\", out)\n\t\t}\n\t}\n}\n\nfunc TestDescribeFor(t *testing.T) ", "output": "{\n\tc := &client.Client{}\n\ttestTypesList := []string{\n\t\t\"Build\", \"BuildConfig\", \"Deployment\", \"DeploymentConfig\",\n\t\t\"Image\", \"ImageRepository\", \"Route\", \"Project\",\n\t}\n\tfor _, o := range testTypesList {\n\t\t_, ok := DescriberFor(o, c, \"\")\n\t\tif !ok {\n\t\t\tt.Errorf(\"Unable to obtain describer for %s\", o)\n\t\t}\n\t}\n}"} {"input": "package router\n\nimport (\n\t\"sync/atomic\"\n\n\t\"github.com/AsynkronIT/protoactor-go/actor\"\n)\n\ntype roundRobinGroupRouter struct {\n\tGroupRouter\n}\n\ntype roundRobinPoolRouter struct {\n\tPoolRouter\n}\n\ntype roundRobinState struct {\n\tindex int32\n\troutees *actor.PIDSet\n\tvalues []actor.PID\n}\n\nfunc (state *roundRobinState) SetRoutees(routees *actor.PIDSet) {\n\tstate.routees = routees\n\tstate.values = routees.Values()\n}\n\nfunc (state *roundRobinState) GetRoutees() *actor.PIDSet {\n\treturn state.routees\n}\n\nfunc (state *roundRobinState) RouteMessage(message interface{}, sender *actor.PID) {\n\tpid := roundRobinRoutee(&state.index, state.values)\n\tpid.Request(message, sender)\n}\n\nfunc NewRoundRobinPool(size int) *actor.Props {\n\treturn actor.FromSpawnFunc(spawner(&roundRobinPoolRouter{PoolRouter{PoolSize: size}}))\n}\n\nfunc NewRoundRobinGroup(routees ...*actor.PID) *actor.Props {\n\treturn actor.FromSpawnFunc(spawner(&roundRobinGroupRouter{GroupRouter{Routees: actor.NewPIDSet(routees...)}}))\n}\n\nfunc (config *roundRobinPoolRouter) CreateRouterState() Interface {\n\treturn &roundRobinState{}\n}\n\nfunc (config *roundRobinGroupRouter) CreateRouterState() Interface {\n\treturn &roundRobinState{}\n}\n\n\n\nfunc roundRobinRoutee(index *int32, routees []actor.PID) actor.PID ", "output": "{\n\ti := int(atomic.AddInt32(index, 1))\n\tif i < 0 {\n\t\t*index = 0\n\t\ti = 0\n\t}\n\tmod := len(routees)\n\troutee := routees[i%mod]\n\treturn routee\n}"} {"input": "package resources\n\nimport \"github.com/awslabs/goformation/cloudformation/policies\"\n\n\n\ntype AWSSecretsManagerRotationSchedule_RotationRules struct {\n\n\tAutomaticallyAfterDays int `json:\"AutomaticallyAfterDays,omitempty\"`\n\n\t_deletionPolicy policies.DeletionPolicy\n\n\t_dependsOn []string\n\n\t_metadata map[string]interface{}\n}\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) AWSCloudFormationType() string {\n\treturn \"AWS::SecretsManager::RotationSchedule.RotationRules\"\n}\n\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) DependsOn() []string {\n\treturn r._dependsOn\n}\n\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}\n\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\n\n\nfunc (r *AWSSecretsManagerRotationSchedule_RotationRules) SetDeletionPolicy(policy policies.DeletionPolicy) ", "output": "{\n\tr._deletionPolicy = policy\n}"} {"input": "package miner\n\nimport \"net/http\"\n\nconst (\n\tWaitTime = 5\n\n\n\tGET = \"GET\"\n\tPOST = \"POST\"\n\tPOSTJSON = \"POSTJSON\"\n\tPOSTXML = \"POSTXML\"\n\tPOSTFILE = \"POSTFILE\"\n\tPUT = \"PUT\"\n\tPUTJSON = \"PUTJSON\"\n\tPUTXML = \"PUTXML\"\n\tPUTFILE = \"PUTFILE\"\n\tDELETE = \"DELETE\"\n\tOTHER = \"OTHER\" \n\n\n\tHTTPFORMContentType = \"application/x-www-form-urlencoded\"\n\tHTTPJSONContentType = \"application/json\"\n\tHTTPXMLContentType = \"text/xml\"\n\tHTTPFILEContentType = \"multipart/form-data\"\n)\n\nvar (\n\tdefaultUserAgent = \"Marmot\"\n\n\tDefaultHeader = map[string][]string{\n\t\t\"User-Agent\": {\n\t\t\tdefaultUserAgent,\n\t\t},\n\t}\n\n\tDefaultTimeOut = 30\n)\n\n\nfunc SetGlobalTimeout(num int) {\n\tDefaultTimeOut = num\n}\n\n\nfunc MergeCookie(before []*http.Cookie, after []*http.Cookie) []*http.Cookie {\n\tcs := make(map[string]*http.Cookie)\n\n\tfor _, b := range before {\n\t\tcs[b.Name] = b\n\t}\n\n\tfor _, a := range after {\n\t\tif len(a.Value) > 0 {\n\t\t\tcs[a.Name] = a\n\t\t}\n\t}\n\n\tres := make([]*http.Cookie, 0, len(cs))\n\n\tfor _, q := range cs {\n\t\tres = append(res, q)\n\t}\n\n\treturn res\n\n}\n\n\n\n\nfunc CloneHeader(h map[string][]string) map[string][]string ", "output": "{\n\tif h == nil || len(h) == 0 {\n\t\th = DefaultHeader\n\t\treturn h\n\t}\n\n\tif len(h[\"User-Agent\"]) == 0 {\n\t\th[\"User-Agent\"] = []string{defaultUserAgent}\n\t}\n\treturn CopyM(h)\n}"} {"input": "package transform\n\nimport (\n\t\"bytes\"\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/drone/drone-exec/yaml\"\n)\n\n\n\nfunc CommandTransform(c *yaml.Config) error {\n\tfor _, p := range c.Pipeline {\n\n\t\tif isPlugin(p) {\n\t\t\tcontinue\n\t\t}\n\n\t\tp.Entrypoint = []string{\n\t\t\t\"/bin/sh\", \"-c\",\n\t\t}\n\t\tp.Command = []string{\n\t\t\t\"echo $DRONE_SCRIPT | base64 -d | /bin/sh -e\",\n\t\t}\n\t\tif p.Environment == nil {\n\t\t\tp.Environment = map[string]string{}\n\t\t}\n\t\tp.Environment[\"HOME\"] = \"/root\"\n\t\tp.Environment[\"SHELL\"] = \"/bin/sh\"\n\t\tp.Environment[\"DRONE_SCRIPT\"] = toScript(\n\t\t\tp.Commands,\n\t\t)\n\t}\n\treturn nil\n}\n\n\n\n\n\nconst setupScript = `\nif [ -n \"$DRONE_NETRC_MACHINE\" ]; then\ncat < $HOME/.netrc\nmachine $DRONE_NETRC_MACHINE\nlogin $DRONE_NETRC_USERNAME\npassword $DRONE_NETRC_PASSWORD\nEOF\nfi\n\nunset DRONE_NETRC_USERNAME\nunset DRONE_NETRC_PASSWORD\nunset DRONE_SCRIPT\n\n%s\n`\n\n\n\nconst traceScript = `\necho + %s\n%s\n`\n\nfunc toScript(commands []string) string ", "output": "{\n\tvar buf bytes.Buffer\n\tfor _, command := range commands {\n\t\tescaped := fmt.Sprintf(\"%q\", command)\n\t\tescaped = strings.Replace(command, \"$\", `$\\`, -1)\n\t\tbuf.WriteString(fmt.Sprintf(\n\t\t\ttraceScript,\n\t\t\tescaped,\n\t\t\tcommand,\n\t\t))\n\t}\n\n\tscript := fmt.Sprintf(\n\t\tsetupScript,\n\t\tbuf.String(),\n\t)\n\n\treturn base64.StdEncoding.EncodeToString([]byte(script))\n}"} {"input": "package sacloud\n\n\ntype propInterfaceDriver struct {\n\tInterfaceDriver EInterfaceDriver `json:\",omitempty\"` \n}\n\n\n\n\n\nfunc (p *propInterfaceDriver) GetInterfaceDriver() EInterfaceDriver {\n\treturn p.InterfaceDriver\n}\n\n\nfunc (p *propInterfaceDriver) SetInterfaceDriverByString(v string) {\n\tp.InterfaceDriver = EInterfaceDriver(v)\n}\n\n\nfunc (p *propInterfaceDriver) GetInterfaceDriverString() string {\n\treturn string(p.InterfaceDriver)\n}\n\nfunc (p *propInterfaceDriver) SetInterfaceDriver(v EInterfaceDriver) ", "output": "{\n\tp.InterfaceDriver = v\n}"} {"input": "package commands\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/asciinema/asciinema/api\"\n)\n\ntype AuthCommand struct {\n\tapi api.API\n}\n\n\n\nfunc (c *AuthCommand) Execute() error {\n\tfmt.Println(\"Open the following URL in a browser to register your API token and assign any recorded asciicasts to your profile:\")\n\tfmt.Println(c.api.AuthUrl())\n\n\treturn nil\n}\n\nfunc NewAuthCommand(api api.API) *AuthCommand ", "output": "{\n\treturn &AuthCommand{api}\n}"} {"input": "package jwk\n\nimport (\n\t\"crypto/rand\"\n\t\"io\"\n\n\t\"github.com/raiqub/jose/converters\"\n)\n\nvar kidGen = DefaultKeyIDGenerator\n\n\n\ntype KeyIDGenerator func() (string, error)\n\n\n\nfunc DefaultKeyIDGenerator() (string, error) {\n\tconst keyIDSize = 16\n\tkidBytes := make([]byte, keyIDSize)\n\n\tif _, err := io.ReadFull(rand.Reader, kidBytes); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn converters.Base64.FromBytes(kidBytes), nil\n}\n\n\n\n\nfunc SetIDGenerator(f KeyIDGenerator) ", "output": "{\n\tkidGen = f\n}"} {"input": "package v2alpha1\n\nimport (\n\t\"github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/util\"\n\tnext \"github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/v2alpha2\"\n\tpkgutil \"github.com/GoogleContainerTools/skaffold/pkg/skaffold/util\"\n)\n\n\n\n\n\n\n\n\n\n\nfunc upgradeOnePipeline(oldPipeline, newPipeline interface{}) error {\n\toldBuild := &oldPipeline.(*Pipeline).Build\n\tnewBuild := &newPipeline.(*next.Pipeline).Build\n\n\tfor i, newArtifact := range newBuild.Artifacts {\n\t\toldArtifact := oldBuild.Artifacts[i]\n\n\t\tkaniko := oldArtifact.KanikoArtifact\n\t\tif kaniko == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tbuildContext := kaniko.BuildContext\n\t\tif buildContext == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif buildContext.LocalDir != nil {\n\t\t\tnewArtifact.KanikoArtifact.InitImage = buildContext.LocalDir.InitImage\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (c *SkaffoldConfig) Upgrade() (util.VersionedConfig, error) ", "output": "{\n\tvar newConfig next.SkaffoldConfig\n\tpkgutil.CloneThroughJSON(c, &newConfig)\n\tnewConfig.APIVersion = next.Version\n\n\terr := util.UpgradePipelines(c, &newConfig, upgradeOnePipeline)\n\treturn &newConfig, err\n}"} {"input": "package reacttype\n\nimport (\n\t\"myitcv.io/react\"\n)\n\n\n\n\n\n\n\n\ntype HelloMessageDef struct {\n\treact.ComponentDef\n}\n\n\n\n\ntype HelloMessageProps struct {\n\tName string\n}\n\n\n\n\ntype HelloMessageState struct {\n\tcount int\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (r HelloMessageDef) Render() react.Element {\n\treturn react.Div(nil,\n\t\treact.S(\"Hello \"+r.Props().Name),\n\t)\n}\n\nfunc HelloMessage(p HelloMessageProps) *HelloMessageElem ", "output": "{\n\treturn buildHelloMessageElem(p)\n}"} {"input": "package admission\n\nimport (\n\t\"io\"\n\n\t\"k8s.io/kubernetes/pkg/admission\"\n\tclient \"k8s.io/kubernetes/pkg/client/unversioned\"\n)\n\n\n\n\n\ntype sccExecRestrictions struct {\n\t*admission.Handler\n\tconstraintAdmission *constraint\n\tclient client.Interface\n}\n\nfunc (d *sccExecRestrictions) Admit(a admission.Attributes) (err error) {\n\tif a.GetOperation() != admission.Connect {\n\t\treturn nil\n\t}\n\tif a.GetResource() != \"pods\" {\n\t\treturn nil\n\t}\n\tif a.GetSubresource() != \"attach\" && a.GetSubresource() != \"exec\" {\n\t\treturn nil\n\t}\n\n\tpod, err := d.client.Pods(a.GetNamespace()).Get(a.GetName())\n\tif err != nil {\n\t\treturn admission.NewForbidden(a, err)\n\t}\n\n\tpod.Spec.ServiceAccountName = \"\"\n\tcreateAttributes := admission.NewAttributesRecord(pod, \"pods\", a.GetNamespace(), a.GetName(), a.GetResource(), a.GetSubresource(), admission.Create, a.GetUserInfo())\n\tif err := d.constraintAdmission.Admit(createAttributes); err != nil {\n\t\treturn admission.NewForbidden(a, err)\n\t}\n\n\treturn nil\n}\n\n\nfunc NewSCCExecRestrictions(client client.Interface) admission.Interface {\n\treturn &sccExecRestrictions{\n\t\tHandler: admission.NewHandler(admission.Connect),\n\t\tconstraintAdmission: NewConstraint(client).(*constraint),\n\t\tclient: client,\n\t}\n}\n\nfunc init() ", "output": "{\n\tadmission.RegisterPlugin(\"SCCExecRestrictions\", func(client client.Interface, config io.Reader) (admission.Interface, error) {\n\t\treturn NewSCCExecRestrictions(client), nil\n\t})\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"context\"\n\n\t\"github.com/go-openapi/strfmt\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\n\ntype Ddns struct {\n\n\tEnabled *bool `json:\"enabled,omitempty\"`\n\n\tFqdn string `json:\"fqdn,omitempty\"`\n\n\tSkipFqdnValidation *bool `json:\"skip_fqdn_validation,omitempty\"`\n\n\tTimeToLive *string `json:\"time_to_live,omitempty\"`\n\n\tUseSecure *bool `json:\"use_secure,omitempty\"`\n}\n\n\nfunc (m *Ddns) Validate(formats strfmt.Registry) error {\n\treturn nil\n}\n\n\nfunc (m *Ddns) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}\n\n\nfunc (m *Ddns) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\n\n\nfunc (m *Ddns) UnmarshalBinary(b []byte) error ", "output": "{\n\tvar res Ddns\n\tif err := swag.ReadJSON(b, &res); err != nil {\n\t\treturn err\n\t}\n\t*m = res\n\treturn nil\n}"} {"input": "package clock\n\nimport (\n\t\"time\"\n)\n\n\n\n\n\ntype Clock interface {\n\tNow() time.Time\n}\n\ntype clock struct{}\n\n\n\n\ntype Mock struct {\n\tcurrentTime time.Time\n}\n\n\nfunc (c *Mock) SetNow(t time.Time) {\n\tc.currentTime = t\n}\n\n\nfunc (c *Mock) Now() time.Time {\n\treturn c.currentTime\n}\n\n\nfunc New() Clock {\n\treturn &clock{}\n}\n\n\nfunc NewMock() *Mock {\n\treturn &Mock{\n\t\tcurrentTime: time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC),\n\t}\n}\n\nfunc (c *clock) Now() time.Time ", "output": "{\n\treturn time.Now()\n}"} {"input": "package armlogic_test\n\nimport (\n\t\"context\"\n\t\"log\"\n\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azidentity\"\n\t\"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/logic/armlogic\"\n)\n\n\nfunc ExampleWorkflowRunActionRepetitionsRequestHistoriesClient_List() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient := armlogic.NewWorkflowRunActionRepetitionsRequestHistoriesClient(\"\", cred, nil)\n\tpager := client.List(\"\",\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\tnil)\n\tfor {\n\t\tnextResult := pager.NextPage(ctx)\n\t\tif err := pager.Err(); err != nil {\n\t\t\tlog.Fatalf(\"failed to advance page: %v\", err)\n\t\t}\n\t\tif !nextResult {\n\t\t\tbreak\n\t\t}\n\t\tfor _, v := range pager.PageResponse().Value {\n\t\t\tlog.Printf(\"Pager result: %#v\\n\", v)\n\t\t}\n\t}\n}\n\n\n\n\nfunc ExampleWorkflowRunActionRepetitionsRequestHistoriesClient_Get() ", "output": "{\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient := armlogic.NewWorkflowRunActionRepetitionsRequestHistoriesClient(\"\", cred, nil)\n\tres, err := client.Get(ctx,\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\tnil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"Response result: %#v\\n\", res.WorkflowRunActionRepetitionsRequestHistoriesClientGetResult)\n}"} {"input": "package ipam\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\t\"github.com/go-openapi/runtime/middleware\"\n\t\"github.com/go-openapi/validate\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\nfunc NewPostIPAMParams() PostIPAMParams {\n\tvar ()\n\treturn PostIPAMParams{}\n}\n\n\n\n\n\ntype PostIPAMParams struct {\n\n\tHTTPRequest *http.Request\n\n\tFamily *string\n}\n\n\n\nfunc (o *PostIPAMParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {\n\tvar res []error\n\to.HTTPRequest = r\n\n\tqs := runtime.Values(r.URL.Query())\n\n\tqFamily, qhkFamily, _ := qs.GetOK(\"family\")\n\tif err := o.bindFamily(qFamily, qhkFamily, route.Formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\n\nfunc (o *PostIPAMParams) validateFamily(formats strfmt.Registry) error {\n\n\tif err := validate.Enum(\"family\", \"query\", *o.Family, []interface{}{\"ipv4\", \"ipv6\"}); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (o *PostIPAMParams) bindFamily(rawData []string, hasKey bool, formats strfmt.Registry) error ", "output": "{\n\tvar raw string\n\tif len(rawData) > 0 {\n\t\traw = rawData[len(rawData)-1]\n\t}\n\tif raw == \"\" { \n\t\treturn nil\n\t}\n\n\to.Family = &raw\n\n\tif err := o.validateFamily(formats); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"input": "package test\n\nimport \"github.com/control-center/serviced/commons/docker\"\nimport \"github.com/stretchr/testify/mock\"\n\ntype MockEventMonitor struct {\n\tmock.Mock\n}\n\nvar _ docker.EventMonitor = &MockEventMonitor{}\n\nfunc (_m *MockEventMonitor) IsActive() bool {\n\tret := _m.Called()\n\n\tvar r0 bool\n\tif rf, ok := ret.Get(0).(func() bool); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(bool)\n\t}\n\n\treturn r0\n}\nfunc (_m *MockEventMonitor) Subscribe(ID string) (*docker.Subscription, error) {\n\tret := _m.Called(ID)\n\n\tvar r0 *docker.Subscription\n\tif rf, ok := ret.Get(0).(func(string) *docker.Subscription); ok {\n\t\tr0 = rf(ID)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*docker.Subscription)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(ID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}\n\n\nfunc (_m *MockEventMonitor) Close() error ", "output": "{\n\tret := _m.Called()\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func() error); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}"} {"input": "package cmd\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/hjma29/ovcli/oneview\"\n)\n\n\n\n\n\n\n\nfunc TestShowSPT(t *testing.T) {\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(oneview.SPTemplateURL, func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.ServeFile(w, r, \"testdata/sptemplate.raw\")\n\t})\n\tmux.HandleFunc(oneview.EGURL, func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.ServeFile(w, r, \"testdata/eg.raw\")\n\t})\n\tmux.HandleFunc(oneview.ServerHWTypeURL, func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.ServeFile(w, r, \"testdata/serverhwt.raw\")\n\t})\n\n\tts := httptest.NewServer(mux)\n\n\tdefer ts.Close()\n\n\ttc := oneview.NewFakeClient(ts.URL, new(bytes.Buffer))\n\n\tcmd := NewShowSPTemplateCmd(tc)\n\tif err := cmd.Execute(); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tout, err := ioutil.ReadAll(tc.Out)\n\tif err != nil {\n\t\tt.Error(\"couldn't read fake client output buffer\")\n\t}\n\n\tgf, err := ioutil.ReadFile(\"testdata/showspt.golden\")\n\tif err != nil {\n\t\tt.Error(\"could not open file \\\"showspt.golden\\\" file\")\n\t}\n\n\tif !bytes.Equal(out, gf) {\n\t\tt.Error(\"show sptemplate displays different than golden file\")\n\n\t}\n\n\n}\n\n\n\nfunc init() ", "output": "{\n\n\tflag.BoolVar(&Debugmode, \"d\", false, \"turn on debug info display\")\n\tflag.Parse()\n\n\tinitConfig()\n\n}"} {"input": "package cli\n\nimport (\n\t\"github.com/spf13/cobra\"\n\n\tcollectorPkg \"github.com/zyndiecate/matic/collector\"\n)\n\nvar (\n\tclientCollector collectorPkg.ClientCollectorI\n\n\tclientCmd = &cobra.Command{\n\t\tUse: \"client\",\n\t\tShort: \"Autogenerate client for web-service\",\n\t\tLong: \"Autogenerate client for web-service\",\n\t\tRun: clientRun,\n\t}\n\n\tlang string\n\troot string\n)\n\nfunc init() {\n\tclientCmd.Flags().StringVarP(&lang, \"lang\", \"l\", \"go\", \"Which language to use to generate client\")\n}\n\n\n\nfunc clientRun(cmd *cobra.Command, args []string) ", "output": "{\n\tswitch lang {\n\tcase \"go\":\n\t\tclientCollector = collectorPkg.NewGoClientCollector()\n\tdefault:\n\t\tcmd.Help()\n\t\tExitStderr(ErrWrongInput)\n\t}\n\n\tswitch len(args) {\n\tcase 0:\n\t\troot = \".\"\n\tcase 1:\n\t\troot = args[0]\n\tdefault:\n\t\tcmd.Help()\n\t\tExitStderr(ErrWrongInput)\n\t}\n\n\terr := clientCollector.GenerateClient(root)\n\tif err != nil {\n\t\tExitStderr(Mask(err))\n\t}\n}"} {"input": "package cluster\n\nimport (\n\t\"github.com/hashicorp/nomad/api\"\n\t\"github.com/jippi/hashi-ui/backend/structs\"\n)\n\nconst (\n\tReconsileSummaries = \"NOMAD_RECONCILE_SYSTEM\"\n)\n\ntype reconsileSummaries struct {\n\taction structs.Action\n\tclient *api.Client\n}\n\n\n\nfunc (w *reconsileSummaries) Do() (structs.Response, error) {\n\terr := w.client.System().ReconcileSummaries()\n\tif err != nil {\n\t\treturn structs.NewErrorResponse(err)\n\t}\n\n\treturn structs.NewSuccessResponse(\"Successfully reconsiled summaries\")\n}\n\nfunc (w *reconsileSummaries) Key() string {\n\treturn \"/system/reconsile_summaries\"\n}\n\nfunc (w *reconsileSummaries) IsMutable() bool {\n\treturn true\n}\n\nfunc (w *reconsileSummaries) BackendType() string {\n\treturn \"nomad\"\n}\n\nfunc NewReconsileSummaries(action structs.Action, client *api.Client) *reconsileSummaries ", "output": "{\n\treturn &reconsileSummaries{\n\t\taction: action,\n\t\tclient: client,\n\t}\n}"} {"input": "package iso20022\n\n\ntype AcknowledgementReason1 struct {\n\n\tCode *AcknowledgementReason1Choice `xml:\"Cd\"`\n\n\tAdditionalReasonInformation *Max210Text `xml:\"AddtlRsnInf,omitempty\"`\n}\n\n\n\nfunc (a *AcknowledgementReason1) SetAdditionalReasonInformation(value string) {\n\ta.AdditionalReasonInformation = (*Max210Text)(&value)\n}\n\nfunc (a *AcknowledgementReason1) AddCode() *AcknowledgementReason1Choice ", "output": "{\n\ta.Code = new(AcknowledgementReason1Choice)\n\treturn a.Code\n}"} {"input": "package clearbit\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\n\n\ntype apiError struct {\n\tErrors []ErrorDetail `json:\"error\"`\n}\n\n\ntype ErrorDetail struct {\n\tType string `json:\"type\"`\n\tMessage string `json:\"message\"`\n}\n\n\ntype ErrorDetailWrapper struct {\n\tError ErrorDetail `json:\"error\"`\n}\n\n\n\n\n\n\n\n\nfunc (e *apiError) UnmarshalJSON(b []byte) (err error) {\n\terrorDetail, errors := ErrorDetailWrapper{}, []ErrorDetail{}\n\tif err = json.Unmarshal(b, &errors); err == nil {\n\t\te.Errors = errors\n\t\treturn\n\t}\n\n\tif err = json.Unmarshal(b, &errorDetail); err == nil {\n\t\terrors = append(errors, errorDetail.Error)\n\t\te.Errors = errors\n\t\treturn\n\t}\n\n\treturn err\n}\n\n\n\nfunc (e *apiError) Empty() bool {\n\treturn len(e.Errors) == 0\n}\n\n\n\n\nfunc relevantError(httpError error, ae apiError) error {\n\tif httpError != nil {\n\t\treturn httpError\n\t}\n\tif ae.Empty() {\n\t\treturn nil\n\t}\n\treturn ae\n}\n\nfunc (e apiError) Error() string ", "output": "{\n\tif len(e.Errors) > 0 {\n\t\terr := e.Errors[0]\n\t\treturn fmt.Sprintf(\"clearbit: %s %v\", err.Type, err.Message)\n\t}\n\treturn \"\"\n}"} {"input": "package grpclog \n\nimport \"os\"\n\nvar logger = newLoggerV2()\n\n\nfunc V(l int) bool {\n\treturn logger.V(l)\n}\n\n\nfunc Info(args ...interface{}) {\n\tlogger.Info(args...)\n}\n\n\nfunc Infof(format string, args ...interface{}) {\n\tlogger.Infof(format, args...)\n}\n\n\n\n\n\nfunc Warning(args ...interface{}) {\n\tlogger.Warning(args...)\n}\n\n\nfunc Warningf(format string, args ...interface{}) {\n\tlogger.Warningf(format, args...)\n}\n\n\nfunc Warningln(args ...interface{}) {\n\tlogger.Warningln(args...)\n}\n\n\nfunc Error(args ...interface{}) {\n\tlogger.Error(args...)\n}\n\n\nfunc Errorf(format string, args ...interface{}) {\n\tlogger.Errorf(format, args...)\n}\n\n\nfunc Errorln(args ...interface{}) {\n\tlogger.Errorln(args...)\n}\n\n\n\nfunc Fatal(args ...interface{}) {\n\tlogger.Fatal(args...)\n\tos.Exit(1)\n}\n\n\n\nfunc Fatalf(format string, args ...interface{}) {\n\tlogger.Fatalf(format, args...)\n\tos.Exit(1)\n}\n\n\n\nfunc Fatalln(args ...interface{}) {\n\tlogger.Fatalln(args...)\n\tos.Exit(1)\n}\n\n\n\n\nfunc Print(args ...interface{}) {\n\tlogger.Info(args...)\n}\n\n\n\n\nfunc Printf(format string, args ...interface{}) {\n\tlogger.Infof(format, args...)\n}\n\n\n\n\nfunc Println(args ...interface{}) {\n\tlogger.Infoln(args...)\n}\n\nfunc Infoln(args ...interface{}) ", "output": "{\n\tlogger.Infoln(args...)\n}"} {"input": "package font\n\nimport (\n\t\"bytes\"\n)\n\nvar alias = map[rune]string{\n\t0x2764: \"\\u2665\", \n\t0x0001f499: \"\\u2665\", \n\t0x0001f49a: \"\\u2665\", \n\t0x0001f49b: \"\\u2665\", \n\t0x0001f49c: \"\\u2665\", \n\t0x0001f49d: \"\\u2665\", \n\t0x0001F601: \":|\", \n\t0x0001F602: \":)\", \n\t0x0001F603: \":D\", \n}\n\ntype Font struct {\n\twidth int\n\theight int\n\tbitmap map[rune][]byte\n}\n\n\n\nfunc (f *Font) Height() int {\n\treturn f.height\n}\n\nfunc (f *Font) Width() int {\n\treturn f.width\n}\n\nfunc (f *Font) Bitmap(c rune) []byte {\n\treturn f.bitmap[c]\n}\n\nfunc ExpandAlias(text string) string ", "output": "{\n\tvar f func(b *bytes.Buffer, s string)\n\tf = func(b *bytes.Buffer, s string) {\n\t\tfor _, c := range s {\n\t\t\tm, ok := alias[c]\n\t\t\tif ok {\n\t\t\t\tf(b, m)\n\t\t\t} else {\n\t\t\t\tb.WriteRune(c)\n\t\t\t}\n\t\t}\n\t}\n\tb := new(bytes.Buffer)\n\tf(b, text)\n\treturn b.String()\n}"} {"input": "package db\n\nimport (\n\t\"time\"\n\n\t\"github.com/boltdb/bolt\"\n\t\"github.com/pkg/errors\"\n)\n\nconst updateSnapshotHistoryBuckets = \"updateSnapshotHistory\"\n\n\n\n\n\n\nfunc UpdateWasEntered(changeID string, db *bolt.DB) (bool, error) {\n\tentered := false\n\n\treturn entered, db.View(func(tx *bolt.Tx) error {\n\n\t\tb := tx.Bucket([]byte(updateSnapshotHistoryBuckets))\n\t\tif b == nil {\n\t\t\treturn errors.New(\"propertyNameBucket bucket not found\")\n\t\t}\n\n\t\tvalue := b.Get([]byte(changeID))\n\t\tentered = value != nil\n\t\treturn nil\n\t})\n}\n\nfunc RecordChangeIDWasEntered(changeID string, db *bolt.DB) error ", "output": "{\n\treturn db.Update(func(tx *bolt.Tx) error {\n\n\t\tb := tx.Bucket([]byte(updateSnapshotHistoryBuckets))\n\t\tif b == nil {\n\t\t\treturn errors.New(\"propertyNameBucket bucket not found\")\n\t\t}\n\n\t\tif value := b.Get([]byte(changeID)); value != nil {\n\t\t\treturn errors.New(\"previous entry time exists for changeID\")\n\t\t}\n\n\t\tnowJSON, err := time.Now().MarshalBinary()\n\t\tif err != nil {\n\t\t\treturn errors.New(\"failed to marshal time.Now to json\")\n\t\t}\n\t\tb.Put([]byte(changeID), nowJSON)\n\n\t\treturn nil\n\t})\n}"} {"input": "package datatransfer \n\nimport (\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc/metadata\"\n)\n\nfunc insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context {\n\tout, _ := metadata.FromOutgoingContext(ctx)\n\tout = out.Copy()\n\tfor _, md := range mds {\n\t\tfor k, v := range md {\n\t\t\tout[k] = append(out[k], v...)\n\t\t}\n\t}\n\treturn metadata.NewOutgoingContext(ctx, out)\n}\n\n\n\n\nfunc DefaultAuthScopes() []string ", "output": "{\n\treturn []string{\n\t\t\"https:www.googleapis.com/auth/bigquery\",\n\t\t\"https:www.googleapis.com/auth/cloud-platform\",\n\t\t\"https:www.googleapis.com/auth/cloud-platform.read-only\",\n\t}\n}"} {"input": "package darwini\n\nimport (\n\t\"net/http\"\n)\n\n\n\n\n\n\n\ntype Method struct {\n\tGET http.HandlerFunc\n\tPOST http.HandlerFunc\n\tPUT http.HandlerFunc\n\tPATCH http.HandlerFunc\n\tDELETE http.HandlerFunc\n\tCustom map[string]http.HandlerFunc\n}\n\nvar _ http.Handler = Method{}\n\n\n\nfunc (m Method) err(w http.ResponseWriter, req *http.Request) {\n\tif m.GET != nil {\n\t\tw.Header().Add(\"Allow\", \"GET\")\n\t}\n\tif m.POST != nil {\n\t\tw.Header().Add(\"Allow\", \"POST\")\n\t}\n\tif m.PUT != nil {\n\t\tw.Header().Add(\"Allow\", \"PUT\")\n\t}\n\tif m.PATCH != nil {\n\t\tw.Header().Add(\"Allow\", \"PATCH\")\n\t}\n\tif m.DELETE != nil {\n\t\tw.Header().Add(\"Allow\", \"DELETE\")\n\t}\n\tfor k, v := range m.Custom {\n\t\tif v != nil {\n\t\t\tw.Header().Add(\"Allow\", k)\n\t\t}\n\t}\n\thttp.Error(w, \"method not allowed\", http.StatusMethodNotAllowed)\n}\n\nfunc (m Method) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\th := m.get(req.Method)\n\tif h == nil {\n\t\tm.err(w, req)\n\t\treturn\n\t}\n\th.ServeHTTP(w, req)\n}\n\nfunc (m Method) get(method string) http.HandlerFunc ", "output": "{\n\tswitch method {\n\tcase \"GET\":\n\t\treturn m.GET\n\tcase \"POST\":\n\t\treturn m.POST\n\tcase \"PUT\":\n\t\treturn m.PUT\n\tcase \"PATCH\":\n\t\treturn m.PATCH\n\tcase \"DELETE\":\n\t\treturn m.DELETE\n\tdefault:\n\t\treturn m.Custom[method]\n\t}\n}"} {"input": "package delete\n\nimport (\n\t\"os\"\n\n\t\"github.com/golang/glog\"\n\t\"github.com/spf13/cobra\"\n\n\t\"k8s.io/test-infra/kind/pkg/cluster\"\n)\n\ntype flags struct {\n\tName string\n}\n\n\n\n\nfunc run(flags *flags, cmd *cobra.Command, args []string) {\n\tconfig := cluster.NewConfig(flags.Name)\n\tctx := cluster.NewContext(config)\n\terr := ctx.Delete()\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to delete cluster: %v\", err)\n\t\tos.Exit(-1)\n\t}\n}\n\nfunc NewCommand() *cobra.Command ", "output": "{\n\tflags := &flags{}\n\tcmd := &cobra.Command{\n\t\tUse: \"delete\",\n\t\tShort: \"Deletes a cluster\",\n\t\tLong: \"Deletes a Kubernetes cluster\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\trun(flags, cmd, args)\n\t\t},\n\t}\n\tcmd.Flags().StringVar(&flags.Name, \"name\", \"\", \"the cluster name\")\n\treturn cmd\n}"} {"input": "package textgen\n\nimport (\n \"math/rand\"\n \"testing\"\n \"time\"\n)\n\nvar (\n text = \"[Test|Text|Guest|Start it|Crash it] [for|not for] [example|fun|you|us]! Oh ya!\"\n)\n\nfunc init() {\n rand.Seed(time.Now().UTC().UnixNano() ^ int64(time.Now().Nanosecond()))\n}\n\n\n\n\n\n\n\nfunc TestProcessRandom(t *testing.T) {\n gen_text, err := ProcessRandom(text, nil)\n t.Logf(\"ProcessRandom: %v, %v\", gen_text, err)\n\n if nil != err {\n t.Error(err)\n }\n}\n\nfunc TestGenerateRandom(t *testing.T) {\n i := 1\n for s := range GenerateRandom(text, 0, 10, true) {\n t.Logf(\"GenerateRandom: %d) %v\", i, s)\n i++\n }\n}\n\nfunc TestGenerate(t *testing.T) {\n i := 1\n for s := range Generate(text, 0) {\n t.Logf(\"Generate: %d) %v\", i, s)\n i++\n }\n}\n\nfunc TestPrepareVariants(t *testing.T) ", "output": "{\n all, variants, err := PrepareVariants(text)\n max := 1\n\n if nil != variants {\n for _, a := range variants {\n max *= len(a)\n }\n }\n\n t.Logf(\"All Variants: %v\", all)\n t.Logf(\"Variants: %v, %v\", variants, err)\n t.Logf(\"Variants MAX: %d\", max)\n\n if nil != err {\n t.Error(err)\n }\n}"} {"input": "package logger\n\nimport (\n\t\"io\"\n\n\t\"github.com/sirupsen/logrus\"\n)\n\nvar _ Logger = Logrus{}\nvar _ FieldLogger = Logrus{}\nvar _ Outable = Logrus{}\n\n\ntype Logrus struct {\n\tlogrus.FieldLogger\n}\n\n\n\nfunc (l Logrus) SetOutput(w io.Writer) {\n\tif lg, ok := l.FieldLogger.(Outable); ok {\n\t\tlg.SetOutput(w)\n\t}\n}\n\n\n\n\n\nfunc (l Logrus) WithFields(m map[string]interface{}) FieldLogger {\n\treturn Logrus{l.FieldLogger.WithFields(m)}\n}\n\nfunc (l Logrus) WithField(s string, i interface{}) FieldLogger ", "output": "{\n\treturn Logrus{l.FieldLogger.WithField(s, i)}\n}"} {"input": "package mvt\n\nimport (\n\t\"fmt\"\n\n\t\"context\"\n\n\t\"github.com/go-spatial/tegola\"\n\t\"github.com/go-spatial/tegola/mvt/vector_tile\"\n)\n\n\ntype Tile struct {\n\tlayers []Layer\n}\n\n\nfunc (t *Tile) AddLayers(layers ...*Layer) error {\n\tfor i := range layers {\n\t\tnl := layers[i]\n\t\tif nl == nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor i, l := range t.layers {\n\t\t\tif l.Name == nl.Name {\n\t\t\t\treturn fmt.Errorf(\"Layer %v, already is named %v, new layer not added.\", i, l.Name)\n\t\t\t}\n\t\t}\n\t\tt.layers = append(t.layers, *nl)\n\t}\n\treturn nil\n}\n\n\n\n\n\n\nfunc (t *Tile) VTile(ctx context.Context, tile *tegola.Tile) (vt *vectorTile.Tile, err error) {\n\tvt = new(vectorTile.Tile)\n\tfor _, l := range t.layers {\n\t\tvtl, err := l.VTileLayer(ctx, tile)\n\t\tif err != nil {\n\t\t\tswitch err {\n\t\t\tcase context.Canceled:\n\t\t\t\treturn nil, err\n\t\t\tdefault:\n\t\t\t\treturn nil, fmt.Errorf(\"Error Getting VTileLayer: %v\", err)\n\t\t\t}\n\t\t}\n\t\tvt.Layers = append(vt.Layers, vtl)\n\t}\n\treturn vt, nil\n}\n\nfunc (t *Tile) Layers() (l []Layer) ", "output": "{\n\tl = append(l, t.layers...)\n\treturn l\n}"} {"input": "package payloads_test\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/01org/ciao/payloads\"\n\t\"github.com/01org/ciao/testutil\"\n\t\"gopkg.in/yaml.v2\"\n)\n\nfunc TestDeleteFailureUnmarshal(t *testing.T) {\n\tvar error ErrorDeleteFailure\n\terr := yaml.Unmarshal([]byte(testutil.DeleteFailureYaml), &error)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif error.InstanceUUID != testutil.InstanceUUID {\n\t\tt.Error(\"Wrong UUID field\")\n\t}\n\n\tif error.Reason != DeleteNoInstance {\n\t\tt.Error(\"Wrong Error field\")\n\t}\n}\n\nfunc TestDeleteFailureMarshal(t *testing.T) {\n\terror := ErrorDeleteFailure{\n\t\tInstanceUUID: testutil.InstanceUUID,\n\t\tReason: DeleteNoInstance,\n\t}\n\n\ty, err := yaml.Marshal(&error)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif string(y) != testutil.DeleteFailureYaml {\n\t\tt.Errorf(\"DeleteFailure marshalling failed\\n[%s]\\n vs\\n[%s]\", string(y), testutil.DeleteFailureYaml)\n\t}\n}\n\n\n\nfunc TestDeleteFailureString(t *testing.T) ", "output": "{\n\tvar stringTests = []struct {\n\t\tr DeleteFailureReason\n\t\texpected string\n\t}{\n\t\t{DeleteNoInstance, \"Instance does not exist\"},\n\t\t{DeleteInvalidPayload, \"YAML payload is corrupt\"},\n\t\t{DeleteInvalidData, \"Command section of YAML payload is corrupt or missing required information\"},\n\t}\n\terror := ErrorDeleteFailure{\n\t\tInstanceUUID: testutil.InstanceUUID,\n\t}\n\tfor _, test := range stringTests {\n\t\terror.Reason = test.r\n\t\ts := error.Reason.String()\n\t\tif s != test.expected {\n\t\t\tt.Errorf(\"expected \\\"%s\\\", got \\\"%s\\\"\", test.expected, s)\n\t\t}\n\t}\n}"} {"input": "package service\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n\t\"net/http\"\n)\n\n\ntype StandardErrorRespModel struct {\n\tErrorMessage string `json:\"error\"`\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc RespondWithSuccessOK(w http.ResponseWriter, respModel interface{}) {\n\tRespondWith(w, http.StatusOK, respModel)\n}\n\n\n\n\n\nfunc RespondWithBadRequestError(w http.ResponseWriter, errMsg string) {\n\tRespondWithError(w, http.StatusBadRequest, errMsg)\n}\n\n\nfunc RespondWithNotFoundError(w http.ResponseWriter, errMsg string) {\n\tRespondWithError(w, http.StatusNotFound, errMsg)\n}\n\n\nfunc RespondWithError(w http.ResponseWriter, httpErrCode int, errMsg string) {\n\tresp := StandardErrorRespModel{\n\t\tErrorMessage: errMsg,\n\t}\n\tRespondWithErrorJSON(w, httpErrCode, resp)\n}\n\n\nfunc RespondWithErrorJSON(w http.ResponseWriter, httpErrCode int, respModel interface{}) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(httpErrCode)\n\tif err := json.NewEncoder(w).Encode(&respModel); err != nil {\n\t\tlog.Println(\" [!] Exception: RespondWithErrorJSON: Error: \", err)\n\t}\n}\n\nfunc RespondWith(w http.ResponseWriter, httpStatusCode int, respModel interface{}) ", "output": "{\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(httpStatusCode)\n\tif err := json.NewEncoder(w).Encode(&respModel); err != nil {\n\t\tlog.Println(\" [!] Exception: RespondWith: Error: \", err)\n\t}\n}"} {"input": "package merkledag\n\nimport (\n\t\"context\"\n\n\tcid \"gx/ipfs/QmPSQnBKM9g7BaUcZCvswUJVscQ1ipjmwxN5PXCjkp9EQ7/go-cid\"\n\tipld \"gx/ipfs/QmR7TcHkR9nxkUorfi8XMTAMLUK7GiP64TWWBzY3aacc1o/go-ipld-format\"\n)\n\n\ntype ErrorService struct {\n\tErr error\n}\n\nvar _ ipld.DAGService = (*ErrorService)(nil)\n\n\nfunc (cs *ErrorService) Add(ctx context.Context, nd ipld.Node) error {\n\treturn cs.Err\n}\n\n\nfunc (cs *ErrorService) AddMany(ctx context.Context, nds []ipld.Node) error {\n\treturn cs.Err\n}\n\n\nfunc (cs *ErrorService) Get(ctx context.Context, c cid.Cid) (ipld.Node, error) {\n\treturn nil, cs.Err\n}\n\n\nfunc (cs *ErrorService) GetMany(ctx context.Context, cids []cid.Cid) <-chan *ipld.NodeOption {\n\tch := make(chan *ipld.NodeOption)\n\tclose(ch)\n\treturn ch\n}\n\n\nfunc (cs *ErrorService) Remove(ctx context.Context, c cid.Cid) error {\n\treturn cs.Err\n}\n\n\n\n\nfunc (cs *ErrorService) RemoveMany(ctx context.Context, cids []cid.Cid) error ", "output": "{\n\treturn cs.Err\n}"} {"input": "package rows\n\nimport (\n\t\"database/sql\"\n\n\t\"github.com/cihangir/gene/example/tinder/models\"\n)\n\n\n\nfunc ProfileRowsScan(rows *sql.Rows, dest interface{}) error ", "output": "{\n\tif rows == nil {\n\t\treturn nil\n\t}\n\n\tvar records []*models.Profile\n\tfor rows.Next() {\n\t\tm := models.NewProfile()\n\t\terr := rows.Scan(\n\t\t\t&m.ID,\n\t\t\t&m.ScreenName,\n\t\t\t&m.Location,\n\t\t\t&m.Description,\n\t\t\t&m.CreatedAt,\n\t\t\t&m.UpdatedAt,\n\t\t\t&m.DeletedAt,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trecords = append(records, m)\n\t}\n\n\tif err := rows.Err(); err != nil {\n\t\treturn err\n\t}\n\n\t*(dest.(*[]*models.Profile)) = records\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\n\tpb \"github.com/azmodb/exp/azmo/azmopb\"\n\t\"golang.org/x/net/context\"\n)\n\nvar putCmd = command{\n\tHelp: `\nPut sets the value for a key. If the key exists and tombstone is true\nthen its previous versions will be overwritten. Supplied key and\nvalue must remain valid for the life of the database.\n\nIt the key exists and the value data type differ, it returns an error.\n`,\n\tShort: \"sets the value for a key\",\n\tArgs: \"[options] key value\",\n\tRun: put,\n}\n\n\n\nfunc put(ctx context.Context, d *dialer, args []string) error ", "output": "{\n\tflags := flag.FlagSet{}\n\tflags.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"%s: put [options] key value\\n\", self)\n\t\tfmt.Fprintf(os.Stderr, \"\\nOptions:\\n\")\n\t\tflags.PrintDefaults()\n\t\tos.Exit(2)\n\t}\n\ttombstone := flags.Bool(\"tombstone\", false, \"overwrite previous values\")\n\tflags.Parse(args)\n\tif flags.NArg() != 2 {\n\t\tflags.Usage()\n\t}\n\targs = flags.Args()\n\n\treq := &pb.PutRequest{\n\t\tKey: []byte(args[0]),\n\t\tValue: []byte(args[1]),\n\t\tTombstone: *tombstone,\n\t}\n\n\tc := d.dial()\n\tdefer c.Close()\n\n\tev, err := c.Put(ctx, req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn encode(ev)\n}"} {"input": "package v1beta1\n\nimport (\n\tv1beta1 \"k8s.io/api/events/v1beta1\"\n\t\"k8s.io/client-go/deprecated/scheme\"\n\trest \"k8s.io/client-go/rest\"\n)\n\ntype EventsV1beta1Interface interface {\n\tRESTClient() rest.Interface\n\tEventsGetter\n}\n\n\ntype EventsV1beta1Client struct {\n\trestClient rest.Interface\n}\n\nfunc (c *EventsV1beta1Client) Events(namespace string) EventInterface {\n\treturn newEvents(c, namespace)\n}\n\n\nfunc NewForConfig(c *rest.Config) (*EventsV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(&config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &EventsV1beta1Client{client}, nil\n}\n\n\n\nfunc NewForConfigOrDie(c *rest.Config) *EventsV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}\n\n\nfunc New(c rest.Interface) *EventsV1beta1Client {\n\treturn &EventsV1beta1Client{c}\n}\n\n\n\n\n\nfunc (c *EventsV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc setConfigDefaults(config *rest.Config) error ", "output": "{\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = &gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"strconv\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/swag\"\n)\n\n\n\n\ntype ControllerStatuses []*ControllerStatus\n\n\n\n\nfunc (m ControllerStatuses) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tfor i := 0; i < len(m); i++ {\n\n\t\tif swag.IsZero(m[i]) { \n\t\t\tcontinue\n\t\t}\n\n\t\tif m[i] != nil {\n\n\t\t\tif err := m[i].Validate(formats); err != nil {\n\t\t\t\tif ve, ok := err.(*errors.Validation); ok {\n\t\t\t\t\treturn ve.ValidateName(strconv.Itoa(i))\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"} {"input": "package inmem\n\nimport (\n\t\"github.com/blevesearch/bleve/index/store\"\n)\n\ntype Reader struct {\n\tstore *Store\n}\n\n\n\nfunc (r *Reader) BytesSafeAfterClose() bool {\n\treturn false\n}\n\nfunc (r *Reader) Get(key []byte) ([]byte, error) {\n\treturn r.store.get(key)\n}\n\nfunc (r *Reader) Iterator(key []byte) store.KVIterator {\n\treturn r.store.iterator(key)\n}\n\nfunc (r *Reader) Close() error {\n\treturn nil\n}\n\nfunc newReader(store *Store) (*Reader, error) ", "output": "{\n\treturn &Reader{\n\t\tstore: store,\n\t}, nil\n}"} {"input": "package memory\n\nimport (\n\t\"log\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/mbertschler/bunny/pkg/data/stored\"\n\t\"github.com/tidwall/buntdb\"\n)\n\ntype itemsTx struct {\n\tparent *Tx\n\ttx *buntdb.Tx\n}\n\nfunc (t *itemsTx) Key(id int) string {\n\treturn itemPrefix + strconv.Itoa(id)\n}\n\nfunc (t *itemsTx) ID(key string) int {\n\tkey = strings.TrimPrefix(key, itemPrefix)\n\ti, err := strconv.Atoi(key)\n\tif err != nil {\n\t\tlog.Println(\"KEY ERROR:\", err)\n\t}\n\treturn i\n}\n\nfunc (t *itemsTx) Get(id int) (stored.Item, error) {\n\tvar item stored.Item\n\tval, err := t.tx.Get(t.Key(id))\n\tif err != nil {\n\t\treturn item, err\n\t}\n\terr = decode(val, &item)\n\treturn item, err\n}\n\nfunc (t *itemsTx) UserItem(user, item int) (stored.Item, error) {\n\ti, err := t.Get(item)\n\tif err != nil {\n\t\treturn i, err\n\t}\n\tfocus, err := t.parent.users.ItemFocus(user, item)\n\ti.Focus = focus\n\treturn i, err\n}\n\nfunc (t *itemsTx) Set(i stored.Item) error {\n\tval, err := encode(i)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, _, err = t.tx.Set(t.Key(i.ID), val, nil)\n\treturn err\n}\n\n\n\nfunc (t *itemsTx) Delete(id int) error {\n\t_, err := t.tx.Delete(t.Key(id))\n\treturn err\n}\n\nfunc (t *itemsTx) New(i stored.Item) (int, error) ", "output": "{\n\tid := 0\n\terr := t.tx.DescendKeys(itemPrefix+\"*\",\n\t\tfunc(key, val string) bool {\n\t\t\tid = t.ID(key)\n\t\t\treturn false\n\t\t})\n\tid++\n\ti.ID = id\n\terr = t.Set(i)\n\treturn id, err\n}"} {"input": "package ray\n\nimport (\n\t\"github.com/v2ray/v2ray-core/common/alloc\"\n)\n\nconst (\n\tbufferSize = 16\n)\n\n\nfunc NewRay() Ray {\n\treturn &directRay{\n\t\tInput: make(chan *alloc.Buffer, bufferSize),\n\t\tOutput: make(chan *alloc.Buffer, bufferSize),\n\t}\n}\n\ntype directRay struct {\n\tInput chan *alloc.Buffer\n\tOutput chan *alloc.Buffer\n}\n\n\n\nfunc (this *directRay) OutboundOutput() chan<- *alloc.Buffer {\n\treturn this.Output\n}\n\nfunc (this *directRay) InboundInput() chan<- *alloc.Buffer {\n\treturn this.Input\n}\n\nfunc (this *directRay) InboundOutput() <-chan *alloc.Buffer {\n\treturn this.Output\n}\n\nfunc (this *directRay) OutboundInput() <-chan *alloc.Buffer ", "output": "{\n\treturn this.Input\n}"} {"input": "package video\n\nimport (\n\t\"sync\"\n\t\"github.com/elliotmr/gdl/event\"\n\t\"github.com/elliotmr/gdl/w32\"\n\t\"github.com/elliotmr/gdl/w32/types/cs\"\n\t\"github.com/elliotmr/gdl/w32/types/wm\"\n\t\"fmt\"\n)\n\nvar GDLAppClass *w32.WindowClass\n\ntype eventHandler struct {\n\twindow *Window\n}\n\n\n\nfunc registerApp(name string, style cs.ClassStyle) error {\n\tvar once sync.Once\n\tonce.Do(func() {\n\t\tfmt.Println(\"registering app\")\n\t\tif name == \"\" {\n\t\t\tname = \"GDL_app\"\n\t\t}\n\t\tif style == 0 {\n\t\t\tstyle = cs.ByteAlignClient | cs.OwnDC | cs.VReDraw | cs.HReDraw\n\t\t}\n\t\tGDLAppClass = &w32.WindowClass{\n\t\t\tName: name,\n\t\t\tStyle: style,\n\t\t}\n\t\terr := GDLAppClass.Register()\n\t\tif err != nil {\n\t\t\tpanic(err) \n\t\t}\n\n\t})\n\treturn nil\n}\n\nfunc (eh *eventHandler) OnMessage(uMsg uint32, wParam, lParam uintptr) (bool, uintptr) ", "output": "{\n\tif event.Q.Enabled(event.SysWMEvent) {\n\t}\n\tswitch uMsg {\n\tcase wm.ShowWindow:\n\t\tif wParam > 0 {\n\t\t\teh.window.SendEvent(event.WindowShown, 0, 0)\n\t\t} else {\n\t\t\teh.window.SendEvent(event.WindowHidden, 0, 0)\n\t\t}\n\tcase wm.Activate:\n\tcase wm.MouseMove:\n\n\t\tfallthrough\n\tcase wm.LButtonUp, wm.LButtonDown, wm.LButtonDblClk, wm.RButtonUp, wm.RButtonDown, wm.RButtonDblClk,\n\t\t wm.MButtonUp, wm.MButtonDown, wm.MButtonDblClk, wm.XButtonUp, wm.XButtonDown, wm.XButtonDblClk:\n\n\t}\n\n\treturn false, 0\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\n\n\nfunc fall(m [][]byte) {\n\tn:=len(m)\n\tfor i:=n-1;i>0;i-- {\n\t\tfor j:=0;j= 0 && mn.Cursor < len(mn.Entries) && !mn.Entries[mn.Cursor].Selectable() {\n\t\tif up {\n\t\t\tmn.Cursor++\n\t\t} else {\n\t\t\tmn.Cursor--\n\t\t}\n\t}\n\n\tif mn.Cursor < 0 {\n\t\tmn.Cursor = 0\n\t}\n\n\tif mn.Cursor >= len(mn.Entries) {\n\t\tmn.Cursor = len(mn.Entries) - 1\n\t}\n}\n\n\nfunc (mn *Menu) Scroll(move int) {\n\tmn.Cursor += move\n\n\tup := move >= 0\n\tmn.scrollToNextSelectable(up)\n\n\tif !mn.Entries[mn.Cursor].Selectable() {\n\t\tmn.scrollToNextSelectable(!up)\n\t}\n}\n\n\nfunc (mn *Menu) Display(width int) error {\n\tfor pos, ClickEntry := range mn.Entries {\n\t\tline := ClickEntry.Render(width, pos == mn.Cursor)\n\t\tif err := mn.lw.Line(mn.Name, pos, line); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\n\n\nfunc (mn *Menu) Click() error ", "output": "{\n\tif len(mn.Entries) == 0 {\n\t\treturn nil\n\t}\n\n\treturn mn.Entries[mn.Cursor].Action()\n}"} {"input": "package primitives\n\nimport (\n \"fmt\"\n . \"github.com/kedebug/LispEx/value\"\n \"math/rand\"\n \"time\"\n)\n\ntype Random struct {\n Primitive\n rand *rand.Rand\n}\n\n\n\nfunc (self *Random) Apply(args []Value) Value {\n if len(args) != 1 {\n panic(fmt.Sprint(\"random: argument mismatch, expected 1\"))\n }\n if val, ok := args[0].(*IntValue); ok {\n if val.Value <= 0 {\n panic(fmt.Sprint(\"random: expected positive integer, given: \", val))\n }\n return NewIntValue(self.rand.Int63n(val.Value))\n }\n panic(fmt.Sprint(\"random: expected integer?, given: \", args[0]))\n}\n\nfunc NewRandom() *Random ", "output": "{\n r := rand.New(rand.NewSource(time.Now().UnixNano()))\n return &Random{Primitive: Primitive{\"random\"}, rand: r}\n}"} {"input": "package main\n\nimport (\n\t\"basic/prof\"\n\t\"bytes\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"pkgtool\"\n\t\"runtime/debug\"\n\t\"strings\"\n)\n\nconst (\n\tARROWS = \"->\"\n)\n\nvar (\n\tpkgImportPathFlag string\n)\n\nfunc init() {\n\tflag.StringVar(&pkgImportPathFlag, \"p\", \"\", \"The path of target package.\")\n}\n\nfunc main() {\n\tprof.Start()\n\tdefer func() {\n\t\tprof.Stop()\n\t\tif err := recover(); err != nil {\n\t\t\tfmt.Errorf(\"FATAL ERROR: %s\", err)\n\t\t\tdebug.PrintStack()\n\t\t}\n\t}()\n\tflag.Parse()\n\tpkgImportPath := getPkgImportPath()\n\tpn := pkgtool.NewPkgNode(pkgImportPath)\n\tfmt.Printf(\"The package node of '%s': %v\\n\", pkgImportPath, *pn)\n\terr := pn.Grow()\n\tif err != nil {\n\t\tfmt.Printf(\"GROW ERROR: %s\\n\", err)\n\t}\n\tfmt.Printf(\"The dependency structure of package '%s':\\n\", pkgImportPath)\n\tShowDepStruct(pn, \"\")\n}\n\nfunc ShowDepStruct(pnode *pkgtool.PkgNode, prefix string) {\n\tvar buf bytes.Buffer\n\tbuf.WriteString(prefix)\n\timportPath := pnode.ImportPath()\n\tbuf.WriteString(importPath)\n\tdeps := pnode.Deps()\n\tif len(deps) == 0 {\n\t\tfmt.Printf(\"%s\\n\", buf.String())\n\t\treturn\n\t}\n\tbuf.WriteString(ARROWS)\n\tfor _, v := range deps {\n\t\tShowDepStruct(v, buf.String())\n\t}\n}\n\n\n\nfunc getPkgImportPath() string ", "output": "{\n\tif len(pkgImportPathFlag) > 0 {\n\t\treturn pkgImportPathFlag\n\t}\n\tfmt.Printf(\"The flag p is invalid, use current dir as package import path.\")\n\tcurrentDir, err := os.Getwd()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tsrcDirs := pkgtool.GetSrcDirs(false)\n\tvar importPath string\n\tfor _, v := range srcDirs {\n\t\tif strings.HasPrefix(currentDir, v) {\n\t\t\timportPath = currentDir[len(v):]\n\t\t\tbreak\n\t\t}\n\t}\n\tif strings.TrimSpace(importPath) == \"\" {\n\t\tpanic(errors.New(\"Can not parse the import path!\"))\n\t}\n\treturn importPath\n}"} {"input": "package github\n\nimport (\n\t\"sync\"\n\n\t\"k8s.io/kubernetes/pkg/util/sets\"\n)\n\n\ntype StatusChange struct {\n\theads map[int]string \n\tpullRequests map[string]sets.Int \n\tchanged sets.String \n\tmutex sync.Mutex\n}\n\n\nfunc NewStatusChange() *StatusChange {\n\treturn &StatusChange{\n\t\theads: map[int]string{},\n\t\tpullRequests: map[string]sets.Int{},\n\t\tchanged: sets.NewString(),\n\t}\n}\n\n\nfunc (s *StatusChange) UpdatePullRequestHead(pullRequestID int, newHead string) {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tif oldHead, has := s.heads[pullRequestID]; has {\n\t\tdelete(s.pullRequests, oldHead)\n\t}\n\ts.heads[pullRequestID] = newHead\n\tif _, has := s.pullRequests[newHead]; !has {\n\t\ts.pullRequests[newHead] = sets.NewInt()\n\t}\n\ts.pullRequests[newHead].Insert(pullRequestID)\n}\n\n\nfunc (s *StatusChange) CommitStatusChanged(commit string) {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\ts.changed.Insert(commit)\n}\n\n\n\n\nfunc (s *StatusChange) PopChangedPullRequests() []int ", "output": "{\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tchangedPullRequests := sets.NewInt()\n\tfor _, commit := range s.changed.List() {\n\t\tif pullRequests, has := s.pullRequests[commit]; has {\n\t\t\tchangedPullRequests = changedPullRequests.Union(pullRequests)\n\t\t}\n\t}\n\ts.changed = sets.NewString()\n\n\treturn changedPullRequests.List()\n}"} {"input": "package hci\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"fmt\"\n)\n\nconst (\n\tpairingRequest = 0x01 \n\tpairingResponse = 0x02 \n\tpairingConfirm = 0x03 \n\tpairingRandom = 0x04 \n\tpairingFailed = 0x05 \n\tencryptionInformation = 0x06 \n\tmasterIdentification = 0x07 \n\tidentiInformation = 0x08 \n\tidentityAddreInformation = 0x09 \n\tsigningInformation = 0x0A \n\tsecurityRequest = 0x0B \n\tpairingPublicKey = 0x0C \n\tpairingDHKeyCheck = 0x0D \n\tpairingKeypress = 0x0E \n)\n\n\n\nfunc (c *Conn) handleSMP(p pdu) error {\n\tlogger.Debug(\"smp\", \"recv\", fmt.Sprintf(\"[%X]\", p))\n\tcode := p[0]\n\tswitch code {\n\tcase pairingRequest:\n\tcase pairingResponse:\n\tcase pairingConfirm:\n\tcase pairingRandom:\n\tcase pairingFailed:\n\tcase encryptionInformation:\n\tcase masterIdentification:\n\tcase identiInformation:\n\tcase identityAddreInformation:\n\tcase signingInformation:\n\tcase securityRequest:\n\tcase pairingPublicKey:\n\tcase pairingDHKeyCheck:\n\tcase pairingKeypress:\n\tdefault:\n\t\treturn nil\n\t}\n\treturn c.sendSMP([]byte{pairingFailed, 0x05})\n}\n\nfunc (c *Conn) sendSMP(p pdu) error ", "output": "{\n\tbuf := bytes.NewBuffer(make([]byte, 0))\n\tbinary.Write(buf, binary.LittleEndian, uint16(4+len(p)))\n\tbinary.Write(buf, binary.LittleEndian, cidSMP)\n\tbinary.Write(buf, binary.LittleEndian, p)\n\t_, err := c.writePDU(buf.Bytes())\n\tlogger.Debug(\"smp\", \"send\", fmt.Sprintf(\"[%X]\", buf.Bytes()))\n\treturn err\n}"} {"input": "package http\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/Cepave/open-falcon-backend/modules/transfer/g\"\n\tlog \"github.com/sirupsen/logrus\"\n\t\"net/http\"\n\t_ \"net/http/pprof\"\n)\n\ntype Dto struct {\n\tMsg string `json:\"msg\"`\n\tData interface{} `json:\"data\"`\n}\n\nfunc Start() {\n\tgo startHttpServer()\n}\nfunc startHttpServer() {\n\tif !g.Config().Http.Enabled {\n\t\treturn\n\t}\n\n\taddr := g.Config().Http.Listen\n\tif addr == \"\" {\n\t\treturn\n\t}\n\n\tconfigCommonRoutes()\n\tconfigProcHttpRoutes()\n\tconfigDebugHttpRoutes()\n\tconfigApiHttpRoutes()\n\n\ts := &http.Server{\n\t\tAddr: addr,\n\t\tMaxHeaderBytes: 1 << 30,\n\t}\n\n\tlog.Println(\"http.startHttpServer ok, listening\", addr)\n\tlog.Fatalln(s.ListenAndServe())\n}\n\nfunc RenderJson(w http.ResponseWriter, v interface{}) {\n\tbs, err := json.Marshal(v)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.Write(bs)\n}\n\nfunc RenderDataJson(w http.ResponseWriter, data interface{}) {\n\tRenderJson(w, Dto{Msg: \"success\", Data: data})\n}\n\n\n\nfunc AutoRender(w http.ResponseWriter, data interface{}, err error) {\n\tif err != nil {\n\t\tRenderMsgJson(w, err.Error())\n\t\treturn\n\t}\n\tRenderDataJson(w, data)\n}\n\nfunc RenderMsgJson(w http.ResponseWriter, msg string) ", "output": "{\n\tRenderJson(w, map[string]string{\"msg\": msg})\n}"} {"input": "package graphql\n\nimport (\n\t\"errors\"\n\n\t\"github.com/equinux/graphql/gqlerrors\"\n\t\"github.com/equinux/graphql/language/ast\"\n)\n\nfunc NewLocatedError(err interface{}, nodes []ast.Node) *gqlerrors.Error {\n\treturn newLocatedError(err, nodes, nil)\n}\n\n\n\nfunc newLocatedError(err interface{}, nodes []ast.Node, path []interface{}) *gqlerrors.Error {\n\tif err, ok := err.(*gqlerrors.Error); ok {\n\t\treturn err\n\t}\n\n\tvar origError error\n\tmessage := \"An unknown error occurred.\"\n\tif err, ok := err.(error); ok {\n\t\tmessage = err.Error()\n\t\torigError = err\n\t}\n\tif err, ok := err.(string); ok {\n\t\tmessage = err\n\t\torigError = errors.New(err)\n\t}\n\tstack := message\n\treturn gqlerrors.NewErrorWithPath(\n\t\tmessage,\n\t\tnodes,\n\t\tstack,\n\t\tnil,\n\t\t[]int{},\n\t\tpath,\n\t\torigError,\n\t)\n}\n\nfunc FieldASTsToNodeASTs(fieldASTs []*ast.Field) []ast.Node {\n\tnodes := []ast.Node{}\n\tfor _, fieldAST := range fieldASTs {\n\t\tnodes = append(nodes, fieldAST)\n\t}\n\treturn nodes\n}\n\nfunc NewLocatedErrorWithPath(err interface{}, nodes []ast.Node, path []interface{}) *gqlerrors.Error ", "output": "{\n\treturn newLocatedError(err, nodes, path)\n}"} {"input": "package internal\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/open-policy-agent/opa/bundle\"\n)\n\n\ntype CustomSigner struct{}\n\n\n\n\n\n\n\nfunc (s *CustomSigner) GenerateSignedToken(files []bundle.FileInfo, sc *bundle.SigningConfig, keyID string) (string, error) ", "output": "{\n\tvar fileNames []string\n\tfor _, file := range files {\n\t\tfileNames = append(fileNames, file.Name)\n\t}\n\treturn fmt.Sprintf(\"some_signature;%s\", strings.Join(fileNames, \";\")), nil\n}"} {"input": "package target\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"testing\"\n)\n\nvar (\n\twrkdir string\n)\n\nfunc init() {\n\tlog.SetOutput(ioutil.Discard)\n\twrkdir, _ = os.Getwd()\n}\n\ntype badWriter struct {\n}\n\nfunc (bw badWriter) Write(p []byte) (n int, err error) {\n\treturn 0, fmt.Errorf(\"bad\")\n}\n\nfunc TestNewMake(t *testing.T) {\n\ttc, _, _ := createTestConfigs(t, nil, nil)\n\t_, err := NewMake(tc)\n\tok(t, err)\n}\n\n\n\nfunc TestMakeRunErr(t *testing.T) {\n\ttc, _, _ := createTestConfigs(t, nil, nil)\n\tm, _ := NewMake(tc)\n\terr := m.Run(\"err\")\n\tif err == nil {\n\t\tt.Fatal(\"expected target not found\")\n\t}\n}\n\nfunc TestMakeRunNoTarget(t *testing.T) {\n\ttc, _, _ := createTestConfigs(t, nil, nil)\n\tm, _ := NewMake(tc)\n\terr := m.Run(\"prop\")\n\tif err == nil {\n\t\tt.Fatal(\"expected target not found\")\n\t}\n}\n\nfunc TestMakeRun(t *testing.T) ", "output": "{\n\ttc, tcW, _ := createTestConfigs(t, nil, nil)\n\tm, _ := NewMake(tc)\n\terr := m.Run(\"ron:prep\")\n\tok(t, err)\n\twant := \"hello\\nprep1\\nprep2\\nprep3\\nprep4\\ngoodbye\\n\"\n\tequals(t, want, tcW.String())\n}"} {"input": "package httpmux\n\nimport \"net/http\"\n\n\ntype ConfigOption interface {\n\tSet(c *Config)\n}\n\n\ntype ConfigOptionFunc func(c *Config)\n\n\nfunc (f ConfigOptionFunc) Set(c *Config) { f(c) }\n\n\nfunc WithPrefix(prefix string) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.Prefix = prefix })\n}\n\n\nfunc WithMiddleware(mw ...Middleware) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.Middleware = mw })\n}\n\n\nfunc WithMiddlewareFunc(mw ...MiddlewareFunc) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.UseFunc(mw...) })\n}\n\n\nfunc WithRedirectTrailingSlash(v bool) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.RedirectTrailingSlash = v })\n}\n\n\nfunc WithRedirectFixedPath(v bool) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.RedirectFixedPath = v })\n}\n\n\nfunc WithHandleMethodNotAllowed(v bool) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.HandleMethodNotAllowed = v })\n}\n\n\nfunc WithNotFound(f http.Handler) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.NotFound = f })\n}\n\n\n\n\n\nfunc WithPanicHandler(f func(http.ResponseWriter, *http.Request, interface{})) ConfigOption {\n\treturn ConfigOptionFunc(func(c *Config) { c.PanicHandler = f })\n}\n\nfunc WithMethodNotAllowed(f http.Handler) ConfigOption ", "output": "{\n\treturn ConfigOptionFunc(func(c *Config) { c.MethodNotAllowed = f })\n}"} {"input": "package internal\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"gopkg.in/reform.v1\"\n)\n\n\ntype Logger struct {\n\tprintf reform.Printf\n\tdebug bool\n}\n\n\nfunc NewLogger(prefix string, debug bool) *Logger {\n\tvar flags int\n\tif debug {\n\t\tflags = log.Ldate | log.Lmicroseconds | log.Lshortfile\n\t}\n\n\tl := log.New(os.Stderr, prefix, flags)\n\treturn &Logger{\n\t\tprintf: func(format string, args ...interface{}) {\n\t\t\tl.Output(3, fmt.Sprintf(format, args...))\n\t\t},\n\t\tdebug: debug,\n\t}\n}\n\n\n\n\n\n\nfunc (l *Logger) Printf(format string, args ...interface{}) {\n\tl.printf(format, args...)\n}\n\n\nfunc (l *Logger) Fatalf(format string, args ...interface{}) {\n\tl.printf(format, args...)\n\tif l.debug {\n\t\tpanic(fmt.Sprintf(format, args...))\n\t}\n\tos.Exit(1)\n}\n\nfunc (l *Logger) Debugf(format string, args ...interface{}) ", "output": "{\n\tif l.debug {\n\t\tl.printf(format, args...)\n\t}\n}"} {"input": "package igdman\n\nimport (\n\t\"fmt\"\n\t\"os/exec\"\n\t\"regexp\"\n\t\"time\"\n)\n\nvar (\n\tsearchRegex *regexp.Regexp\n)\n\n\n\nfunc defaultGatewayIp() (string, error) {\n\tlog.Trace(\"Calling netstat\")\n\tcmd := exec.Command(\"netstat\", \"-f\", \"inet\", \"-rn\")\n\tout, err := execTimeout(10*time.Second, cmd)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Unable to call netstat: %s\\n%s\", err, out)\n\t}\n\tlog.Tracef(\"Netstat output\\n------------\\n%s\\n\\n\", out)\n\n\tsubmatches := searchRegex.FindSubmatch(out)\n\tif len(submatches) < 2 {\n\t\treturn \"\", fmt.Errorf(\"Unable to find default gateway in netstat output: \\n%s\", out)\n\t}\n\n\treturn string(submatches[1]), nil\n}\n\nfunc init() ", "output": "{\n\tvar err error\n\tsearchRegex, err = regexp.Compile(\".*default\\\\s+([0-9]{1,3}\\\\.[0-9]{1,3}\\\\.[0-9,]{1,3}\\\\.[0-9,]{1,3})\\\\.*\")\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to compile searchRegex: %s\", err)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/kormat/go-slackapi/config\"\n\t\"github.com/kormat/go-slackapi/users\"\n)\n\ntype UserInfo struct {\n\tArgs struct {\n\t\tID string `description:\"User ID\"`\n\t} `positional-args:\"yes\" required:\"yes\"`\n}\ntype UserList struct{}\n\nvar userInfo UserInfo\nvar userList UserList\n\nfunc init() {\n\tparser.AddCommand(\"users.info\", \"Show user info\", \"\", &userInfo)\n\tparser.AddCommand(\"users.list\", \"List users\", \"\", &userList)\n}\n\nfunc (u *UserInfo) Execute(_ []string) error {\n\tif config.CfgErr != nil {\n\t\treturn config.CfgErr\n\t}\n\tinfo, err := users.Info(u.Args.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(info)\n\treturn nil\n}\n\n\n\nfunc (ul *UserList) Execute(_ []string) error ", "output": "{\n\tif config.CfgErr != nil {\n\t\treturn config.CfgErr\n\t}\n\tulist, err := users.List()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor i, u := range ulist {\n\t\tfmt.Printf(\"%d. `%s` (Id: %s)\\n\", i, u.Name, u.ID)\n\t}\n\treturn nil\n}"} {"input": "package operations\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n)\n\n\nconst DeleteDeploymentOKCode int = 200\n\n\ntype DeleteDeploymentOK struct {\n}\n\n\nfunc NewDeleteDeploymentOK() *DeleteDeploymentOK {\n\treturn &DeleteDeploymentOK{}\n}\n\n\nfunc (o *DeleteDeploymentOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(200)\n}\n\n\nconst DeleteDeploymentUnauthorizedCode int = 401\n\n\ntype DeleteDeploymentUnauthorized struct {\n\tWWWAuthenticate string `json:\"WWW_Authenticate\"`\n}\n\n\nfunc NewDeleteDeploymentUnauthorized() *DeleteDeploymentUnauthorized {\n\treturn &DeleteDeploymentUnauthorized{}\n}\n\n\nfunc (o *DeleteDeploymentUnauthorized) WithWWWAuthenticate(wWWAuthenticate string) *DeleteDeploymentUnauthorized {\n\to.WWWAuthenticate = wWWAuthenticate\n\treturn o\n}\n\n\nfunc (o *DeleteDeploymentUnauthorized) SetWWWAuthenticate(wWWAuthenticate string) {\n\to.WWWAuthenticate = wWWAuthenticate\n}\n\n\nfunc (o *DeleteDeploymentUnauthorized) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\n\twWWAuthenticate := o.WWWAuthenticate\n\tif wWWAuthenticate != \"\" {\n\t\trw.Header().Set(\"WWW_Authenticate\", wWWAuthenticate)\n\t}\n\n\trw.WriteHeader(401)\n}\n\n\nconst DeleteDeploymentNotFoundCode int = 404\n\n\ntype DeleteDeploymentNotFound struct {\n}\n\n\nfunc NewDeleteDeploymentNotFound() *DeleteDeploymentNotFound {\n\treturn &DeleteDeploymentNotFound{}\n}\n\n\n\n\n\nconst DeleteDeploymentInternalServerErrorCode int = 500\n\n\ntype DeleteDeploymentInternalServerError struct {\n}\n\n\nfunc NewDeleteDeploymentInternalServerError() *DeleteDeploymentInternalServerError {\n\treturn &DeleteDeploymentInternalServerError{}\n}\n\n\nfunc (o *DeleteDeploymentInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(500)\n}\n\nfunc (o *DeleteDeploymentNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) ", "output": "{\n\n\trw.WriteHeader(404)\n}"} {"input": "package tests\n\n\ntype EmbeddedType struct {\n\tEmbeddedInnerType\n\tInner struct {\n\t\tEmbeddedInnerType\n\t}\n\tField2 int\n\tEmbeddedInnerType2 `json:\"named\"`\n}\n\ntype EmbeddedInnerType struct {\n\tField1 int\n}\n\ntype EmbeddedInnerType2 struct {\n\tField3 int\n}\n\nvar embeddedTypeValue EmbeddedType\n\n\n\nvar embeddedTypeValueString = `{\"Inner\":{\"Field1\":3},\"Field2\":2,\"named\":{\"Field3\":4},\"Field1\":1}`\n\nfunc init() ", "output": "{\n\tembeddedTypeValue.Field1 = 1\n\tembeddedTypeValue.Field2 = 2\n\tembeddedTypeValue.Inner.Field1 = 3\n\tembeddedTypeValue.Field3 = 4\n}"} {"input": "package geom\n\nimport (\n\t\"github.com/gmacd/rays/core\"\n)\n\n\n\n\ntype Light interface {\n\tIsLight() bool\n\tSetIsLight(isLight bool)\n\tLightCentre() core.Vec3\n}\n\ntype LightData struct {\n\tisLight bool\n\tpos core.Vec3\n}\n\nfunc NewLightData(pos core.Vec3) *LightData {\n\treturn &LightData{false, pos}\n}\n\nfunc NewLightDataNone() *LightData {\n\treturn &LightData{false, core.NewVec3Zero()}\n}\n\nfunc (light *LightData) IsLight() bool {\n\treturn light.isLight\n}\n\nfunc (light *LightData) SetIsLight(isLight bool) {\n\tlight.isLight = isLight\n}\n\n\n\nfunc (light *LightData) LightCentre() core.Vec3 ", "output": "{\n\treturn light.pos\n}"} {"input": "package loadbalancer\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n\t\"net/http\"\n)\n\n\n\n\n\n\ntype CreateListenerRequest struct {\n\n\tCreateListenerDetails `contributesTo:\"body\"`\n\n\tLoadBalancerId *string `mandatory:\"true\" contributesTo:\"path\" name:\"loadBalancerId\"`\n\n\tOpcRequestId *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-request-id\"`\n\n\tOpcRetryToken *string `mandatory:\"false\" contributesTo:\"header\" name:\"opc-retry-token\"`\n\n\tRequestMetadata common.RequestMetadata\n}\n\nfunc (request CreateListenerRequest) String() string {\n\treturn common.PointerString(request)\n}\n\n\nfunc (request CreateListenerRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)\n}\n\n\nfunc (request CreateListenerRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {\n\n\treturn nil, false\n\n}\n\n\nfunc (request CreateListenerRequest) RetryPolicy() *common.RetryPolicy {\n\treturn request.RequestMetadata.RetryPolicy\n}\n\n\ntype CreateListenerResponse struct {\n\n\tRawResponse *http.Response\n\n\tOpcWorkRequestId *string `presentIn:\"header\" name:\"opc-work-request-id\"`\n\n\tOpcRequestId *string `presentIn:\"header\" name:\"opc-request-id\"`\n}\n\nfunc (response CreateListenerResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response CreateListenerResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package hooks\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"regexp\"\n\n\t\"github.com/cloudfoundry/libbuildpack\"\n)\n\ntype AppHook struct {\n\tlibbuildpack.DefaultHook\n}\n\nfunc init() {\n\tlibbuildpack.AddHook(AppHook{})\n}\n\n\n\nfunc (h AppHook) AfterCompile(compiler *libbuildpack.Stager) error {\n\treturn runHook(\"post_compile\", compiler)\n}\n\nfunc runHook(scriptName string, compiler *libbuildpack.Stager) error {\n\tpath := filepath.Join(compiler.BuildDir(), \"bin\", scriptName)\n\tif exists, err := libbuildpack.FileExists(path); err != nil {\n\t\treturn err\n\t} else if exists {\n\t\tcompiler.Logger().BeginStep(\"Running \" + scriptName + \" hook\")\n\t\tif err := os.Chmod(path, 0755); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfileContents, err := ioutil.ReadFile(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tshebangRegex := regexp.MustCompile(\"^\\\\s*#!\")\n\t\thasShebang := shebangRegex.Match(fileContents)\n\n\t\tvar cmd *exec.Cmd\n\t\tif hasShebang {\n\t\t\tcmd = exec.Command(path)\n\t\t} else {\n\t\t\tcmd = exec.Command(\"/bin/sh\", path)\n\t\t}\n\n\t\tcmd.Dir = compiler.BuildDir()\n\t\toutput, err := cmd.CombinedOutput()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcompiler.Logger().Info(\"%s\", output)\n\t}\n\treturn nil\n\n}\n\nfunc (h AppHook) BeforeCompile(compiler *libbuildpack.Stager) error ", "output": "{\n\treturn runHook(\"pre_compile\", compiler)\n}"} {"input": "package events\n\nimport (\n\t\"errors\"\n\n\t\"github.com/miketheprogrammer/go-thrust/lib/commands\"\n\t\"github.com/miketheprogrammer/go-thrust/lib/dispatcher\"\n)\n\n\nfunc NewHandler(event string, fn interface{}) (ThrustEventHandler, error) {\n\th := ThrustEventHandler{}\n\th.Event = event\n\th.Type = \"event\"\n\terr := h.SetHandleFunc(fn)\n\tdispatcher.RegisterHandler(h)\n\treturn h, err\n}\n\n\ntype Handler interface {\n\tHandle(cr commands.CommandResponse)\n\tRegister()\n\tSetHandleFunc(fn interface{})\n}\n\ntype ThrustEventHandler struct {\n\tType string\n\tEvent string\n\tHandler interface{}\n}\n\n\n\nfunc (teh *ThrustEventHandler) SetHandleFunc(fn interface{}) error {\n\tif fn, ok := fn.(func(commands.CommandResponse)); ok == true {\n\t\tteh.Handler = fn\n\t\treturn nil\n\t}\n\tif fn, ok := fn.(func(commands.EventResult)); ok == true {\n\t\tteh.Handler = fn\n\t\treturn nil\n\t}\n\n\treturn errors.New(\"Invalid Handler Definition\")\n}\n\nfunc (teh ThrustEventHandler) Handle(cr commands.CommandResponse) ", "output": "{\n\tif cr.Action != \"event\" {\n\t\treturn\n\t}\n\tif cr.Type != teh.Event && teh.Event != \"*\" {\n\t\treturn\n\t}\n\tcr.Event.Type = cr.Type\n\tif fn, ok := teh.Handler.(func(commands.CommandResponse)); ok == true {\n\t\tfn(cr)\n\t\treturn\n\t}\n\tif fn, ok := teh.Handler.(func(commands.EventResult)); ok == true {\n\t\tfn(cr.Event)\n\t\treturn\n\t}\n}"} {"input": "package queue\n\nimport \"context\"\n\n\ntype Client struct {\n\tContent []byte\n\terr error\n}\n\n\n\n\n\nfunc NewClient(options ...func(*Client)) *Client {\n\tc := &Client{}\n\n\tfor _, option := range options {\n\t\toption(c)\n\t}\n\n\treturn c\n}\n\n\nfunc ClientError(err error) func(*Client) {\n\treturn func(c *Client) {\n\t\tc.err = err\n\t}\n}\n\nfunc (c *Client) Push(ctx context.Context, content []byte) error ", "output": "{\n\tif c.err != nil {\n\t\treturn c.err\n\t}\n\tc.Content = content\n\treturn nil\n}"} {"input": "package mesh\n\nimport (\n\t\"time\"\n)\n\n\n\ntype tokenBucket struct {\n\tcapacity int64 \n\ttokenInterval time.Duration \n\trefillDuration time.Duration \n\tearliestUnspentToken time.Time\n}\n\n\n\n\n\n\n\nfunc (tb *tokenBucket) wait() {\n\ttime.Sleep(time.Until(tb.earliestUnspentToken))\n\n\tcapacityToken := tb.capacityToken()\n\tif tb.earliestUnspentToken.Before(capacityToken) {\n\t\ttb.earliestUnspentToken = capacityToken\n\t}\n\n\ttb.earliestUnspentToken = tb.earliestUnspentToken.Add(tb.tokenInterval)\n}\n\n\nfunc (tb *tokenBucket) capacityToken() time.Time {\n\treturn time.Now().Add(-tb.refillDuration).Truncate(tb.tokenInterval)\n}\n\nfunc newTokenBucket(capacity int64, tokenInterval time.Duration) *tokenBucket ", "output": "{\n\ttb := tokenBucket{\n\t\tcapacity: capacity,\n\t\ttokenInterval: tokenInterval,\n\t\trefillDuration: tokenInterval * time.Duration(capacity)}\n\n\ttb.earliestUnspentToken = tb.capacityToken()\n\n\treturn &tb\n}"} {"input": "package builder\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\n\tvelerov1api \"github.com/vmware-tanzu/velero/pkg/apis/velero/v1\"\n)\n\n\ntype PodVolumeBackupBuilder struct {\n\tobject *velerov1api.PodVolumeBackup\n}\n\n\nfunc ForPodVolumeBackup(ns, name string) *PodVolumeBackupBuilder {\n\treturn &PodVolumeBackupBuilder{\n\t\tobject: &velerov1api.PodVolumeBackup{\n\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\tAPIVersion: velerov1api.SchemeGroupVersion.String(),\n\t\t\t\tKind: \"PodVolumeBackup\",\n\t\t\t},\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: ns,\n\t\t\t\tName: name,\n\t\t\t},\n\t\t},\n\t}\n}\n\n\n\n\n\nfunc (b *PodVolumeBackupBuilder) ObjectMeta(opts ...ObjectMetaOpt) *PodVolumeBackupBuilder {\n\tfor _, opt := range opts {\n\t\topt(b.object)\n\t}\n\n\treturn b\n}\n\n\nfunc (b *PodVolumeBackupBuilder) Phase(phase velerov1api.PodVolumeBackupPhase) *PodVolumeBackupBuilder {\n\tb.object.Status.Phase = phase\n\treturn b\n}\n\n\nfunc (b *PodVolumeBackupBuilder) SnapshotID(snapshotID string) *PodVolumeBackupBuilder {\n\tb.object.Status.SnapshotID = snapshotID\n\treturn b\n}\n\n\nfunc (b *PodVolumeBackupBuilder) PodName(name string) *PodVolumeBackupBuilder {\n\tb.object.Spec.Pod.Name = name\n\treturn b\n}\n\n\nfunc (b *PodVolumeBackupBuilder) Volume(volume string) *PodVolumeBackupBuilder {\n\tb.object.Spec.Volume = volume\n\treturn b\n}\n\nfunc (b *PodVolumeBackupBuilder) Result() *velerov1api.PodVolumeBackup ", "output": "{\n\treturn b.object\n}"} {"input": "package readline\n\nimport \"io\"\n\ntype Instance struct {\n\tt *Terminal\n\to *Operation\n}\n\ntype Config struct {\n\tPrompt string\n\tHistoryFile string\n}\n\nfunc NewEx(cfg *Config) (*Instance, error) {\n\tt, err := NewTerminal(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trl := t.Readline()\n\treturn &Instance{\n\t\tt: t,\n\t\to: rl,\n\t}, nil\n}\n\nfunc New(prompt string) (*Instance, error) {\n\treturn NewEx(&Config{Prompt: prompt})\n}\n\nfunc (i *Instance) Stdout() io.Writer {\n\treturn i.o.Stdout()\n}\n\nfunc (i *Instance) Stderr() io.Writer {\n\treturn i.o.Stderr()\n}\n\nfunc (i *Instance) Readline() (string, error) {\n\treturn i.o.String()\n}\n\nfunc (i *Instance) ReadSlice() ([]byte, error) {\n\treturn i.o.Slice()\n}\n\n\n\nfunc (i *Instance) Close() error ", "output": "{\n\tif err := i.t.Close(); err != nil {\n\t\treturn err\n\t}\n\ti.o.Close()\n\treturn nil\n}"} {"input": "package testbackend\n\nimport (\n\t\"context\"\n\n\t\"github.com/stripe/veneur/v14/ssf\"\n\t\"github.com/stripe/veneur/v14/trace\"\n)\n\n\n\ntype SendErrorSource func(*ssf.SSFSpan) error\n\n\n\ntype BackendOption func(*Backend)\n\n\n\nfunc SendErrors(src SendErrorSource) BackendOption {\n\treturn func(be *Backend) {\n\t\tbe.errorSrc = src\n\t}\n}\n\n\n\ntype Backend struct {\n\tch chan<- *ssf.SSFSpan\n\terrorSrc SendErrorSource\n}\n\n\n\n\n\nfunc (be *Backend) SendSync(ctx context.Context, span *ssf.SSFSpan) error {\n\tif be.errorSrc != nil {\n\t\tif err := be.errorSrc(span); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tselect {\n\tcase be.ch <- span:\n\t\treturn nil\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n}\n\n\n\nfunc NewBackend(ch chan<- *ssf.SSFSpan, opts ...BackendOption) trace.ClientBackend {\n\tbe := &Backend{ch: ch}\n\tfor _, opt := range opts {\n\t\topt(be)\n\t}\n\treturn be\n}\n\nfunc (be *Backend) Close() error ", "output": "{\n\treturn nil\n}"} {"input": "package cpf\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\nfunc Valid(digits string) (bool, error) {\n\treturn valid(digits)\n}\n\n\n\nfunc valid(data string) (bool, error) {\n\tdata = sanitize(data)\n\n\tif len(data) != 11 {\n\t\treturn false, errors.New(\"Invalid length\")\n\t}\n\n\tif strings.Contains(blacklist, data) || !check(data) {\n\t\treturn false, errors.New(\"Invalid value\")\n\t}\n\n\treturn true, nil\n}\n\nconst blacklist = `00000000000\n11111111111\n22222222222\n33333333333\n44444444444\n55555555555\n66666666666\n77777777777\n88888888888\n99999999999\n12345678909`\n\nfunc stringToIntSlice(data string) (res []int) {\n\tfor _, d := range data {\n\t\tx, err := strconv.Atoi(string(d))\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tres = append(res, x)\n\t}\n\treturn\n}\n\nfunc verify(data []int, n int) int {\n\tvar total int\n\n\tfor i := 0; i < n; i++ {\n\t\ttotal += data[i] * (n + 1 - i)\n\t}\n\n\ttotal = total % 11\n\tif total < 2 {\n\t\treturn 0\n\t}\n\treturn 11 - total\n}\n\nfunc check(data string) bool {\n\treturn checkEach(data, 9) && checkEach(data, 10)\n}\n\nfunc checkEach(data string, n int) bool {\n\tfinal := verify(stringToIntSlice(data), n)\n\n\tx, err := strconv.Atoi(string(data[n]))\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn final == x\n}\n\nfunc sanitize(data string) string ", "output": "{\n\tdata = strings.Replace(data, \".\", \"\", -1)\n\tdata = strings.Replace(data, \"-\", \"\", -1)\n\treturn data\n}"} {"input": "package validation\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"k8s.io/api/core/v1\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/client-go/kubernetes/fake\"\n)\n\n\n\n\n\n\n\n\n\n\n\nfunc TestWaitForNodeToBeNotReady(t *testing.T) {\n\tconditions := []v1.NodeCondition{{Type: \"Ready\", Status: \"False\"}}\n\tnodeName := \"node-foo\"\n\tnodeAA := setupNodeAA(t, conditions, nodeName)\n\n\ttest, err := nodeAA.WaitForNodeToBeNotReady(nodeName)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif test != true {\n\t\tt.Fatalf(\"unexpected error WaitForNodeToBeNotReady Failed: %v\", test)\n\t}\n}\n\n\n\n\n\nfunc setupNodeAA(t *testing.T, conditions []v1.NodeCondition, nodeName string) *NodeAPIAdapter {\n\tnode := &v1.Node{\n\t\tObjectMeta: metav1.ObjectMeta{Name: nodeName},\n\t\tSpec: v1.NodeSpec{Unschedulable: false},\n\t\tStatus: v1.NodeStatus{Conditions: conditions},\n\t}\n\n\tc := fake.NewSimpleClientset(node)\n\tnodeAA, err := NewNodeAPIAdapter(c, time.Duration(10)*time.Millisecond)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error building NodeAPIAdapter: %v\", err)\n\t}\n\treturn nodeAA\n}\n\nfunc TestWaitForNodeToBeReady(t *testing.T) ", "output": "{\n\tconditions := []v1.NodeCondition{{Type: \"Ready\", Status: \"True\"}}\n\tnodeName := \"node-foo\"\n\tnodeAA := setupNodeAA(t, conditions, nodeName)\n\n\ttest, err := nodeAA.WaitForNodeToBeReady(nodeName)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif test != true {\n\t\tt.Fatalf(\"unexpected error WaitForNodeToBeReady Failed: %v\", test)\n\t}\n}"} {"input": "package routing\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestNewHttpError(t *testing.T) ", "output": "{\n\te := NewHTTPError(http.StatusNotFound)\n\tassert.Equal(t, http.StatusNotFound, e.StatusCode())\n\tassert.Equal(t, http.StatusText(http.StatusNotFound), e.Error())\n\n\te = NewHTTPError(http.StatusNotFound, \"abc\")\n\tassert.Equal(t, http.StatusNotFound, e.StatusCode())\n\tassert.Equal(t, \"abc\", e.Error())\n\n\ts, _ := json.Marshal(e)\n\tassert.Equal(t, `{\"status\":404,\"message\":\"abc\"}`, string(s))\n}"} {"input": "package domain\n\n\nfunc MathPaymentMethodFlag(methods []int) int {\n\tf := 0\n\tfor _, v := range methods {\n\t\tf |= 1 << uint(v-1)\n\t}\n\treturn f\n}\n\n\n\n\nfunc AndPayMethod(payFlag int, method int) bool ", "output": "{\n\tf := 1 << uint(method-1)\n\treturn payFlag&f == f\n}"} {"input": "package stdlib\n\nimport (\n\t\"net/http/httptrace\"\n\t\"reflect\"\n)\n\n\n\nfunc init() ", "output": "{\n\tSymbols[\"net/http/httptrace\"] = map[string]reflect.Value{\n\t\t\"ContextClientTrace\": reflect.ValueOf(httptrace.ContextClientTrace),\n\t\t\"WithClientTrace\": reflect.ValueOf(httptrace.WithClientTrace),\n\n\t\t\"ClientTrace\": reflect.ValueOf((*httptrace.ClientTrace)(nil)),\n\t\t\"DNSDoneInfo\": reflect.ValueOf((*httptrace.DNSDoneInfo)(nil)),\n\t\t\"DNSStartInfo\": reflect.ValueOf((*httptrace.DNSStartInfo)(nil)),\n\t\t\"GotConnInfo\": reflect.ValueOf((*httptrace.GotConnInfo)(nil)),\n\t\t\"WroteRequestInfo\": reflect.ValueOf((*httptrace.WroteRequestInfo)(nil)),\n\t}\n}"} {"input": "package xml2json\n\nimport (\n\t\"strings\"\n)\n\n\ntype Node struct {\n\tChildren map[string]Nodes\n\tData string\n\tChildrenAlwaysAsArray bool\n}\n\n\ntype Nodes []*Node\n\n\nfunc (n *Node) AddChild(s string, c *Node) {\n\tif n.Children == nil {\n\t\tn.Children = map[string]Nodes{}\n\t}\n\n\tn.Children[s] = append(n.Children[s], c)\n}\n\n\n\n\n\nfunc (n *Node) GetChild(path string) *Node {\n\tresult := n\n\tnames := strings.Split(path, \".\")\n\tfor _, name := range names {\n\t\tchildren, exists := result.Children[name]\n\t\tif !exists {\n\t\t\treturn nil\n\t\t}\n\t\tif len(children) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\tresult = children[0]\n\t}\n\treturn result\n}\n\nfunc (n *Node) IsComplex() bool ", "output": "{\n\treturn len(n.Children) > 0\n}"} {"input": "package gzip\n\nimport (\n\t\"net/http\"\n\t\"path\"\n\n\t\"github.com/mholt/caddy/middleware\"\n)\n\n\ntype Filter interface {\n\tShouldCompress(*http.Request) bool\n}\n\n\nvar defaultExtensions = []string{\"\", \".txt\", \".htm\", \".html\", \".css\", \".php\", \".js\", \".json\", \".md\", \".xml\"}\n\n\nfunc DefaultExtFilter() ExtFilter {\n\tm := ExtFilter{Exts: make(Set)}\n\tfor _, extension := range defaultExtensions {\n\t\tm.Exts.Add(extension)\n\t}\n\treturn m\n}\n\n\ntype ExtFilter struct {\n\tExts Set\n}\n\n\nconst ExtWildCard = \"*\"\n\n\n\n\nfunc (e ExtFilter) ShouldCompress(r *http.Request) bool {\n\text := path.Ext(r.URL.Path)\n\treturn e.Exts.Contains(ExtWildCard) || e.Exts.Contains(ext)\n}\n\n\ntype PathFilter struct {\n\tIgnoredPaths Set\n}\n\n\n\n\nfunc (p PathFilter) ShouldCompress(r *http.Request) bool {\n\treturn !p.IgnoredPaths.ContainsFunc(func(value string) bool {\n\t\treturn middleware.Path(r.URL.Path).Matches(value)\n\t})\n}\n\n\ntype Set map[string]struct{}\n\n\nfunc (s Set) Add(value string) {\n\ts[value] = struct{}{}\n}\n\n\n\n\n\nfunc (s Set) Contains(value string) bool {\n\t_, ok := s[value]\n\treturn ok\n}\n\n\n\n\nfunc (s Set) ContainsFunc(f func(string) bool) bool {\n\tfor k, _ := range s {\n\t\tif f(k) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (s Set) Remove(value string) ", "output": "{\n\tdelete(s, value)\n}"} {"input": "\n\nfunc combine(n int, k int) [][]int {\n var result [][]int\n backtrack(1, []int{}, n, k, &result)\n return result\n}\n\nfunc backtrack(start int, current []int, n, k int, result *[][]int) ", "output": "{\n if len(current) == k {\n currentCopy := make([]int, len(current))\n copy(currentCopy, current)\n *result = append(*result, currentCopy)\n return\n }\n if start > n {\n return\n }\n for i := start; i <= n; i++ {\n current = append(current, i) \n backtrack(i+1, current, n, k, result)\n current = current[0:len(current)-1]\n }\n}"} {"input": "package instructions\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/bongo227/goory/types\"\n\n\t\"github.com/bongo227/goory/value\"\n)\n\n\ntype CondBr struct {\n\tblock value.Value\n\tname string\n\tcondition value.Value\n\ttrueBlock value.Value\n\tfalseBlock value.Value\n}\n\nfunc NewCondBr(block value.Value, name string, condition value.Value, trueBlock value.Value, falseBlock value.Value) *CondBr {\n\tif !condition.Type().Equal(types.NewBoolType()) {\n\t\tpanic(\"condition is not a bool type\")\n\t}\n\n\tif !trueBlock.Type().Equal(types.NewBlockType()) {\n\t\tpanic(\"trueBlock is not a block type\")\n\t}\n\n\tif !falseBlock.Type().Equal(types.NewBlockType()) {\n\t\tpanic(\"falseBlock is not a block type\")\n\t}\n\n\treturn &CondBr{block, name, condition, trueBlock, falseBlock}\n}\n\nfunc (i *CondBr) Block() value.Value {\n\treturn i.block\n}\n\n\n\nfunc (i *CondBr) Type() types.Type {\n\treturn types.VOID\n}\n\nfunc (i *CondBr) Ident() string {\n\treturn \"%\" + i.name\n}\n\nfunc (i *CondBr) Llvm() string {\n\treturn fmt.Sprintf(\"br i1 %s, label %%%s, label %%%s\",\n\t\ti.condition.Ident(),\n\t\ti.trueBlock.Ident(),\n\t\ti.falseBlock.Ident())\n}\n\nfunc (i *CondBr) IsTerminator() bool ", "output": "{\n\treturn true\n}"} {"input": "package rpm\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"io\"\n)\n\n\nvar ErrNotRPMFile = errorf(\"invalid file descriptor\")\n\n\n\ntype Lead struct {\n\tVersionMajor int\n\tVersionMinor int\n\tName string\n\tType int\n\tArchitecture int\n\tOperatingSystem int\n\tSignatureType int\n}\n\ntype leadBytes [96]byte\n\nfunc (c leadBytes) Magic() []byte { return c[:4] }\nfunc (c leadBytes) VersionMajor() int { return int(c[4]) }\nfunc (c leadBytes) VersionMinor() int { return int(c[5]) }\nfunc (c leadBytes) Type() int { return int(binary.BigEndian.Uint16(c[6:8])) }\nfunc (c leadBytes) Architecture() int { return int(binary.BigEndian.Uint16(c[8:10])) }\nfunc (c leadBytes) Name() string { return string(c[10:76]) }\nfunc (c leadBytes) OperatingSystem() int { return int(binary.BigEndian.Uint16(c[76:78])) }\nfunc (c leadBytes) SignatureType() int { return int(binary.BigEndian.Uint16(c[78:80])) }\n\n\n\n\n\nfunc readLead(r io.Reader) (*Lead, error) ", "output": "{\n\tvar lead leadBytes\n\t_, err := io.ReadFull(r, lead[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !bytes.Equal(lead.Magic(), []byte{0xED, 0xAB, 0xEE, 0xDB}) {\n\t\treturn nil, ErrNotRPMFile\n\t}\n\tif lead.VersionMajor() < 3 || lead.VersionMajor() > 4 {\n\t\treturn nil, errorf(\"unsupported rpm version: %d\", lead.VersionMajor())\n\t}\n\treturn &Lead{\n\t\tVersionMajor: lead.VersionMajor(),\n\t\tVersionMinor: lead.VersionMinor(),\n\t\tType: lead.Type(),\n\t\tArchitecture: lead.Architecture(),\n\t\tName: lead.Name(),\n\t\tOperatingSystem: lead.OperatingSystem(),\n\t\tSignatureType: lead.SignatureType(),\n\t}, nil\n}"} {"input": "package backend\n\nimport (\n\t\"sync\"\n\n\t\"github.com/docker/infrakit/pkg/run/scope\"\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/pflag\"\n)\n\n\ntype ExecFunc func(script string, cmd *cobra.Command, args []string) error\n\n\ntype FlagsFunc func(*pflag.FlagSet)\n\n\ntype TemplateFunc func(scope scope.Scope, trial bool, opt ...interface{}) (ExecFunc, error)\n\nvar (\n\tbackends = map[string]TemplateFunc{}\n\tflags = map[string]FlagsFunc{}\n\tlock = sync.Mutex{}\n)\n\n\n\nfunc Register(funcName string, backend TemplateFunc, buildFlags FlagsFunc) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tbackends[funcName] = backend\n\tflags[funcName] = buildFlags\n}\n\n\n\n\n\n\nfunc VisitFlags(visitor func(string, FlagsFunc)) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tfor funcName, f := range flags {\n\t\tvisitor(funcName, f)\n\t}\n}\n\nfunc Visit(visitor func(funcName string, backend TemplateFunc)) ", "output": "{\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tfor funcName, backend := range backends {\n\t\tvisitor(funcName, backend)\n\t}\n}"} {"input": "package bit\n\nimport (\n\t\"image\"\n)\n\nfunc (img *Image) Mozaic(n int) Image {\n\tgrayimg := img.Gray()\n\tbounds := grayimg.Bounds()\n\n\tymax := (bounds.Max.Y / n) * bounds.Max.Y\n\txmax := (bounds.Max.X / n) * bounds.Max.X\n\n\trectangle := image.Rect(0, 0, xmax, ymax)\n\tnewimg := image.NewRGBA(rectangle)\n\n\tpoint := image.Point{0, 0}\n\n\tfor y := 0; y < bounds.Max.Y; y += n {\n\t\tfor x := 0; x < bounds.Max.X; x += n {\n\t\t\tavgcol := img.AverageColor(image.Point{x, y}, n)\n\t\t\tavgimg := grayimg.And(avgcol)\n\n\t\t\timagefill(&avgimg, newimg, point)\n\n\t\t\tpoint.X += bounds.Max.X\n\t\t}\n\t\tpoint.X = 0\n\t\tpoint.Y += bounds.Max.Y\n\t}\n\n\treturn Image{newimg}\n}\n\n\n\nfunc imagefill(src *Image, dst *image.RGBA, point image.Point) ", "output": "{\n\tbounds := src.Bounds()\n\n\tymax := point.Y + bounds.Max.Y\n\txmax := point.X + bounds.Max.X\n\n\tfor y := point.Y; y < ymax; y++ {\n\t\tfor x := point.X; x < xmax; x++ {\n\t\t\t_x := x % bounds.Max.X\n\t\t\t_y := y % bounds.Max.Y\n\n\t\t\tcol := src.At(_x, _y)\n\n\t\t\tdst.Set(x, y, col)\n\t\t}\n\t}\n}"} {"input": "package testing\n\nimport (\n\tnodev1 \"k8s.io/api/node/v1\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\tclientset \"k8s.io/client-go/kubernetes\"\n\t\"k8s.io/client-go/kubernetes/fake\"\n\t\"k8s.io/kubernetes/pkg/kubelet/runtimeclass\"\n)\n\nconst (\n\tSandboxRuntimeClass = \"sandbox\"\n\tSandboxRuntimeHandler = \"kata-containers\"\n\n\tEmptyRuntimeClass = \"native\"\n)\n\n\n\nfunc NewPopulatedClient() clientset.Interface {\n\treturn fake.NewSimpleClientset(\n\t\tNewRuntimeClass(EmptyRuntimeClass, \"\"),\n\t\tNewRuntimeClass(SandboxRuntimeClass, SandboxRuntimeHandler),\n\t)\n}\n\n\n\n\n\n\n\n\nfunc NewRuntimeClass(name, handler string) *nodev1.RuntimeClass {\n\treturn &nodev1.RuntimeClass{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t},\n\t\tHandler: handler,\n\t}\n}\n\nfunc StartManagerSync(m *runtimeclass.Manager) func() ", "output": "{\n\tstopCh := make(chan struct{})\n\tm.Start(stopCh)\n\tm.WaitForCacheSync(stopCh)\n\treturn func() {\n\t\tclose(stopCh)\n\t}\n}"} {"input": "package chipecs\n\nimport (\n\t\"log\"\n\n\t\"engo.io/ecs\"\n\t\"engo.io/engo\"\n\t\"engo.io/engo/common\"\n\t\"github.com/vova616/chipmunk\"\n\t\"github.com/vova616/chipmunk/vect\"\n)\n\n\n\nfunc (ps *PhysicsSystem) Remove(basic ecs.BasicEntity) {\n\tdelete := -1\n\tfor index, e := range ps.entities {\n\t\tif e.BasicEntity.ID() == basic.ID() {\n\t\t\tdelete = index\n\t\t\tps.Space.RemoveBody(e.Shape.Body)\n\t\t\tbreak\n\t\t}\n\t}\n\tif delete >= 0 {\n\t\tps.entities = append(ps.entities[:delete], ps.entities[delete+1:]...)\n\t}\n}\n\n\nfunc (ps *PhysicsSystem) New(*ecs.World) {\n\tlog.Println(\"PhyiscsSystem was added to the scene.\")\n\tps.Space = chipmunk.NewSpace()\n\tps.Space.Gravity = vect.Vect{X: 0, Y: 0}\n}\n\n\nfunc (ps *PhysicsSystem) Update(dt float32) {\n\tfor _, e := range ps.entities {\n\t\tpos := e.PhysicsComponent.Shape.Body.Position()\n\t\te.Position = engo.Point{X: float32(pos.X), Y: float32(pos.Y)}\n\t\te.Rotation = 0 \n\t}\n\tps.Space.Step(vect.Float(dt))\n}\n\n\n\n\nfunc (ps *PhysicsSystem) Add(basic *ecs.BasicEntity, physics *PhysicsComponent, space *common.SpaceComponent) ", "output": "{\n\tps.entities = append(ps.entities, physicsEntity{basic, physics, space})\n\tps.Space.AddBody(physics.Shape.Body)\n}"} {"input": "package client\n\nimport (\n\t\"context\"\n\t\"strconv\"\n\n\t\"github.com/containerd/containerd/containers\"\n\t\"github.com/containerd/containerd/oci\"\n\tspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n)\n\nconst newLine = \"\\r\\n\"\n\nfunc withExitStatus(es int) oci.SpecOpts {\n\treturn func(_ context.Context, _ oci.Client, _ *containers.Container, s *specs.Spec) error {\n\t\ts.Process.Args = []string{\"cmd\", \"/c\", \"exit\", strconv.Itoa(es)}\n\t\treturn nil\n\t}\n}\n\n\n\nfunc withCat() oci.SpecOpts {\n\treturn oci.WithProcessArgs(\"cmd\", \"/c\", \"more\")\n}\n\nfunc withTrue() oci.SpecOpts {\n\treturn oci.WithProcessArgs(\"cmd\", \"/c\")\n}\n\nfunc withExecExitStatus(s *specs.Process, es int) {\n\ts.Args = []string{\"cmd\", \"/c\", \"exit\", strconv.Itoa(es)}\n}\n\nfunc withExecArgs(s *specs.Process, args ...string) {\n\ts.Args = append([]string{\"cmd\", \"/c\"}, args...)\n}\n\nfunc withProcessArgs(args ...string) oci.SpecOpts ", "output": "{\n\treturn oci.WithProcessArgs(append([]string{\"cmd\", \"/c\"}, args...)...)\n}"} {"input": "package fake\n\nimport (\n\tclientset \"github.com/openshift/client-go/oauth/clientset/versioned\"\n\toauthv1 \"github.com/openshift/client-go/oauth/clientset/versioned/typed/oauth/v1\"\n\tfakeoauthv1 \"github.com/openshift/client-go/oauth/clientset/versioned/typed/oauth/v1/fake\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apimachinery/pkg/watch\"\n\t\"k8s.io/client-go/discovery\"\n\tfakediscovery \"k8s.io/client-go/discovery/fake\"\n\t\"k8s.io/client-go/testing\"\n)\n\n\n\n\n\nfunc NewSimpleClientset(objects ...runtime.Object) *Clientset {\n\to := testing.NewObjectTracker(scheme, codecs.UniversalDecoder())\n\tfor _, obj := range objects {\n\t\tif err := o.Add(obj); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tfakePtr := testing.Fake{}\n\tfakePtr.AddReactor(\"*\", \"*\", testing.ObjectReaction(o))\n\tfakePtr.AddWatchReactor(\"*\", testing.DefaultWatchReactor(watch.NewFake(), nil))\n\n\treturn &Clientset{fakePtr, &fakediscovery.FakeDiscovery{Fake: &fakePtr}}\n}\n\n\n\n\ntype Clientset struct {\n\ttesting.Fake\n\tdiscovery *fakediscovery.FakeDiscovery\n}\n\n\n\nvar _ clientset.Interface = &Clientset{}\n\n\nfunc (c *Clientset) OauthV1() oauthv1.OauthV1Interface {\n\treturn &fakeoauthv1.FakeOauthV1{Fake: &c.Fake}\n}\n\n\nfunc (c *Clientset) Oauth() oauthv1.OauthV1Interface {\n\treturn &fakeoauthv1.FakeOauthV1{Fake: &c.Fake}\n}\n\nfunc (c *Clientset) Discovery() discovery.DiscoveryInterface ", "output": "{\n\treturn c.discovery\n}"} {"input": "package dao\n\nimport (\n\t\"context\"\n\n\t\"go-common/library/cache/redis\"\n\t\"go-common/library/log\"\n)\n\nconst (\n\t_taskJobKey = \"task_job\"\n)\n\n\nfunc (d *Dao) SetnxTaskJob(c context.Context, value string) (ok bool, err error) {\n\tvar (\n\t\tconn = d.dmRds.Get(c)\n\t)\n\tdefer conn.Close()\n\tif ok, err = redis.Bool(conn.Do(\"SETNX\", _taskJobKey, value)); err != nil {\n\t\tlog.Error(\"d.SetnxMask(value:%s),error(%v)\", value, err)\n\t\treturn\n\t}\n\treturn\n}\n\n\nfunc (d *Dao) GetTaskJob(c context.Context) (value string, err error) {\n\tvar (\n\t\tconn = d.dmRds.Get(c)\n\t)\n\tdefer conn.Close()\n\tif value, err = redis.String(conn.Do(\"GET\", _taskJobKey)); err != nil {\n\t\tlog.Error(\"d.GetMaskJob,error(%v)\", err)\n\t\treturn\n\t}\n\treturn\n}\n\n\n\n\n\nfunc (d *Dao) DelTaskJob(c context.Context) (err error) {\n\tvar (\n\t\tconn = d.dmRds.Get(c)\n\t)\n\tdefer conn.Close()\n\tif _, err = conn.Do(\"DEL\", _taskJobKey); err != nil {\n\t\tlog.Error(\"d.DelTaskJob,error(%v)\", err)\n\t\treturn\n\t}\n\treturn\n}\n\nfunc (d *Dao) GetSetTaskJob(c context.Context, value string) (old string, err error) ", "output": "{\n\tvar (\n\t\tconn = d.dmRds.Get(c)\n\t)\n\tdefer conn.Close()\n\tif old, err = redis.String(conn.Do(\"GETSET\", _taskJobKey, value)); err != nil {\n\t\tlog.Error(\"d.GetSetTaskJob(value:%s),error(%v)\", value, err)\n\t\treturn\n\t}\n\treturn\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/strfmt\"\n\t\"github.com/go-openapi/validate\"\n)\n\n\n\n\n\ntype RdmaProtocol string\n\nconst (\n\n\tRdmaProtocolRoce RdmaProtocol = \"roce\"\n)\n\n\nvar rdmaProtocolEnum []interface{}\n\nfunc init() {\n\tvar res []RdmaProtocol\n\tif err := json.Unmarshal([]byte(`[\"roce\"]`), &res); err != nil {\n\t\tpanic(err)\n\t}\n\tfor _, v := range res {\n\t\trdmaProtocolEnum = append(rdmaProtocolEnum, v)\n\t}\n}\n\n\n\n\nfunc (m RdmaProtocol) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateRdmaProtocolEnum(\"\", \"body\", m); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\n\nfunc (m RdmaProtocol) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}\n\nfunc (m RdmaProtocol) validateRdmaProtocolEnum(path, location string, value RdmaProtocol) error ", "output": "{\n\tif err := validate.EnumCase(path, location, value, rdmaProtocolEnum, true); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}"} {"input": "package handlers\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\n\t\"github.com/cloudfoundry-incubator/rep\"\n\t\"github.com/pivotal-golang/lager\"\n)\n\ntype perform struct {\n\trep rep.AuctionCellClient\n\tlogger lager.Logger\n}\n\n\n\nfunc (h *perform) ServeHTTP(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tlogger := h.logger.Session(\"auction-perform-work\")\n\tlogger.Info(\"handling\")\n\n\tvar work rep.Work\n\terr := json.NewDecoder(r.Body).Decode(&work)\n\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tlogger.Error(\"failed-to-unmarshal\", err)\n\t\treturn\n\t}\n\n\tfailedWork, err := h.rep.Perform(work)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tlogger.Error(\"failed-to-perform-work\", err)\n\t\treturn\n\t}\n\n\tjson.NewEncoder(w).Encode(failedWork)\n\tlogger.Info(\"success\")\n}"} {"input": "package get\n\n\n\n\nimport (\n\t\"time\"\n\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/runtime\"\n\tcr \"github.com/go-openapi/runtime/client\"\n\n\tstrfmt \"github.com/go-openapi/strfmt\"\n)\n\n\n\n\n\n\n\nfunc NewGetPollersIdentifierDataParamsWithTimeout(timeout time.Duration) *GetPollersIdentifierDataParams {\n\tvar ()\n\treturn &GetPollersIdentifierDataParams{\n\n\t\ttimeout: timeout,\n\t}\n}\n\n\ntype GetPollersIdentifierDataParams struct {\n\n\tIdentifier string\n\n\ttimeout time.Duration\n}\n\n\nfunc (o *GetPollersIdentifierDataParams) WithIdentifier(identifier string) *GetPollersIdentifierDataParams {\n\to.Identifier = identifier\n\treturn o\n}\n\n\nfunc (o *GetPollersIdentifierDataParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tr.SetTimeout(o.timeout)\n\tvar res []error\n\n\tif err := r.SetPathParam(\"identifier\", o.Identifier); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc NewGetPollersIdentifierDataParams() *GetPollersIdentifierDataParams ", "output": "{\n\tvar ()\n\treturn &GetPollersIdentifierDataParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}"} {"input": "package tcplisten\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n)\n\nconst (\n\tsoReusePort = 0x0F\n\ttcpFastOpen = 0x17\n)\n\nfunc enableDeferAccept(fd int) error {\n\tif err := syscall.SetsockoptInt(fd, syscall.IPPROTO_TCP, syscall.TCP_DEFER_ACCEPT, 1); err != nil {\n\t\treturn fmt.Errorf(\"cannot enable TCP_DEFER_ACCEPT: %s\", err)\n\t}\n\treturn nil\n}\n\n\n\nconst fastOpenQlen = 16 * 1024\n\nfunc soMaxConn() (int, error) {\n\tdata, err := ioutil.ReadFile(soMaxConnFilePath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn syscall.SOMAXCONN, nil\n\t\t}\n\t\treturn -1, err\n\t}\n\ts := strings.TrimSpace(string(data))\n\tn, err := strconv.Atoi(s)\n\tif err != nil || n <= 0 {\n\t\treturn -1, fmt.Errorf(\"cannot parse somaxconn %q read from %s: %s\", s, soMaxConnFilePath, err)\n\t}\n\n\tif n > 1<<16-1 {\n\t\tn = 1<<16 - 1\n\t}\n\treturn n, nil\n}\n\nconst soMaxConnFilePath = \"/proc/sys/net/core/somaxconn\"\n\nfunc enableFastOpen(fd int) error ", "output": "{\n\tif err := syscall.SetsockoptInt(fd, syscall.SOL_TCP, tcpFastOpen, fastOpenQlen); err != nil {\n\t\treturn fmt.Errorf(\"cannot enable TCP_FASTOPEN(qlen=%d): %s\", fastOpenQlen, err)\n\t}\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com/asticode/go-logger/logger\"\n\t\"github.com/asticode/go-stopwatch/stopwatch\"\n\textendederror \"github.com/asticode/go-toolbox/error\"\n\t_ \"github.com/asticode/go-keyboardemulator/keyboardemulator\"\n\t_ \"os/exec\"\n\t\"github.com/asticode/go-texttospeech/texttospeech\"\n)\n\nfunc main() {\n\tdefer extendederror.Catch(catchPrepare, map[string]interface{}{})\n\n\tconfigPath := flag.String(\"config\", \"\", \"Path to the local configuration file\")\n\tflag.Parse()\n\n\tprepare(*configPath)\n}\n\nfunc catchPrepare(err interface{}, args map[string]interface{}) {\n\tfmt.Println(\"CRITICAL: \" + extendederror.ParseError(err))\n}\n\n\n\nfunc catchRun(err interface{}, args map[string]interface{}) {\n\tl := args[\"logger\"].(logger.Logger)\n\n\tl.Critical(extendederror.ParseError(err))\n}\n\nfunc run(c configuration, l logger.Logger) {\n\tsw := stopwatch.NewStopwatchFromConfiguration(c.StopWatch).SetIsEnabled(true)\n\tsw.AddEvent(\"Init\", \"Stopwatch has been created\")\n\n\n\n\ttts := texttospeech.NewTextToSpeech()\n\n\ttts.Say(\"Good morning sir, how may I help you today?\")\n\n\n\tl.Info(\"Done\")\n}\n\nfunc prepare(configPath string) ", "output": "{\n\tc := newConfiguration(configPath)\n\n\tl, err := logger.NewLoggerFromConfiguration(c.Logger)\n\textendederror.ProcessError(err)\n\n\tdefer extendederror.Catch(catchRun, map[string]interface{}{\n\t\t\"logger\": l,\n\t})\n\trun(*c, l)\n}"}